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/Target/TargetOptions.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(numSubJoins , "Number of subclass joins performed");
40 STATISTIC(numCommutes , "Number of instruction commuting performed");
41 STATISTIC(numExtends , "Number of copies extended");
42 STATISTIC(NumReMats , "Number of instructions re-materialized");
43 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
44 STATISTIC(numAborts , "Number of times interval joining aborted");
46 char SimpleRegisterCoalescing::ID = 0;
48 EnableJoining("join-liveintervals",
49 cl::desc("Coalesce copies (default=true)"),
53 NewHeuristic("new-coalescer-heuristic",
54 cl::desc("Use new coalescer heuristic"),
55 cl::init(false), cl::Hidden);
58 CrossClassJoin("join-subclass-copies",
59 cl::desc("Coalesce copies to sub- register class"),
60 cl::init(false), cl::Hidden);
62 static RegisterPass<SimpleRegisterCoalescing>
63 X("simple-register-coalescing", "Simple Register Coalescing");
65 // Declare that we implement the RegisterCoalescer interface
66 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
68 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
70 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<LiveIntervals>();
72 AU.addPreserved<LiveIntervals>();
73 AU.addRequired<MachineLoopInfo>();
74 AU.addPreserved<MachineLoopInfo>();
75 AU.addPreservedID(MachineDominatorsID);
77 AU.addPreservedID(StrongPHIEliminationID);
79 AU.addPreservedID(PHIEliminationID);
80 AU.addPreservedID(TwoAddressInstructionPassID);
81 MachineFunctionPass::getAnalysisUsage(AU);
84 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
85 /// being the source and IntB being the dest, thus this defines a value number
86 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
87 /// see if we can merge these two pieces of B into a single value number,
88 /// eliminating a copy. For example:
92 /// B1 = A3 <- this copy
94 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
95 /// value number to be replaced with B0 (which simplifies the B liveinterval).
97 /// This returns true if an interval was modified.
99 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
101 MachineInstr *CopyMI) {
102 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
104 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
105 // the example above.
106 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
107 if (BLR == IntB.end()) // Should never happen!
109 VNInfo *BValNo = BLR->valno;
111 // Get the location that B is defined at. Two options: either this value has
112 // an unknown definition point or it is defined at CopyIdx. If unknown, we
114 if (!BValNo->copy) return false;
115 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
117 // AValNo is the value number in A that defines the copy, A3 in the example.
118 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
119 if (ALR == IntA.end()) // Should never happen!
121 VNInfo *AValNo = ALR->valno;
122 // If it's re-defined by an early clobber somewhere in the live range, then
123 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
125 // 172 %ECX<def> = MOV32rr %reg1039<kill>
126 // 180 INLINEASM <es:subl $5,$1
127 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
128 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
129 // 188 %EAX<def> = MOV32rr %EAX<kill>
130 // 196 %ECX<def> = MOV32rr %ECX<kill>
131 // 204 %ECX<def> = MOV32rr %ECX<kill>
132 // 212 %EAX<def> = MOV32rr %EAX<kill>
133 // 220 %EAX<def> = MOV32rr %EAX
134 // 228 %reg1039<def> = MOV32rr %ECX<kill>
135 // The early clobber operand ties ECX input to the ECX def.
137 // The live interval of ECX is represented as this:
138 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
139 // The coalescer has no idea there was a def in the middle of [174,230].
140 if (AValNo->redefByEC)
143 // If AValNo is defined as a copy from IntB, we can potentially process this.
144 // Get the instruction that defines this value number.
145 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
146 if (!SrcReg) return false; // Not defined by a copy.
148 // If the value number is not defined by a copy instruction, ignore it.
150 // If the source register comes from an interval other than IntB, we can't
152 if (SrcReg != IntB.reg) return false;
154 // Get the LiveRange in IntB that this value number starts with.
155 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
156 if (ValLR == IntB.end()) // Should never happen!
159 // Make sure that the end of the live range is inside the same block as
161 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
163 ValLREndInst->getParent() != CopyMI->getParent()) return false;
165 // Okay, we now know that ValLR ends in the same block that the CopyMI
166 // live-range starts. If there are no intervening live ranges between them in
167 // IntB, we can merge them.
168 if (ValLR+1 != BLR) return false;
170 // If a live interval is a physical register, conservatively check if any
171 // of its sub-registers is overlapping the live interval of the virtual
172 // register. If so, do not coalesce.
173 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
174 *tri_->getSubRegisters(IntB.reg)) {
175 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
176 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
177 DOUT << "Interfere with sub-register ";
178 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
183 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
185 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
186 // We are about to delete CopyMI, so need to remove it as the 'instruction
187 // that defines this value #'. Update the the valnum with the new defining
189 BValNo->def = FillerStart;
192 // Okay, we can merge them. We need to insert a new liverange:
193 // [ValLR.end, BLR.begin) of either value number, then we merge the
194 // two value numbers.
195 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
197 // If the IntB live range is assigned to a physical register, and if that
198 // physreg has aliases,
199 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
200 // Update the liveintervals of sub-registers.
201 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
202 LiveInterval &AliasLI = li_->getInterval(*AS);
203 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
204 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
208 // Okay, merge "B1" into the same value number as "B0".
209 if (BValNo != ValLR->valno) {
210 IntB.addKills(ValLR->valno, BValNo->kills);
211 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
213 DOUT << " result = "; IntB.print(DOUT, tri_);
216 // If the source instruction was killing the source register before the
217 // merge, unset the isKill marker given the live range has been extended.
218 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
220 ValLREndInst->getOperand(UIdx).setIsKill(false);
221 IntB.removeKill(ValLR->valno, FillerStart);
228 /// HasOtherReachingDefs - Return true if there are definitions of IntB
229 /// other than BValNo val# that can reach uses of AValno val# of IntA.
230 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
234 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
236 if (AI->valno != AValNo) continue;
237 LiveInterval::Ranges::iterator BI =
238 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
239 if (BI != IntB.ranges.begin())
241 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
242 if (BI->valno == BValNo)
244 if (BI->start <= AI->start && BI->end > AI->start)
246 if (BI->start > AI->start && BI->start < AI->end)
253 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
254 /// being the source and IntB being the dest, thus this defines a value number
255 /// in IntB. If the source value number (in IntA) is defined by a commutable
256 /// instruction and its other operand is coalesced to the copy dest register,
257 /// see if we can transform the copy into a noop by commuting the definition. For
260 /// A3 = op A2 B0<kill>
262 /// B1 = A3 <- this copy
264 /// = op A3 <- more uses
268 /// B2 = op B0 A2<kill>
270 /// B1 = B2 <- now an identify copy
272 /// = op B2 <- more uses
274 /// This returns true if an interval was modified.
276 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
278 MachineInstr *CopyMI) {
279 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
281 // FIXME: For now, only eliminate the copy by commuting its def when the
282 // source register is a virtual register. We want to guard against cases
283 // where the copy is a back edge copy and commuting the def lengthen the
284 // live interval of the source register to the entire loop.
285 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
288 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
289 // the example above.
290 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
291 if (BLR == IntB.end()) // Should never happen!
293 VNInfo *BValNo = BLR->valno;
295 // Get the location that B is defined at. Two options: either this value has
296 // an unknown definition point or it is defined at CopyIdx. If unknown, we
298 if (!BValNo->copy) return false;
299 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
301 // AValNo is the value number in A that defines the copy, A3 in the example.
302 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
303 if (ALR == IntA.end()) // Should never happen!
305 VNInfo *AValNo = ALR->valno;
306 // If other defs can reach uses of this def, then it's not safe to perform
308 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
310 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
311 const TargetInstrDesc &TID = DefMI->getDesc();
313 if (!TID.isCommutable() ||
314 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
317 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
318 unsigned NewReg = NewDstMO.getReg();
319 if (NewReg != IntB.reg || !NewDstMO.isKill())
322 // Make sure there are no other definitions of IntB that would reach the
323 // uses which the new definition can reach.
324 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
327 // If some of the uses of IntA.reg is already coalesced away, return false.
328 // It's not possible to determine whether it's safe to perform the coalescing.
329 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
330 UE = mri_->use_end(); UI != UE; ++UI) {
331 MachineInstr *UseMI = &*UI;
332 unsigned UseIdx = li_->getInstructionIndex(UseMI);
333 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
334 if (ULR == IntA.end())
336 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
340 // At this point we have decided that it is legal to do this
341 // transformation. Start by commuting the instruction.
342 MachineBasicBlock *MBB = DefMI->getParent();
343 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
346 if (NewMI != DefMI) {
347 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
348 MBB->insert(DefMI, NewMI);
351 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
352 NewMI->getOperand(OpIdx).setIsKill();
354 bool BHasPHIKill = BValNo->hasPHIKill;
355 SmallVector<VNInfo*, 4> BDeadValNos;
356 SmallVector<unsigned, 4> BKills;
357 std::map<unsigned, unsigned> BExtend;
359 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
368 // then do not add kills of A to the newly created B interval.
369 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
371 BExtend[ALR->end] = BLR->end;
373 // Update uses of IntA of the specific Val# with IntB.
374 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
375 UE = mri_->use_end(); UI != UE;) {
376 MachineOperand &UseMO = UI.getOperand();
377 MachineInstr *UseMI = &*UI;
379 if (JoinedCopies.count(UseMI))
381 unsigned UseIdx = li_->getInstructionIndex(UseMI);
382 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
383 if (ULR == IntA.end() || ULR->valno != AValNo)
385 UseMO.setReg(NewReg);
388 if (UseMO.isKill()) {
390 UseMO.setIsKill(false);
392 BKills.push_back(li_->getUseIndex(UseIdx)+1);
394 unsigned SrcReg, DstReg;
395 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
397 if (DstReg == IntB.reg) {
398 // This copy will become a noop. If it's defining a new val#,
399 // remove that val# as well. However this live range is being
400 // extended to the end of the existing live range defined by the copy.
401 unsigned DefIdx = li_->getDefIndex(UseIdx);
402 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
403 BHasPHIKill |= DLR->valno->hasPHIKill;
404 assert(DLR->valno->def == DefIdx);
405 BDeadValNos.push_back(DLR->valno);
406 BExtend[DLR->start] = DLR->end;
407 JoinedCopies.insert(UseMI);
408 // If this is a kill but it's going to be removed, the last use
409 // of the same val# is the new kill.
415 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
416 // simply extend BLR if CopyMI doesn't end the range.
417 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
419 // Remove val#'s defined by copies that will be coalesced away.
420 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
421 IntB.removeValNo(BDeadValNos[i]);
423 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
424 // is updated. Kills are also updated.
425 VNInfo *ValNo = BValNo;
426 ValNo->def = AValNo->def;
428 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
429 unsigned Kill = ValNo->kills[j];
430 if (Kill != BLR->end)
431 BKills.push_back(Kill);
433 ValNo->kills.clear();
434 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
436 if (AI->valno != AValNo) continue;
437 unsigned End = AI->end;
438 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
439 if (EI != BExtend.end())
441 IntB.addRange(LiveRange(AI->start, End, ValNo));
443 IntB.addKills(ValNo, BKills);
444 ValNo->hasPHIKill = BHasPHIKill;
446 DOUT << " result = "; IntB.print(DOUT, tri_);
449 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
450 IntA.removeValNo(AValNo);
451 DOUT << " result = "; IntA.print(DOUT, tri_);
458 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
459 /// computation, replace the copy by rematerialize the definition.
460 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
462 MachineInstr *CopyMI) {
463 unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
464 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
465 if (SrcLR == SrcInt.end()) // Should never happen!
467 VNInfo *ValNo = SrcLR->valno;
468 // If other defs can reach uses of this def, then it's not safe to perform
470 if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
472 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
473 const TargetInstrDesc &TID = DefMI->getDesc();
474 if (!TID.isAsCheapAsAMove())
476 bool SawStore = false;
477 if (!DefMI->isSafeToMove(tii_, SawStore))
480 unsigned DefIdx = li_->getDefIndex(CopyIdx);
481 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
482 DLR->valno->copy = NULL;
483 // Don't forget to update sub-register intervals.
484 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
485 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
486 if (!li_->hasInterval(*SR))
488 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
489 if (DLR && DLR->valno->copy == CopyMI)
490 DLR->valno->copy = NULL;
494 MachineBasicBlock *MBB = CopyMI->getParent();
495 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
496 CopyMI->removeFromParent();
497 tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
498 MachineInstr *NewMI = prior(MII);
499 // CopyMI may have implicit operands, transfer them over to the newly
500 // rematerialized instruction. And update implicit def interval valnos.
501 for (unsigned i = CopyMI->getDesc().getNumOperands(),
502 e = CopyMI->getNumOperands(); i != e; ++i) {
503 MachineOperand &MO = CopyMI->getOperand(i);
504 if (MO.isReg() && MO.isImplicit())
505 NewMI->addOperand(MO);
506 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
507 unsigned Reg = MO.getReg();
508 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
509 if (DLR && DLR->valno->copy == CopyMI)
510 DLR->valno->copy = NULL;
514 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
515 MBB->getParent()->DeleteMachineInstr(CopyMI);
516 ReMatCopies.insert(CopyMI);
517 ReMatDefs.insert(DefMI);
522 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
524 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
525 unsigned DstReg) const {
526 MachineBasicBlock *MBB = CopyMI->getParent();
527 const MachineLoop *L = loopInfo->getLoopFor(MBB);
530 if (MBB != L->getLoopLatch())
533 LiveInterval &LI = li_->getInterval(DstReg);
534 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
535 LiveInterval::const_iterator DstLR =
536 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
537 if (DstLR == LI.end())
539 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
540 if (DstLR->valno->kills.size() == 1 &&
541 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
546 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
547 /// update the subregister number if it is not zero. If DstReg is a
548 /// physical register and the existing subregister number of the def / use
549 /// being updated is not zero, make sure to set it to the correct physical
552 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
554 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
555 if (DstIsPhys && SubIdx) {
556 // Figure out the real physical register we are updating with.
557 DstReg = tri_->getSubReg(DstReg, SubIdx);
561 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
562 E = mri_->reg_end(); I != E; ) {
563 MachineOperand &O = I.getOperand();
564 MachineInstr *UseMI = &*I;
566 unsigned OldSubIdx = O.getSubReg();
568 unsigned UseDstReg = DstReg;
570 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
572 unsigned CopySrcReg, CopyDstReg;
573 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg) &&
574 CopySrcReg != CopyDstReg &&
575 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
576 // If the use is a copy and it won't be coalesced away, and its source
577 // is defined by a trivial computation, try to rematerialize it instead.
578 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
587 // Sub-register indexes goes from small to large. e.g.
588 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
589 // EAX: 1 -> AL, 2 -> AX
590 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
591 // sub-register 2 is also AX.
592 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
593 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
596 // Remove would-be duplicated kill marker.
597 if (O.isKill() && UseMI->killsRegister(DstReg))
601 // After updating the operand, check if the machine instruction has
602 // become a copy. If so, update its val# information.
603 const TargetInstrDesc &TID = UseMI->getDesc();
604 unsigned CopySrcReg, CopyDstReg;
605 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
606 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg) &&
607 CopySrcReg != CopyDstReg &&
608 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
609 allocatableRegs_[CopyDstReg])) {
610 LiveInterval &LI = li_->getInterval(CopyDstReg);
611 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
612 const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx);
613 if (DLR->valno->def == DefIdx)
614 DLR->valno->copy = UseMI;
619 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
620 /// registers due to insert_subreg coalescing. e.g.
622 /// r1025 = implicit_def
623 /// r1025 = insert_subreg r1025, r1024
627 /// r1025 = implicit_def
628 /// r1025 = insert_subreg r1025, r1025
631 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
632 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
633 E = mri_->reg_end(); I != E; ) {
634 MachineOperand &O = I.getOperand();
635 MachineInstr *DefMI = &*I;
639 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
641 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
643 li_->RemoveMachineInstrFromMaps(DefMI);
644 DefMI->eraseFromParent();
648 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
649 /// due to live range lengthening as the result of coalescing.
650 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
652 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
653 UE = mri_->use_end(); UI != UE; ++UI) {
654 MachineOperand &UseMO = UI.getOperand();
655 if (UseMO.isKill()) {
656 MachineInstr *UseMI = UseMO.getParent();
657 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
658 if (JoinedCopies.count(UseMI))
660 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
661 if (!UI || !LI.isKill(UI->valno, UseIdx+1))
662 UseMO.setIsKill(false);
667 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
668 /// from a physical register live interval as well as from the live intervals
669 /// of its sub-registers.
670 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
671 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
672 li.removeRange(Start, End, true);
673 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
674 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
675 if (!li_->hasInterval(*SR))
677 LiveInterval &sli = li_->getInterval(*SR);
678 unsigned RemoveEnd = Start;
679 while (RemoveEnd != End) {
680 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
683 RemoveEnd = (LR->end < End) ? LR->end : End;
684 sli.removeRange(Start, RemoveEnd, true);
691 /// removeIntervalIfEmpty - Check if the live interval of a physical register
692 /// is empty, if so remove it and also remove the empty intervals of its
693 /// sub-registers. Return true if live interval is removed.
694 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
695 const TargetRegisterInfo *tri_) {
697 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
698 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
699 if (!li_->hasInterval(*SR))
701 LiveInterval &sli = li_->getInterval(*SR);
703 li_->removeInterval(*SR);
705 li_->removeInterval(li.reg);
711 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
712 /// Return true if live interval is removed.
713 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
714 MachineInstr *CopyMI) {
715 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
716 LiveInterval::iterator MLR =
717 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
719 return false; // Already removed by ShortenDeadCopySrcLiveRange.
720 unsigned RemoveStart = MLR->start;
721 unsigned RemoveEnd = MLR->end;
722 // Remove the liverange that's defined by this.
723 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
724 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
725 return removeIntervalIfEmpty(li, li_, tri_);
730 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
731 /// the val# it defines. If the live interval becomes empty, remove it as well.
732 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
733 MachineInstr *DefMI) {
734 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
735 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
736 if (DefIdx != MLR->valno->def)
738 li.removeValNo(MLR->valno);
739 return removeIntervalIfEmpty(li, li_, tri_);
742 /// PropagateDeadness - Propagate the dead marker to the instruction which
743 /// defines the val#.
744 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
745 unsigned &LRStart, LiveIntervals *li_,
746 const TargetRegisterInfo* tri_) {
747 MachineInstr *DefMI =
748 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
749 if (DefMI && DefMI != CopyMI) {
750 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
752 DefMI->getOperand(DeadIdx).setIsDead();
753 // A dead def should have a single cycle interval.
759 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
760 /// fallthoughs to SuccMBB.
761 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
762 MachineBasicBlock *SuccMBB,
763 const TargetInstrInfo *tii_) {
766 MachineBasicBlock *TBB = 0, *FBB = 0;
767 SmallVector<MachineOperand, 4> Cond;
768 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
769 MBB->isSuccessor(SuccMBB);
772 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
773 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
774 /// ends the live range there. If there isn't another use, then this live range
775 /// is dead. Return true if live interval is removed.
777 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
778 MachineInstr *CopyMI) {
779 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
781 // FIXME: special case: function live in. It can be a general case if the
782 // first instruction index starts at > 0 value.
783 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
784 // Live-in to the function but dead. Remove it from entry live-in set.
785 if (mf_->begin()->isLiveIn(li.reg))
786 mf_->begin()->removeLiveIn(li.reg);
787 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
788 removeRange(li, LR->start, LR->end, li_, tri_);
789 return removeIntervalIfEmpty(li, li_, tri_);
792 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
794 // Livein but defined by a phi.
797 unsigned RemoveStart = LR->start;
798 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
799 if (LR->end > RemoveEnd)
800 // More uses past this copy? Nothing to do.
803 MachineBasicBlock *CopyMBB = CopyMI->getParent();
804 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
806 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
809 MachineInstr *LastUseMI = LastUse->getParent();
810 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
817 // r1025<dead> = r1024<kill>
818 if (MBBStart < LR->end)
819 removeRange(li, MBBStart, LR->end, li_, tri_);
823 // There are uses before the copy, just shorten the live range to the end
825 LastUse->setIsKill();
826 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
827 unsigned SrcReg, DstReg;
828 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
830 // Last use is itself an identity code.
831 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
832 LastUseMI->getOperand(DeadIdx).setIsDead();
838 if (LR->start <= MBBStart && LR->end > MBBStart) {
839 if (LR->start == 0) {
840 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
841 // Live-in to the function but dead. Remove it from entry live-in set.
842 mf_->begin()->removeLiveIn(li.reg);
844 // FIXME: Shorten intervals in BBs that reaches this BB.
847 if (LR->valno->def == RemoveStart)
848 // If the def MI defines the val#, propagate the dead marker.
849 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
851 removeRange(li, RemoveStart, LR->end, li_, tri_);
852 return removeIntervalIfEmpty(li, li_, tri_);
855 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
856 /// from an implicit def to another register can be coalesced away.
857 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
859 LiveInterval &ImpLi) const{
860 if (!CopyMI->killsRegister(ImpLi.reg))
862 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
863 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
866 if (LR->valno->hasPHIKill)
868 if (LR->valno->def != CopyIdx)
870 // Make sure all of val# uses are copies.
871 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
872 UE = mri_->use_end(); UI != UE;) {
873 MachineInstr *UseMI = &*UI;
875 if (JoinedCopies.count(UseMI))
877 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
878 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
879 if (ULR == li.end() || ULR->valno != LR->valno)
881 // If the use is not a use, then it's not safe to coalesce the move.
882 unsigned SrcReg, DstReg;
883 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
884 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
885 UseMI->getOperand(1).getReg() == li.reg)
894 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
895 /// def and it is being removed. Turn all copies from this value# into
896 /// identity copies so they will be removed.
897 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
899 SmallVector<MachineInstr*, 4> ImpDefs;
900 MachineOperand *LastUse = NULL;
901 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
902 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
903 RE = mri_->reg_end(); RI != RE;) {
904 MachineOperand *MO = &RI.getOperand();
905 MachineInstr *MI = &*RI;
908 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
909 ImpDefs.push_back(MI);
913 if (JoinedCopies.count(MI))
915 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
916 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
917 if (ULR == li.end() || ULR->valno != VNI)
919 // If the use is a copy, turn it into an identity copy.
920 unsigned SrcReg, DstReg;
921 if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
922 // Each use MI may have multiple uses of this register. Change them all.
923 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
924 MachineOperand &MO = MI->getOperand(i);
925 if (MO.isReg() && MO.getReg() == li.reg)
928 JoinedCopies.insert(MI);
929 } else if (UseIdx > LastUseIdx) {
935 LastUse->setIsKill();
937 // Remove dead implicit_def's.
938 while (!ImpDefs.empty()) {
939 MachineInstr *ImpDef = ImpDefs.back();
941 li_->RemoveMachineInstrFromMaps(ImpDef);
942 ImpDef->eraseFromParent();
947 /// getMatchingSuperReg - Return a super-register of the specified register
948 /// Reg so its sub-register of index SubIdx is Reg.
949 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
950 const TargetRegisterClass *RC,
951 const TargetRegisterInfo* TRI) {
952 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
953 unsigned SR = *SRs; ++SRs)
954 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
959 /// isProfitableToCoalesceToSubRC - Given that register class of DstReg is
960 /// a subset of the register class of SrcReg, return true if it's profitable
961 /// to coalesce the two registers.
963 SimpleRegisterCoalescing::isProfitableToCoalesceToSubRC(unsigned SrcReg,
965 MachineBasicBlock *MBB){
969 // First let's make sure all uses are in the same MBB.
970 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(SrcReg),
971 RE = mri_->reg_end(); RI != RE; ++RI) {
972 MachineInstr &MI = *RI;
973 if (MI.getParent() != MBB)
976 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(DstReg),
977 RE = mri_->reg_end(); RI != RE; ++RI) {
978 MachineInstr &MI = *RI;
979 if (MI.getParent() != MBB)
983 // Then make sure the intervals are *short*.
984 LiveInterval &SrcInt = li_->getInterval(SrcReg);
985 LiveInterval &DstInt = li_->getInterval(DstReg);
986 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
987 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
988 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
989 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
990 return (SrcSize + DstSize) <= Threshold;
993 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
994 /// register with a physical register, check if any of the virtual register
995 /// operand is a sub-register use or def. If so, make sure it won't result
996 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
997 /// vr1024 = extract_subreg vr1025, 1
999 /// vr1024 = mov8rr AH
1000 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
1001 /// AH does not have a super-reg whose sub-register 1 is AH.
1003 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1006 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1007 E = mri_->reg_end(); I != E; ++I) {
1008 MachineOperand &O = I.getOperand();
1009 MachineInstr *MI = &*I;
1010 if (MI == CopyMI || JoinedCopies.count(MI))
1012 unsigned SubIdx = O.getSubReg();
1013 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1015 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1016 SubIdx = MI->getOperand(2).getImm();
1017 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1020 unsigned SrcReg = MI->getOperand(1).getReg();
1021 const TargetRegisterClass *RC =
1022 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1023 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1024 : mri_->getRegClass(SrcReg);
1025 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1029 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1030 SubIdx = MI->getOperand(3).getImm();
1031 if (VirtReg == MI->getOperand(0).getReg()) {
1032 if (!tri_->getSubReg(PhysReg, SubIdx))
1035 unsigned DstReg = MI->getOperand(0).getReg();
1036 const TargetRegisterClass *RC =
1037 TargetRegisterInfo::isPhysicalRegister(DstReg)
1038 ? tri_->getPhysicalRegisterRegClass(DstReg)
1039 : mri_->getRegClass(DstReg);
1040 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1049 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1050 /// which are the src/dst of the copy instruction CopyMI. This returns true
1051 /// if the copy was successfully coalesced away. If it is not currently
1052 /// possible to coalesce this interval, but it may be possible if other
1053 /// things get coalesced, then it returns true by reference in 'Again'.
1054 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1055 MachineInstr *CopyMI = TheCopy.MI;
1058 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1059 return false; // Already done.
1061 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1065 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1066 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1067 unsigned SubIdx = 0;
1069 DstReg = CopyMI->getOperand(0).getReg();
1070 SrcReg = CopyMI->getOperand(1).getReg();
1071 } else if (isInsSubReg) {
1072 if (CopyMI->getOperand(2).getSubReg()) {
1073 DOUT << "\tSource of insert_subreg is already coalesced "
1074 << "to another register.\n";
1075 return false; // Not coalescable.
1077 DstReg = CopyMI->getOperand(0).getReg();
1078 SrcReg = CopyMI->getOperand(2).getReg();
1079 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
1080 assert(0 && "Unrecognized copy instruction!");
1084 // If they are already joined we continue.
1085 if (SrcReg == DstReg) {
1086 DOUT << "\tCopy already coalesced.\n";
1087 return false; // Not coalescable.
1090 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1091 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1093 // If they are both physical registers, we cannot join them.
1094 if (SrcIsPhys && DstIsPhys) {
1095 DOUT << "\tCan not coalesce physregs.\n";
1096 return false; // Not coalescable.
1099 // We only join virtual registers with allocatable physical registers.
1100 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1101 DOUT << "\tSrc reg is unallocatable physreg.\n";
1102 return false; // Not coalescable.
1104 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1105 DOUT << "\tDst reg is unallocatable physreg.\n";
1106 return false; // Not coalescable.
1109 // Should be non-null only when coalescing to a sub-register class.
1110 const TargetRegisterClass *SubRC = NULL;
1111 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1112 unsigned RealDstReg = 0;
1113 unsigned RealSrcReg = 0;
1114 if (isExtSubReg || isInsSubReg) {
1115 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1116 if (SrcIsPhys && isExtSubReg) {
1117 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1118 // coalesced with AX.
1119 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1121 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1122 // coalesced to a larger register so the subreg indices cancel out.
1123 if (DstSubIdx != SubIdx) {
1124 DOUT << "\t Sub-register indices mismatch.\n";
1125 return false; // Not coalescable.
1128 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1130 } else if (DstIsPhys && isInsSubReg) {
1131 // EAX = INSERT_SUBREG EAX, r1024, 0
1132 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1134 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1135 // coalesced to a larger register so the subreg indices cancel out.
1136 if (SrcSubIdx != SubIdx) {
1137 DOUT << "\t Sub-register indices mismatch.\n";
1138 return false; // Not coalescable.
1141 DstReg = tri_->getSubReg(DstReg, SubIdx);
1143 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
1144 // If this is a extract_subreg where dst is a physical register, e.g.
1145 // cl = EXTRACT_SUBREG reg1024, 1
1146 // then create and update the actual physical register allocated to RHS.
1148 // reg1024 = INSERT_SUBREG r1024, cl, 1
1149 if (CopyMI->getOperand(1).getSubReg()) {
1150 DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
1151 << " of a super-class.\n";
1152 return false; // Not coalescable.
1154 const TargetRegisterClass *RC =
1155 mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
1157 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
1158 assert(RealDstReg && "Invalid extract_subreg instruction!");
1160 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
1161 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1164 // For this type of EXTRACT_SUBREG, conservatively
1165 // check if the live interval of the source register interfere with the
1166 // actual super physical register we are trying to coalesce with.
1167 unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
1168 LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
1169 if (li_->hasInterval(PhysReg) &&
1170 RHS.overlaps(li_->getInterval(PhysReg))) {
1171 DOUT << "Interfere with register ";
1172 DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
1173 return false; // Not coalescable
1175 for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
1176 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1177 DOUT << "Interfere with sub-register ";
1178 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1179 return false; // Not coalescable
1183 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1184 : CopyMI->getOperand(2).getSubReg();
1186 if (OldSubIdx == SubIdx &&
1187 !differingRegisterClasses(SrcReg, DstReg, SubRC))
1188 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1189 // coalesced to a larger register so the subreg indices cancel out.
1190 // Also check if the other larger register is of the same register
1191 // class as the would be resulting register.
1194 DOUT << "\t Sub-register indices mismatch.\n";
1195 return false; // Not coalescable.
1199 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1200 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1201 unsigned LargeRegSize =
1202 li_->getApproximateInstructionCount(li_->getInterval(LargeReg));
1203 unsigned SmallRegSize =
1204 li_->getApproximateInstructionCount(li_->getInterval(SmallReg));
1205 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
1206 unsigned Threshold = allocatableRCRegs_[RC].count();
1207 // Be conservative. If both sides are virtual registers, do not coalesce
1208 // if this will cause a high use density interval to target a smaller
1209 // set of registers.
1210 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
1211 if ((float)std::distance(mri_->use_begin(SmallReg),
1212 mri_->use_end()) / SmallRegSize <
1213 (float)std::distance(mri_->use_begin(LargeReg),
1214 mri_->use_end()) / LargeRegSize) {
1215 Again = true; // May be possible to coalesce later.
1221 } else if (differingRegisterClasses(SrcReg, DstReg, SubRC)) {
1222 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
1223 // with another? If it's the resulting destination register, then
1224 // the subidx must be propagated to uses (but only those defined
1225 // by the EXTRACT_SUBREG). If it's being coalesced into another
1226 // register, it should be safe because register is assumed to have
1227 // the register class of the super-register.
1229 if (!SubRC || !isProfitableToCoalesceToSubRC(SrcReg, DstReg, CopyMBB)) {
1230 // If they are not of the same register class, we cannot join them.
1231 DOUT << "\tSrc/Dest are different register classes.\n";
1232 // Allow the coalescer to try again in case either side gets coalesced to
1233 // a physical register that's compatible with the other side. e.g.
1234 // r1024 = MOV32to32_ r1025
1235 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1236 Again = true; // May be possible to coalesce later.
1241 // Will it create illegal extract_subreg / insert_subreg?
1242 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1244 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1247 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1248 LiveInterval &DstInt = li_->getInterval(DstReg);
1249 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1250 "Register mapping is horribly broken!");
1252 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1253 DOUT << " and "; DstInt.print(DOUT, tri_);
1256 // Check if it is necessary to propagate "isDead" property.
1257 if (!isExtSubReg && !isInsSubReg) {
1258 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1259 bool isDead = mopd->isDead();
1261 // We need to be careful about coalescing a source physical register with a
1262 // virtual register. Once the coalescing is done, it cannot be broken and
1263 // these are not spillable! If the destination interval uses are far away,
1264 // think twice about coalescing them!
1265 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1266 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1267 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1268 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1269 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1270 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1271 if (TheCopy.isBackEdge)
1272 Threshold *= 2; // Favors back edge copies.
1274 // If the virtual register live interval is long but it has low use desity,
1275 // do not join them, instead mark the physical register as its allocation
1277 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1278 if (Length > Threshold &&
1279 (((float)std::distance(mri_->use_begin(JoinVReg),
1280 mri_->use_end()) / Length) < (1.0 / Threshold))) {
1281 JoinVInt.preference = JoinPReg;
1283 DOUT << "\tMay tie down a physical register, abort!\n";
1284 Again = true; // May be possible to coalesce later.
1290 // Okay, attempt to join these two intervals. On failure, this returns false.
1291 // Otherwise, if one of the intervals being joined is a physreg, this method
1292 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1293 // been modified, so we can use this information below to update aliases.
1294 bool Swapped = false;
1295 // If SrcInt is implicitly defined, it's safe to coalesce.
1296 bool isEmpty = SrcInt.empty();
1297 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1298 // Only coalesce an empty interval (defined by implicit_def) with
1299 // another interval which has a valno defined by the CopyMI and the CopyMI
1300 // is a kill of the implicit def.
1301 DOUT << "Not profitable!\n";
1305 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1306 // Coalescing failed.
1308 // If definition of source is defined by trivial computation, try
1309 // rematerializing it.
1310 if (!isExtSubReg && !isInsSubReg &&
1311 ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1314 // If we can eliminate the copy without merging the live ranges, do so now.
1315 if (!isExtSubReg && !isInsSubReg &&
1316 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1317 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1318 JoinedCopies.insert(CopyMI);
1322 // Otherwise, we are unable to join the intervals.
1323 DOUT << "Interference!\n";
1324 Again = true; // May be possible to coalesce later.
1328 LiveInterval *ResSrcInt = &SrcInt;
1329 LiveInterval *ResDstInt = &DstInt;
1331 std::swap(SrcReg, DstReg);
1332 std::swap(ResSrcInt, ResDstInt);
1334 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1335 "LiveInterval::join didn't work right!");
1337 // If we're about to merge live ranges into a physical register live range,
1338 // we have to update any aliased register's live ranges to indicate that they
1339 // have clobbered values for this range.
1340 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1341 // If this is a extract_subreg where dst is a physical register, e.g.
1342 // cl = EXTRACT_SUBREG reg1024, 1
1343 // then create and update the actual physical register allocated to RHS.
1344 if (RealDstReg || RealSrcReg) {
1345 LiveInterval &RealInt =
1346 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1347 SmallSet<const VNInfo*, 4> CopiedValNos;
1348 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1349 E = ResSrcInt->ranges.end(); I != E; ++I) {
1350 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1351 assert(DstLR && "Invalid joined interval!");
1352 const VNInfo *DstValNo = DstLR->valno;
1353 if (CopiedValNos.insert(DstValNo)) {
1354 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1355 li_->getVNInfoAllocator());
1356 ValNo->hasPHIKill = DstValNo->hasPHIKill;
1357 RealInt.addKills(ValNo, DstValNo->kills);
1358 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
1362 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1365 // Update the liveintervals of sub-registers.
1366 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1367 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1368 li_->getVNInfoAllocator());
1371 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1372 // larger super-register.
1373 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1374 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1375 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1376 std::swap(SrcReg, DstReg);
1377 std::swap(ResSrcInt, ResDstInt);
1381 // Coalescing to a virtual register that is of a sub-register class of the
1382 // other. Make sure the resulting register is set to the right register class.
1384 mri_->setRegClass(DstReg, SubRC);
1389 // Add all copies that define val# in the source interval into the queue.
1390 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1391 e = ResSrcInt->vni_end(); i != e; ++i) {
1392 const VNInfo *vni = *i;
1393 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1395 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1396 unsigned NewSrcReg, NewDstReg;
1398 JoinedCopies.count(CopyMI) == 0 &&
1399 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
1400 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
1401 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1402 isBackEdgeCopy(CopyMI, DstReg)));
1407 // Remember to delete the copy instruction.
1408 JoinedCopies.insert(CopyMI);
1410 // Some live range has been lengthened due to colaescing, eliminate the
1411 // unnecessary kills.
1412 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1413 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1414 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1419 // r1024 = implicit_def
1422 RemoveDeadImpDef(DstReg, *ResDstInt);
1423 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1425 // SrcReg is guarateed to be the register whose live interval that is
1427 li_->removeInterval(SrcReg);
1430 // Now the copy is being coalesced away, the val# previously defined
1431 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1432 // length interval. Remove the val#.
1433 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1434 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1435 VNInfo *ImpVal = LR->valno;
1436 assert(ImpVal->def == CopyIdx);
1437 unsigned NextDef = LR->end;
1438 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1439 ResDstInt->removeValNo(ImpVal);
1440 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1441 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1442 // Special case: vr1024 = implicit_def
1443 // vr1024 = insert_subreg vr1024, vr1025, c
1444 // The insert_subreg becomes a "copy" that defines a val# which can itself
1445 // be coalesced away.
1446 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1447 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1448 LR->valno->copy = DefMI;
1452 // If resulting interval has a preference that no longer fits because of subreg
1453 // coalescing, just clear the preference.
1454 if (ResDstInt->preference && (isExtSubReg || isInsSubReg) &&
1455 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1456 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1457 if (!RC->contains(ResDstInt->preference))
1458 ResDstInt->preference = 0;
1461 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1468 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1469 /// compute what the resultant value numbers for each value in the input two
1470 /// ranges will be. This is complicated by copies between the two which can
1471 /// and will commonly cause multiple value numbers to be merged into one.
1473 /// VN is the value number that we're trying to resolve. InstDefiningValue
1474 /// keeps track of the new InstDefiningValue assignment for the result
1475 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1476 /// whether a value in this or other is a copy from the opposite set.
1477 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1478 /// already been assigned.
1480 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1481 /// contains the value number the copy is from.
1483 static unsigned ComputeUltimateVN(VNInfo *VNI,
1484 SmallVector<VNInfo*, 16> &NewVNInfo,
1485 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1486 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1487 SmallVector<int, 16> &ThisValNoAssignments,
1488 SmallVector<int, 16> &OtherValNoAssignments) {
1489 unsigned VN = VNI->id;
1491 // If the VN has already been computed, just return it.
1492 if (ThisValNoAssignments[VN] >= 0)
1493 return ThisValNoAssignments[VN];
1494 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1496 // If this val is not a copy from the other val, then it must be a new value
1497 // number in the destination.
1498 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1499 if (I == ThisFromOther.end()) {
1500 NewVNInfo.push_back(VNI);
1501 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1503 VNInfo *OtherValNo = I->second;
1505 // Otherwise, this *is* a copy from the RHS. If the other side has already
1506 // been computed, return it.
1507 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1508 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1510 // Mark this value number as currently being computed, then ask what the
1511 // ultimate value # of the other value is.
1512 ThisValNoAssignments[VN] = -2;
1513 unsigned UltimateVN =
1514 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1515 OtherValNoAssignments, ThisValNoAssignments);
1516 return ThisValNoAssignments[VN] = UltimateVN;
1519 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1520 return std::find(V.begin(), V.end(), Val) != V.end();
1523 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1524 /// the specified live interval is defined by a copy from the specified
1526 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1529 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1532 if (LR->valno->def == ~0U &&
1533 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1534 *tri_->getSuperRegisters(li.reg)) {
1535 // It's a sub-register live interval, we may not have precise information.
1537 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1538 unsigned SrcReg, DstReg;
1539 if (DefMI && tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
1540 DstReg == li.reg && SrcReg == Reg) {
1541 // Cache computed info.
1542 LR->valno->def = LR->start;
1543 LR->valno->copy = DefMI;
1550 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1551 /// caller of this method must guarantee that the RHS only contains a single
1552 /// value number and that the RHS is not defined by a copy from this
1553 /// interval. This returns false if the intervals are not joinable, or it
1554 /// joins them and returns true.
1555 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1556 assert(RHS.containsOneValue());
1558 // Some number (potentially more than one) value numbers in the current
1559 // interval may be defined as copies from the RHS. Scan the overlapping
1560 // portions of the LHS and RHS, keeping track of this and looking for
1561 // overlapping live ranges that are NOT defined as copies. If these exist, we
1564 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1565 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1567 if (LHSIt->start < RHSIt->start) {
1568 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1569 if (LHSIt != LHS.begin()) --LHSIt;
1570 } else if (RHSIt->start < LHSIt->start) {
1571 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1572 if (RHSIt != RHS.begin()) --RHSIt;
1575 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1578 // Determine if these live intervals overlap.
1579 bool Overlaps = false;
1580 if (LHSIt->start <= RHSIt->start)
1581 Overlaps = LHSIt->end > RHSIt->start;
1583 Overlaps = RHSIt->end > LHSIt->start;
1585 // If the live intervals overlap, there are two interesting cases: if the
1586 // LHS interval is defined by a copy from the RHS, it's ok and we record
1587 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1588 // coalesce these live ranges and we bail out.
1590 // If we haven't already recorded that this value # is safe, check it.
1591 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1592 // Copy from the RHS?
1593 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1594 return false; // Nope, bail out.
1596 if (LHSIt->contains(RHSIt->valno->def))
1597 // Here is an interesting situation:
1599 // vr1025 = copy vr1024
1604 // Even though vr1025 is copied from vr1024, it's not safe to
1605 // coalesced them since live range of vr1025 intersects the
1606 // def of vr1024. This happens because vr1025 is assigned the
1607 // value of the previous iteration of vr1024.
1609 EliminatedLHSVals.push_back(LHSIt->valno);
1612 // We know this entire LHS live range is okay, so skip it now.
1613 if (++LHSIt == LHSEnd) break;
1617 if (LHSIt->end < RHSIt->end) {
1618 if (++LHSIt == LHSEnd) break;
1620 // One interesting case to check here. It's possible that we have
1621 // something like "X3 = Y" which defines a new value number in the LHS,
1622 // and is the last use of this liverange of the RHS. In this case, we
1623 // want to notice this copy (so that it gets coalesced away) even though
1624 // the live ranges don't actually overlap.
1625 if (LHSIt->start == RHSIt->end) {
1626 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1627 // We already know that this value number is going to be merged in
1628 // if coalescing succeeds. Just skip the liverange.
1629 if (++LHSIt == LHSEnd) break;
1631 // Otherwise, if this is a copy from the RHS, mark it as being merged
1633 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1634 if (LHSIt->contains(RHSIt->valno->def))
1635 // Here is an interesting situation:
1637 // vr1025 = copy vr1024
1642 // Even though vr1025 is copied from vr1024, it's not safe to
1643 // coalesced them since live range of vr1025 intersects the
1644 // def of vr1024. This happens because vr1025 is assigned the
1645 // value of the previous iteration of vr1024.
1647 EliminatedLHSVals.push_back(LHSIt->valno);
1649 // We know this entire LHS live range is okay, so skip it now.
1650 if (++LHSIt == LHSEnd) break;
1655 if (++RHSIt == RHSEnd) break;
1659 // If we got here, we know that the coalescing will be successful and that
1660 // the value numbers in EliminatedLHSVals will all be merged together. Since
1661 // the most common case is that EliminatedLHSVals has a single number, we
1662 // optimize for it: if there is more than one value, we merge them all into
1663 // the lowest numbered one, then handle the interval as if we were merging
1664 // with one value number.
1665 VNInfo *LHSValNo = NULL;
1666 if (EliminatedLHSVals.size() > 1) {
1667 // Loop through all the equal value numbers merging them into the smallest
1669 VNInfo *Smallest = EliminatedLHSVals[0];
1670 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1671 if (EliminatedLHSVals[i]->id < Smallest->id) {
1672 // Merge the current notion of the smallest into the smaller one.
1673 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1674 Smallest = EliminatedLHSVals[i];
1676 // Merge into the smallest.
1677 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1680 LHSValNo = Smallest;
1681 } else if (EliminatedLHSVals.empty()) {
1682 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1683 *tri_->getSuperRegisters(LHS.reg))
1684 // Imprecise sub-register information. Can't handle it.
1686 assert(0 && "No copies from the RHS?");
1688 LHSValNo = EliminatedLHSVals[0];
1691 // Okay, now that there is a single LHS value number that we're merging the
1692 // RHS into, update the value number info for the LHS to indicate that the
1693 // value number is defined where the RHS value number was.
1694 const VNInfo *VNI = RHS.getValNumInfo(0);
1695 LHSValNo->def = VNI->def;
1696 LHSValNo->copy = VNI->copy;
1698 // Okay, the final step is to loop over the RHS live intervals, adding them to
1700 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1701 LHS.addKills(LHSValNo, VNI->kills);
1702 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1703 LHS.weight += RHS.weight;
1704 if (RHS.preference && !LHS.preference)
1705 LHS.preference = RHS.preference;
1710 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1711 /// returns false. Otherwise, if one of the intervals being joined is a
1712 /// physreg, this method always canonicalizes LHS to be it. The output
1713 /// "RHS" will not have been modified, so we can use this information
1714 /// below to update aliases.
1715 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1716 LiveInterval &RHS, bool &Swapped) {
1717 // Compute the final value assignment, assuming that the live ranges can be
1719 SmallVector<int, 16> LHSValNoAssignments;
1720 SmallVector<int, 16> RHSValNoAssignments;
1721 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1722 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1723 SmallVector<VNInfo*, 16> NewVNInfo;
1725 // If a live interval is a physical register, conservatively check if any
1726 // of its sub-registers is overlapping the live interval of the virtual
1727 // register. If so, do not coalesce.
1728 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1729 *tri_->getSubRegisters(LHS.reg)) {
1730 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1731 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1732 DOUT << "Interfere with sub-register ";
1733 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1736 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1737 *tri_->getSubRegisters(RHS.reg)) {
1738 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1739 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1740 DOUT << "Interfere with sub-register ";
1741 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1746 // Compute ultimate value numbers for the LHS and RHS values.
1747 if (RHS.containsOneValue()) {
1748 // Copies from a liveinterval with a single value are simple to handle and
1749 // very common, handle the special case here. This is important, because
1750 // often RHS is small and LHS is large (e.g. a physreg).
1752 // Find out if the RHS is defined as a copy from some value in the LHS.
1753 int RHSVal0DefinedFromLHS = -1;
1755 VNInfo *RHSValNoInfo = NULL;
1756 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1757 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1758 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1759 // If RHS is not defined as a copy from the LHS, we can use simpler and
1760 // faster checks to see if the live ranges are coalescable. This joiner
1761 // can't swap the LHS/RHS intervals though.
1762 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1763 return SimpleJoin(LHS, RHS);
1765 RHSValNoInfo = RHSValNoInfo0;
1768 // It was defined as a copy from the LHS, find out what value # it is.
1769 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1770 RHSValID = RHSValNoInfo->id;
1771 RHSVal0DefinedFromLHS = RHSValID;
1774 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1775 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1776 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1778 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1779 // should now get updated.
1780 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1783 unsigned VN = VNI->id;
1784 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1785 if (LHSSrcReg != RHS.reg) {
1786 // If this is not a copy from the RHS, its value number will be
1787 // unmodified by the coalescing.
1788 NewVNInfo[VN] = VNI;
1789 LHSValNoAssignments[VN] = VN;
1790 } else if (RHSValID == -1) {
1791 // Otherwise, it is a copy from the RHS, and we don't already have a
1792 // value# for it. Keep the current value number, but remember it.
1793 LHSValNoAssignments[VN] = RHSValID = VN;
1794 NewVNInfo[VN] = RHSValNoInfo;
1795 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1797 // Otherwise, use the specified value #.
1798 LHSValNoAssignments[VN] = RHSValID;
1799 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1800 NewVNInfo[VN] = RHSValNoInfo;
1801 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1805 NewVNInfo[VN] = VNI;
1806 LHSValNoAssignments[VN] = VN;
1810 assert(RHSValID != -1 && "Didn't find value #?");
1811 RHSValNoAssignments[0] = RHSValID;
1812 if (RHSVal0DefinedFromLHS != -1) {
1813 // This path doesn't go through ComputeUltimateVN so just set
1815 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1818 // Loop over the value numbers of the LHS, seeing if any are defined from
1820 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1823 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1826 // DstReg is known to be a register in the LHS interval. If the src is
1827 // from the RHS interval, we can use its value #.
1828 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1831 // Figure out the value # from the RHS.
1832 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1835 // Loop over the value numbers of the RHS, seeing if any are defined from
1837 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1840 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1843 // DstReg is known to be a register in the RHS interval. If the src is
1844 // from the LHS interval, we can use its value #.
1845 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1848 // Figure out the value # from the LHS.
1849 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1852 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1853 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1854 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1856 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1859 unsigned VN = VNI->id;
1860 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1862 ComputeUltimateVN(VNI, NewVNInfo,
1863 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1864 LHSValNoAssignments, RHSValNoAssignments);
1866 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1869 unsigned VN = VNI->id;
1870 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1872 // If this value number isn't a copy from the LHS, it's a new number.
1873 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1874 NewVNInfo.push_back(VNI);
1875 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1879 ComputeUltimateVN(VNI, NewVNInfo,
1880 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1881 RHSValNoAssignments, LHSValNoAssignments);
1885 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1886 // interval lists to see if these intervals are coalescable.
1887 LiveInterval::const_iterator I = LHS.begin();
1888 LiveInterval::const_iterator IE = LHS.end();
1889 LiveInterval::const_iterator J = RHS.begin();
1890 LiveInterval::const_iterator JE = RHS.end();
1892 // Skip ahead until the first place of potential sharing.
1893 if (I->start < J->start) {
1894 I = std::upper_bound(I, IE, J->start);
1895 if (I != LHS.begin()) --I;
1896 } else if (J->start < I->start) {
1897 J = std::upper_bound(J, JE, I->start);
1898 if (J != RHS.begin()) --J;
1902 // Determine if these two live ranges overlap.
1904 if (I->start < J->start) {
1905 Overlaps = I->end > J->start;
1907 Overlaps = J->end > I->start;
1910 // If so, check value # info to determine if they are really different.
1912 // If the live range overlap will map to the same value number in the
1913 // result liverange, we can still coalesce them. If not, we can't.
1914 if (LHSValNoAssignments[I->valno->id] !=
1915 RHSValNoAssignments[J->valno->id])
1919 if (I->end < J->end) {
1928 // Update kill info. Some live ranges are extended due to copy coalescing.
1929 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1930 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1931 VNInfo *VNI = I->first;
1932 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1933 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1934 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1935 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1938 // Update kill info. Some live ranges are extended due to copy coalescing.
1939 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1940 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1941 VNInfo *VNI = I->first;
1942 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1943 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1944 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1945 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1948 // If we get here, we know that we can coalesce the live ranges. Ask the
1949 // intervals to coalesce themselves now.
1950 if ((RHS.ranges.size() > LHS.ranges.size() &&
1951 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1952 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1953 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1956 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1963 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1964 // depth of the basic block (the unsigned), and then on the MBB number.
1965 struct DepthMBBCompare {
1966 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1967 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1968 if (LHS.first > RHS.first) return true; // Deeper loops first
1969 return LHS.first == RHS.first &&
1970 LHS.second->getNumber() < RHS.second->getNumber();
1975 /// getRepIntervalSize - Returns the size of the interval that represents the
1976 /// specified register.
1978 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1979 return Rc->getRepIntervalSize(Reg);
1982 /// CopyRecSort::operator - Join priority queue sorting function.
1984 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1985 // Inner loops first.
1986 if (left.LoopDepth > right.LoopDepth)
1988 else if (left.LoopDepth == right.LoopDepth)
1989 if (left.isBackEdge && !right.isBackEdge)
1994 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1995 std::vector<CopyRec> &TryAgain) {
1996 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1998 std::vector<CopyRec> VirtCopies;
1999 std::vector<CopyRec> PhysCopies;
2000 std::vector<CopyRec> ImpDefCopies;
2001 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
2002 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2004 MachineInstr *Inst = MII++;
2006 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2007 unsigned SrcReg, DstReg;
2008 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2009 DstReg = Inst->getOperand(0).getReg();
2010 SrcReg = Inst->getOperand(1).getReg();
2011 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
2012 DstReg = Inst->getOperand(0).getReg();
2013 SrcReg = Inst->getOperand(2).getReg();
2014 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
2017 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2018 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2020 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
2022 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2023 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2024 else if (SrcIsPhys || DstIsPhys)
2025 PhysCopies.push_back(CopyRec(Inst, 0, false));
2027 VirtCopies.push_back(CopyRec(Inst, 0, false));
2034 // Try coalescing implicit copies first, followed by copies to / from
2035 // physical registers, then finally copies from virtual registers to
2036 // virtual registers.
2037 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2038 CopyRec &TheCopy = ImpDefCopies[i];
2040 if (!JoinCopy(TheCopy, Again))
2042 TryAgain.push_back(TheCopy);
2044 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2045 CopyRec &TheCopy = PhysCopies[i];
2047 if (!JoinCopy(TheCopy, Again))
2049 TryAgain.push_back(TheCopy);
2051 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2052 CopyRec &TheCopy = VirtCopies[i];
2054 if (!JoinCopy(TheCopy, Again))
2056 TryAgain.push_back(TheCopy);
2060 void SimpleRegisterCoalescing::joinIntervals() {
2061 DOUT << "********** JOINING INTERVALS ***********\n";
2064 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2066 std::vector<CopyRec> TryAgainList;
2067 if (loopInfo->empty()) {
2068 // If there are no loops in the function, join intervals in function order.
2069 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2071 CopyCoalesceInMBB(I, TryAgainList);
2073 // Otherwise, join intervals in inner loops before other intervals.
2074 // Unfortunately we can't just iterate over loop hierarchy here because
2075 // there may be more MBB's than BB's. Collect MBB's for sorting.
2077 // Join intervals in the function prolog first. We want to join physical
2078 // registers with virtual registers before the intervals got too long.
2079 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2080 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2081 MachineBasicBlock *MBB = I;
2082 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2085 // Sort by loop depth.
2086 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2088 // Finally, join intervals in loop nest order.
2089 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2090 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2093 // Joining intervals can allow other intervals to be joined. Iteratively join
2094 // until we make no progress.
2096 SmallVector<CopyRec, 16> TryAgain;
2097 bool ProgressMade = true;
2098 while (ProgressMade) {
2099 ProgressMade = false;
2100 while (!JoinQueue->empty()) {
2101 CopyRec R = JoinQueue->pop();
2103 bool Success = JoinCopy(R, Again);
2105 ProgressMade = true;
2107 TryAgain.push_back(R);
2111 while (!TryAgain.empty()) {
2112 JoinQueue->push(TryAgain.back());
2113 TryAgain.pop_back();
2118 bool ProgressMade = true;
2119 while (ProgressMade) {
2120 ProgressMade = false;
2122 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2123 CopyRec &TheCopy = TryAgainList[i];
2126 bool Success = JoinCopy(TheCopy, Again);
2127 if (Success || !Again) {
2128 TheCopy.MI = 0; // Mark this one as done.
2129 ProgressMade = true;
2140 /// Return true if the two specified registers belong to different register
2141 /// classes. The registers may be either phys or virt regs. In the
2142 /// case where both registers are virtual registers, it would also returns
2143 /// true by reference the RegB register class in SubRC if it is a subset of
2144 /// RegA's register class.
2146 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA, unsigned RegB,
2147 const TargetRegisterClass *&SubRC) const {
2149 // Get the register classes for the first reg.
2150 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2151 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2152 "Shouldn't consider two physregs!");
2153 return !mri_->getRegClass(RegB)->contains(RegA);
2156 // Compare against the regclass for the second reg.
2157 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2158 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2159 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2160 if (RegClassA == RegClassB)
2162 SubRC = (RegClassA->hasSubClass(RegClassB)) ? RegClassB : NULL;
2165 return !RegClassA->contains(RegB);
2168 /// lastRegisterUse - Returns the last use of the specific register between
2169 /// cycles Start and End or NULL if there are no uses.
2171 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
2172 unsigned Reg, unsigned &UseIdx) const{
2174 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2175 MachineOperand *LastUse = NULL;
2176 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2177 E = mri_->use_end(); I != E; ++I) {
2178 MachineOperand &Use = I.getOperand();
2179 MachineInstr *UseMI = Use.getParent();
2180 unsigned SrcReg, DstReg;
2181 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
2182 // Ignore identity copies.
2184 unsigned Idx = li_->getInstructionIndex(UseMI);
2185 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2193 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2196 // Skip deleted instructions
2197 MachineInstr *MI = li_->getInstructionFromIndex(e);
2198 while ((e - InstrSlots::NUM) >= s && !MI) {
2199 e -= InstrSlots::NUM;
2200 MI = li_->getInstructionFromIndex(e);
2202 if (e < s || MI == NULL)
2205 // Ignore identity copies.
2206 unsigned SrcReg, DstReg;
2207 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
2208 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2209 MachineOperand &Use = MI->getOperand(i);
2210 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2211 tri_->regsOverlap(Use.getReg(), Reg)) {
2217 e -= InstrSlots::NUM;
2224 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2225 if (TargetRegisterInfo::isPhysicalRegister(reg))
2226 cerr << tri_->getName(reg);
2228 cerr << "%reg" << reg;
2231 void SimpleRegisterCoalescing::releaseMemory() {
2232 JoinedCopies.clear();
2233 ReMatCopies.clear();
2237 static bool isZeroLengthInterval(LiveInterval *li) {
2238 for (LiveInterval::Ranges::const_iterator
2239 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2240 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2245 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2246 /// turn the copy into an implicit def.
2248 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2249 MachineBasicBlock *MBB,
2250 unsigned DstReg, unsigned SrcReg) {
2251 MachineInstr *CopyMI = &*I;
2252 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2253 if (!li_->hasInterval(SrcReg))
2255 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2256 if (!SrcInt.empty())
2258 if (!li_->hasInterval(DstReg))
2260 LiveInterval &DstInt = li_->getInterval(DstReg);
2261 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
2262 DstInt.removeValNo(DstLR->valno);
2263 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2264 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2265 CopyMI->RemoveOperand(i);
2266 bool NoUse = mri_->use_empty(SrcReg);
2268 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2269 E = mri_->reg_end(); I != E; ) {
2270 assert(I.getOperand().isDef());
2271 MachineInstr *DefMI = &*I;
2273 // The implicit_def source has no other uses, delete it.
2274 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2275 li_->RemoveMachineInstrFromMaps(DefMI);
2276 DefMI->eraseFromParent();
2284 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2286 mri_ = &fn.getRegInfo();
2287 tm_ = &fn.getTarget();
2288 tri_ = tm_->getRegisterInfo();
2289 tii_ = tm_->getInstrInfo();
2290 li_ = &getAnalysis<LiveIntervals>();
2291 loopInfo = &getAnalysis<MachineLoopInfo>();
2293 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2294 << "********** Function: "
2295 << ((Value*)mf_->getFunction())->getName() << '\n';
2297 allocatableRegs_ = tri_->getAllocatableSet(fn);
2298 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2299 E = tri_->regclass_end(); I != E; ++I)
2300 allocatableRCRegs_.insert(std::make_pair(*I,
2301 tri_->getAllocatableSet(fn, *I)));
2303 // Join (coalesce) intervals if requested.
2304 if (EnableJoining) {
2307 DOUT << "********** INTERVALS POST JOINING **********\n";
2308 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2309 I->second->print(DOUT, tri_);
2315 // Perform a final pass over the instructions and compute spill weights
2316 // and remove identity moves.
2317 SmallVector<unsigned, 4> DeadDefs;
2318 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2319 mbbi != mbbe; ++mbbi) {
2320 MachineBasicBlock* mbb = mbbi;
2321 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2323 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2325 MachineInstr *MI = mii;
2326 unsigned SrcReg, DstReg;
2327 if (JoinedCopies.count(MI)) {
2328 // Delete all coalesced copies.
2329 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg)) {
2330 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2331 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2332 "Unrecognized copy instruction");
2333 DstReg = MI->getOperand(0).getReg();
2335 if (MI->registerDefIsDead(DstReg)) {
2336 LiveInterval &li = li_->getInterval(DstReg);
2337 if (!ShortenDeadCopySrcLiveRange(li, MI))
2338 ShortenDeadCopyLiveRange(li, MI);
2340 li_->RemoveMachineInstrFromMaps(MI);
2341 mii = mbbi->erase(mii);
2346 // Now check if this is a remat'ed def instruction which is now dead.
2347 if (ReMatDefs.count(MI)) {
2349 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2350 const MachineOperand &MO = MI->getOperand(i);
2353 unsigned Reg = MO.getReg();
2354 if (TargetRegisterInfo::isVirtualRegister(Reg))
2355 DeadDefs.push_back(Reg);
2358 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2359 !mri_->use_empty(Reg)) {
2365 while (!DeadDefs.empty()) {
2366 unsigned DeadDef = DeadDefs.back();
2367 DeadDefs.pop_back();
2368 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2370 li_->RemoveMachineInstrFromMaps(mii);
2371 mii = mbbi->erase(mii);
2377 // If the move will be an identity move delete it
2378 bool isMove = tii_->isMoveInstr(*MI, SrcReg, DstReg);
2379 if (isMove && SrcReg == DstReg) {
2380 if (li_->hasInterval(SrcReg)) {
2381 LiveInterval &RegInt = li_->getInterval(SrcReg);
2382 // If def of this move instruction is dead, remove its live range
2383 // from the dstination register's live interval.
2384 if (MI->registerDefIsDead(DstReg)) {
2385 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2386 ShortenDeadCopyLiveRange(RegInt, MI);
2389 li_->RemoveMachineInstrFromMaps(MI);
2390 mii = mbbi->erase(mii);
2392 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2393 SmallSet<unsigned, 4> UniqueUses;
2394 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2395 const MachineOperand &mop = MI->getOperand(i);
2396 if (mop.isReg() && mop.getReg() &&
2397 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2398 unsigned reg = mop.getReg();
2399 // Multiple uses of reg by the same instruction. It should not
2400 // contribute to spill weight again.
2401 if (UniqueUses.count(reg) != 0)
2403 LiveInterval &RegInt = li_->getInterval(reg);
2405 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2406 UniqueUses.insert(reg);
2414 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2415 LiveInterval &LI = *I->second;
2416 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2417 // If the live interval length is essentially zero, i.e. in every live
2418 // range the use follows def immediately, it doesn't make sense to spill
2419 // it and hope it will be easier to allocate for this li.
2420 if (isZeroLengthInterval(&LI))
2421 LI.weight = HUGE_VALF;
2423 bool isLoad = false;
2424 SmallVector<LiveInterval*, 4> SpillIs;
2425 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2426 // If all of the definitions of the interval are re-materializable,
2427 // it is a preferred candidate for spilling. If non of the defs are
2428 // loads, then it's potentially very cheap to re-materialize.
2429 // FIXME: this gets much more complicated once we support non-trivial
2430 // re-materialization.
2438 // Slightly prefer live interval that has been assigned a preferred reg.
2442 // Divide the weight of the interval by its size. This encourages
2443 // spilling of intervals that are large and have few uses, and
2444 // discourages spilling of small intervals with many uses.
2445 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2453 /// print - Implement the dump method.
2454 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2458 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2459 return new SimpleRegisterCoalescing();
2462 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2463 DEFINING_FILE_FOR(SimpleRegisterCoalescing)