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 assert(BLR != IntB.end() && "Live range not found!");
108 VNInfo *BValNo = BLR->valno;
110 // Get the location that B is defined at. Two options: either this value has
111 // an unknown definition point or it is defined at CopyIdx. If unknown, we
113 if (!BValNo->copy) return false;
114 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
116 // AValNo is the value number in A that defines the copy, A3 in the example.
117 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
118 assert(ALR != IntA.end() && "Live range not found!");
119 VNInfo *AValNo = ALR->valno;
120 // If it's re-defined by an early clobber somewhere in the live range, then
121 // it's not safe to eliminate the copy. FIXME: This is a temporary workaround.
123 // 172 %ECX<def> = MOV32rr %reg1039<kill>
124 // 180 INLINEASM <es:subl $5,$1
125 // sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9, %EAX<kill>,
126 // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
127 // 188 %EAX<def> = MOV32rr %EAX<kill>
128 // 196 %ECX<def> = MOV32rr %ECX<kill>
129 // 204 %ECX<def> = MOV32rr %ECX<kill>
130 // 212 %EAX<def> = MOV32rr %EAX<kill>
131 // 220 %EAX<def> = MOV32rr %EAX
132 // 228 %reg1039<def> = MOV32rr %ECX<kill>
133 // The early clobber operand ties ECX input to the ECX def.
135 // The live interval of ECX is represented as this:
136 // %reg20,inf = [46,47:1)[174,230:0) 0@174-(230) 1@46-(47)
137 // The coalescer has no idea there was a def in the middle of [174,230].
138 if (AValNo->redefByEC)
141 // If AValNo is defined as a copy from IntB, we can potentially process this.
142 // Get the instruction that defines this value number.
143 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
144 if (!SrcReg) return false; // Not defined by a copy.
146 // If the value number is not defined by a copy instruction, ignore it.
148 // If the source register comes from an interval other than IntB, we can't
150 if (SrcReg != IntB.reg) return false;
152 // Get the LiveRange in IntB that this value number starts with.
153 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
154 assert(ValLR != IntB.end() && "Live range not found!");
156 // Make sure that the end of the live range is inside the same block as
158 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
160 ValLREndInst->getParent() != CopyMI->getParent()) return false;
162 // Okay, we now know that ValLR ends in the same block that the CopyMI
163 // live-range starts. If there are no intervening live ranges between them in
164 // IntB, we can merge them.
165 if (ValLR+1 != BLR) return false;
167 // If a live interval is a physical register, conservatively check if any
168 // of its sub-registers is overlapping the live interval of the virtual
169 // register. If so, do not coalesce.
170 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
171 *tri_->getSubRegisters(IntB.reg)) {
172 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
173 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
174 DOUT << "Interfere with sub-register ";
175 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
180 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
182 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
183 // We are about to delete CopyMI, so need to remove it as the 'instruction
184 // that defines this value #'. Update the the valnum with the new defining
186 BValNo->def = FillerStart;
189 // Okay, we can merge them. We need to insert a new liverange:
190 // [ValLR.end, BLR.begin) of either value number, then we merge the
191 // two value numbers.
192 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
194 // If the IntB live range is assigned to a physical register, and if that
195 // physreg has aliases,
196 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
197 // Update the liveintervals of sub-registers.
198 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
199 LiveInterval &AliasLI = li_->getInterval(*AS);
200 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
201 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
205 // Okay, merge "B1" into the same value number as "B0".
206 if (BValNo != ValLR->valno) {
207 IntB.addKills(ValLR->valno, BValNo->kills);
208 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
210 DOUT << " result = "; IntB.print(DOUT, tri_);
213 // If the source instruction was killing the source register before the
214 // merge, unset the isKill marker given the live range has been extended.
215 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
217 ValLREndInst->getOperand(UIdx).setIsKill(false);
218 IntB.removeKill(ValLR->valno, FillerStart);
225 /// HasOtherReachingDefs - Return true if there are definitions of IntB
226 /// other than BValNo val# that can reach uses of AValno val# of IntA.
227 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
231 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
233 if (AI->valno != AValNo) continue;
234 LiveInterval::Ranges::iterator BI =
235 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
236 if (BI != IntB.ranges.begin())
238 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
239 if (BI->valno == BValNo)
241 if (BI->start <= AI->start && BI->end > AI->start)
243 if (BI->start > AI->start && BI->start < AI->end)
250 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
251 /// being the source and IntB being the dest, thus this defines a value number
252 /// in IntB. If the source value number (in IntA) is defined by a commutable
253 /// instruction and its other operand is coalesced to the copy dest register,
254 /// see if we can transform the copy into a noop by commuting the definition. For
257 /// A3 = op A2 B0<kill>
259 /// B1 = A3 <- this copy
261 /// = op A3 <- more uses
265 /// B2 = op B0 A2<kill>
267 /// B1 = B2 <- now an identify copy
269 /// = op B2 <- more uses
271 /// This returns true if an interval was modified.
273 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
275 MachineInstr *CopyMI) {
276 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
278 // FIXME: For now, only eliminate the copy by commuting its def when the
279 // source register is a virtual register. We want to guard against cases
280 // where the copy is a back edge copy and commuting the def lengthen the
281 // live interval of the source register to the entire loop.
282 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
285 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
286 // the example above.
287 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
288 assert(BLR != IntB.end() && "Live range not found!");
289 VNInfo *BValNo = BLR->valno;
291 // Get the location that B is defined at. Two options: either this value has
292 // an unknown definition point or it is defined at CopyIdx. If unknown, we
294 if (!BValNo->copy) return false;
295 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
297 // AValNo is the value number in A that defines the copy, A3 in the example.
298 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
299 assert(ALR != IntA.end() && "Live range not found!");
300 VNInfo *AValNo = ALR->valno;
301 // If other defs can reach uses of this def, then it's not safe to perform
303 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
305 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
306 const TargetInstrDesc &TID = DefMI->getDesc();
308 if (!TID.isCommutable() ||
309 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
312 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
313 unsigned NewReg = NewDstMO.getReg();
314 if (NewReg != IntB.reg || !NewDstMO.isKill())
317 // Make sure there are no other definitions of IntB that would reach the
318 // uses which the new definition can reach.
319 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
322 // If some of the uses of IntA.reg is already coalesced away, return false.
323 // It's not possible to determine whether it's safe to perform the coalescing.
324 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
325 UE = mri_->use_end(); UI != UE; ++UI) {
326 MachineInstr *UseMI = &*UI;
327 unsigned UseIdx = li_->getInstructionIndex(UseMI);
328 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
329 if (ULR == IntA.end())
331 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
335 // At this point we have decided that it is legal to do this
336 // transformation. Start by commuting the instruction.
337 MachineBasicBlock *MBB = DefMI->getParent();
338 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
341 if (NewMI != DefMI) {
342 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
343 MBB->insert(DefMI, NewMI);
346 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
347 NewMI->getOperand(OpIdx).setIsKill();
349 bool BHasPHIKill = BValNo->hasPHIKill;
350 SmallVector<VNInfo*, 4> BDeadValNos;
351 SmallVector<unsigned, 4> BKills;
352 std::map<unsigned, unsigned> BExtend;
354 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
363 // then do not add kills of A to the newly created B interval.
364 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
366 BExtend[ALR->end] = BLR->end;
368 // Update uses of IntA of the specific Val# with IntB.
369 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
370 UE = mri_->use_end(); UI != UE;) {
371 MachineOperand &UseMO = UI.getOperand();
372 MachineInstr *UseMI = &*UI;
374 if (JoinedCopies.count(UseMI))
376 unsigned UseIdx = li_->getInstructionIndex(UseMI);
377 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
378 if (ULR == IntA.end() || ULR->valno != AValNo)
380 UseMO.setReg(NewReg);
383 if (UseMO.isKill()) {
385 UseMO.setIsKill(false);
387 BKills.push_back(li_->getUseIndex(UseIdx)+1);
389 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
390 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
392 if (DstReg == IntB.reg) {
393 // This copy will become a noop. If it's defining a new val#,
394 // remove that val# as well. However this live range is being
395 // extended to the end of the existing live range defined by the copy.
396 unsigned DefIdx = li_->getDefIndex(UseIdx);
397 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
398 BHasPHIKill |= DLR->valno->hasPHIKill;
399 assert(DLR->valno->def == DefIdx);
400 BDeadValNos.push_back(DLR->valno);
401 BExtend[DLR->start] = DLR->end;
402 JoinedCopies.insert(UseMI);
403 // If this is a kill but it's going to be removed, the last use
404 // of the same val# is the new kill.
410 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
411 // simply extend BLR if CopyMI doesn't end the range.
412 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
414 // Remove val#'s defined by copies that will be coalesced away.
415 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
416 IntB.removeValNo(BDeadValNos[i]);
418 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
419 // is updated. Kills are also updated.
420 VNInfo *ValNo = BValNo;
421 ValNo->def = AValNo->def;
423 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
424 unsigned Kill = ValNo->kills[j];
425 if (Kill != BLR->end)
426 BKills.push_back(Kill);
428 ValNo->kills.clear();
429 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
431 if (AI->valno != AValNo) continue;
432 unsigned End = AI->end;
433 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
434 if (EI != BExtend.end())
436 IntB.addRange(LiveRange(AI->start, End, ValNo));
438 IntB.addKills(ValNo, BKills);
439 ValNo->hasPHIKill = BHasPHIKill;
441 DOUT << " result = "; IntB.print(DOUT, tri_);
444 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
445 IntA.removeValNo(AValNo);
446 DOUT << " result = "; IntA.print(DOUT, tri_);
453 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
454 /// computation, replace the copy by rematerialize the definition.
455 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
457 MachineInstr *CopyMI) {
458 unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
459 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
460 assert(SrcLR != SrcInt.end() && "Live range not found!");
461 VNInfo *ValNo = SrcLR->valno;
462 // If other defs can reach uses of this def, then it's not safe to perform
464 if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
466 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
467 const TargetInstrDesc &TID = DefMI->getDesc();
468 if (!TID.isAsCheapAsAMove())
470 bool SawStore = false;
471 if (!DefMI->isSafeToMove(tii_, SawStore))
474 unsigned DefIdx = li_->getDefIndex(CopyIdx);
475 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
476 DLR->valno->copy = NULL;
477 // Don't forget to update sub-register intervals.
478 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
479 for (const unsigned* SR = tri_->getSubRegisters(DstReg); *SR; ++SR) {
480 if (!li_->hasInterval(*SR))
482 DLR = li_->getInterval(*SR).getLiveRangeContaining(DefIdx);
483 if (DLR && DLR->valno->copy == CopyMI)
484 DLR->valno->copy = NULL;
488 MachineBasicBlock *MBB = CopyMI->getParent();
489 MachineBasicBlock::iterator MII = next(MachineBasicBlock::iterator(CopyMI));
490 CopyMI->removeFromParent();
491 tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
492 MachineInstr *NewMI = prior(MII);
493 // CopyMI may have implicit operands, transfer them over to the newly
494 // rematerialized instruction. And update implicit def interval valnos.
495 for (unsigned i = CopyMI->getDesc().getNumOperands(),
496 e = CopyMI->getNumOperands(); i != e; ++i) {
497 MachineOperand &MO = CopyMI->getOperand(i);
498 if (MO.isReg() && MO.isImplicit())
499 NewMI->addOperand(MO);
500 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
501 unsigned Reg = MO.getReg();
502 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
503 if (DLR && DLR->valno->copy == CopyMI)
504 DLR->valno->copy = NULL;
508 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
509 MBB->getParent()->DeleteMachineInstr(CopyMI);
510 ReMatCopies.insert(CopyMI);
511 ReMatDefs.insert(DefMI);
516 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
518 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
519 unsigned DstReg) const {
520 MachineBasicBlock *MBB = CopyMI->getParent();
521 const MachineLoop *L = loopInfo->getLoopFor(MBB);
524 if (MBB != L->getLoopLatch())
527 LiveInterval &LI = li_->getInterval(DstReg);
528 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
529 LiveInterval::const_iterator DstLR =
530 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
531 if (DstLR == LI.end())
533 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
534 if (DstLR->valno->kills.size() == 1 &&
535 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
540 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
541 /// update the subregister number if it is not zero. If DstReg is a
542 /// physical register and the existing subregister number of the def / use
543 /// being updated is not zero, make sure to set it to the correct physical
546 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
548 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
549 if (DstIsPhys && SubIdx) {
550 // Figure out the real physical register we are updating with.
551 DstReg = tri_->getSubReg(DstReg, SubIdx);
555 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
556 E = mri_->reg_end(); I != E; ) {
557 MachineOperand &O = I.getOperand();
558 MachineInstr *UseMI = &*I;
560 unsigned OldSubIdx = O.getSubReg();
562 unsigned UseDstReg = DstReg;
564 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
566 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
567 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
568 CopySrcSubIdx, CopyDstSubIdx) &&
569 CopySrcReg != CopyDstReg &&
570 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
571 // If the use is a copy and it won't be coalesced away, and its source
572 // is defined by a trivial computation, try to rematerialize it instead.
573 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
582 // Sub-register indexes goes from small to large. e.g.
583 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
584 // EAX: 1 -> AL, 2 -> AX
585 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
586 // sub-register 2 is also AX.
587 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
588 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
591 // Remove would-be duplicated kill marker.
592 if (O.isKill() && UseMI->killsRegister(DstReg))
596 // After updating the operand, check if the machine instruction has
597 // become a copy. If so, update its val# information.
598 const TargetInstrDesc &TID = UseMI->getDesc();
599 unsigned CopySrcReg, CopyDstReg, CopySrcSubIdx, CopyDstSubIdx;
600 if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
601 tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg,
602 CopySrcSubIdx, CopyDstSubIdx) &&
603 CopySrcReg != CopyDstReg &&
604 (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
605 allocatableRegs_[CopyDstReg])) {
606 LiveInterval &LI = li_->getInterval(CopyDstReg);
607 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
608 const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx);
609 if (DLR->valno->def == DefIdx)
610 DLR->valno->copy = UseMI;
615 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
616 /// registers due to insert_subreg coalescing. e.g.
618 /// r1025 = implicit_def
619 /// r1025 = insert_subreg r1025, r1024
623 /// r1025 = implicit_def
624 /// r1025 = insert_subreg r1025, r1025
627 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
628 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
629 E = mri_->reg_end(); I != E; ) {
630 MachineOperand &O = I.getOperand();
631 MachineInstr *DefMI = &*I;
635 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
637 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
639 li_->RemoveMachineInstrFromMaps(DefMI);
640 DefMI->eraseFromParent();
644 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
645 /// due to live range lengthening as the result of coalescing.
646 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
648 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
649 UE = mri_->use_end(); UI != UE; ++UI) {
650 MachineOperand &UseMO = UI.getOperand();
651 if (UseMO.isKill()) {
652 MachineInstr *UseMI = UseMO.getParent();
653 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
654 if (JoinedCopies.count(UseMI))
656 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
657 if (!UI || !LI.isKill(UI->valno, UseIdx+1))
658 UseMO.setIsKill(false);
663 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
664 /// from a physical register live interval as well as from the live intervals
665 /// of its sub-registers.
666 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
667 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
668 li.removeRange(Start, End, true);
669 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
670 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
671 if (!li_->hasInterval(*SR))
673 LiveInterval &sli = li_->getInterval(*SR);
674 unsigned RemoveEnd = Start;
675 while (RemoveEnd != End) {
676 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
679 RemoveEnd = (LR->end < End) ? LR->end : End;
680 sli.removeRange(Start, RemoveEnd, true);
687 /// removeIntervalIfEmpty - Check if the live interval of a physical register
688 /// is empty, if so remove it and also remove the empty intervals of its
689 /// sub-registers. Return true if live interval is removed.
690 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
691 const TargetRegisterInfo *tri_) {
693 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
694 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
695 if (!li_->hasInterval(*SR))
697 LiveInterval &sli = li_->getInterval(*SR);
699 li_->removeInterval(*SR);
701 li_->removeInterval(li.reg);
707 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
708 /// Return true if live interval is removed.
709 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
710 MachineInstr *CopyMI) {
711 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
712 LiveInterval::iterator MLR =
713 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
715 return false; // Already removed by ShortenDeadCopySrcLiveRange.
716 unsigned RemoveStart = MLR->start;
717 unsigned RemoveEnd = MLR->end;
718 // Remove the liverange that's defined by this.
719 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
720 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
721 return removeIntervalIfEmpty(li, li_, tri_);
726 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
727 /// the val# it defines. If the live interval becomes empty, remove it as well.
728 bool SimpleRegisterCoalescing::RemoveDeadDef(LiveInterval &li,
729 MachineInstr *DefMI) {
730 unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(DefMI));
731 LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
732 if (DefIdx != MLR->valno->def)
734 li.removeValNo(MLR->valno);
735 return removeIntervalIfEmpty(li, li_, tri_);
738 /// PropagateDeadness - Propagate the dead marker to the instruction which
739 /// defines the val#.
740 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
741 unsigned &LRStart, LiveIntervals *li_,
742 const TargetRegisterInfo* tri_) {
743 MachineInstr *DefMI =
744 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
745 if (DefMI && DefMI != CopyMI) {
746 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
748 DefMI->getOperand(DeadIdx).setIsDead();
749 // A dead def should have a single cycle interval.
755 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
756 /// fallthoughs to SuccMBB.
757 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
758 MachineBasicBlock *SuccMBB,
759 const TargetInstrInfo *tii_) {
762 MachineBasicBlock *TBB = 0, *FBB = 0;
763 SmallVector<MachineOperand, 4> Cond;
764 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
765 MBB->isSuccessor(SuccMBB);
768 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
769 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
770 /// ends the live range there. If there isn't another use, then this live range
771 /// is dead. Return true if live interval is removed.
773 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
774 MachineInstr *CopyMI) {
775 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
777 // FIXME: special case: function live in. It can be a general case if the
778 // first instruction index starts at > 0 value.
779 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
780 // Live-in to the function but dead. Remove it from entry live-in set.
781 if (mf_->begin()->isLiveIn(li.reg))
782 mf_->begin()->removeLiveIn(li.reg);
783 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
784 removeRange(li, LR->start, LR->end, li_, tri_);
785 return removeIntervalIfEmpty(li, li_, tri_);
788 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
790 // Livein but defined by a phi.
793 unsigned RemoveStart = LR->start;
794 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
795 if (LR->end > RemoveEnd)
796 // More uses past this copy? Nothing to do.
799 MachineBasicBlock *CopyMBB = CopyMI->getParent();
800 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
802 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
805 MachineInstr *LastUseMI = LastUse->getParent();
806 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
813 // r1025<dead> = r1024<kill>
814 if (MBBStart < LR->end)
815 removeRange(li, MBBStart, LR->end, li_, tri_);
819 // There are uses before the copy, just shorten the live range to the end
821 LastUse->setIsKill();
822 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
823 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
824 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
826 // Last use is itself an identity code.
827 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
828 LastUseMI->getOperand(DeadIdx).setIsDead();
834 if (LR->start <= MBBStart && LR->end > MBBStart) {
835 if (LR->start == 0) {
836 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
837 // Live-in to the function but dead. Remove it from entry live-in set.
838 mf_->begin()->removeLiveIn(li.reg);
840 // FIXME: Shorten intervals in BBs that reaches this BB.
843 if (LR->valno->def == RemoveStart)
844 // If the def MI defines the val#, propagate the dead marker.
845 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
847 removeRange(li, RemoveStart, LR->end, li_, tri_);
848 return removeIntervalIfEmpty(li, li_, tri_);
851 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
852 /// from an implicit def to another register can be coalesced away.
853 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
855 LiveInterval &ImpLi) const{
856 if (!CopyMI->killsRegister(ImpLi.reg))
858 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
859 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
862 if (LR->valno->hasPHIKill)
864 if (LR->valno->def != CopyIdx)
866 // Make sure all of val# uses are copies.
867 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
868 UE = mri_->use_end(); UI != UE;) {
869 MachineInstr *UseMI = &*UI;
871 if (JoinedCopies.count(UseMI))
873 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
874 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
875 if (ULR == li.end() || ULR->valno != LR->valno)
877 // If the use is not a use, then it's not safe to coalesce the move.
878 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
879 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
880 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
881 UseMI->getOperand(1).getReg() == li.reg)
890 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
891 /// def and it is being removed. Turn all copies from this value# into
892 /// identity copies so they will be removed.
893 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
895 SmallVector<MachineInstr*, 4> ImpDefs;
896 MachineOperand *LastUse = NULL;
897 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
898 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
899 RE = mri_->reg_end(); RI != RE;) {
900 MachineOperand *MO = &RI.getOperand();
901 MachineInstr *MI = &*RI;
904 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
905 ImpDefs.push_back(MI);
909 if (JoinedCopies.count(MI))
911 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
912 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
913 if (ULR == li.end() || ULR->valno != VNI)
915 // If the use is a copy, turn it into an identity copy.
916 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
917 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
919 // Each use MI may have multiple uses of this register. Change them all.
920 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
921 MachineOperand &MO = MI->getOperand(i);
922 if (MO.isReg() && MO.getReg() == li.reg)
925 JoinedCopies.insert(MI);
926 } else if (UseIdx > LastUseIdx) {
932 LastUse->setIsKill();
934 // Remove dead implicit_def's.
935 while (!ImpDefs.empty()) {
936 MachineInstr *ImpDef = ImpDefs.back();
938 li_->RemoveMachineInstrFromMaps(ImpDef);
939 ImpDef->eraseFromParent();
944 /// getMatchingSuperReg - Return a super-register of the specified register
945 /// Reg so its sub-register of index SubIdx is Reg.
946 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
947 const TargetRegisterClass *RC,
948 const TargetRegisterInfo* TRI) {
949 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
950 unsigned SR = *SRs; ++SRs)
951 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
956 /// isProfitableToCoalesceToSubRC - Given that register class of DstReg is
957 /// a subset of the register class of SrcReg, return true if it's profitable
958 /// to coalesce the two registers.
960 SimpleRegisterCoalescing::isProfitableToCoalesceToSubRC(unsigned SrcReg,
962 MachineBasicBlock *MBB){
966 // First let's make sure all uses are in the same MBB.
967 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(SrcReg),
968 RE = mri_->reg_end(); RI != RE; ++RI) {
969 MachineInstr &MI = *RI;
970 if (MI.getParent() != MBB)
973 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(DstReg),
974 RE = mri_->reg_end(); RI != RE; ++RI) {
975 MachineInstr &MI = *RI;
976 if (MI.getParent() != MBB)
980 // Then make sure the intervals are *short*.
981 LiveInterval &SrcInt = li_->getInterval(SrcReg);
982 LiveInterval &DstInt = li_->getInterval(DstReg);
983 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
984 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
985 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
986 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
987 return (SrcSize + DstSize) <= Threshold;
990 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
991 /// register with a physical register, check if any of the virtual register
992 /// operand is a sub-register use or def. If so, make sure it won't result
993 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
994 /// vr1024 = extract_subreg vr1025, 1
996 /// vr1024 = mov8rr AH
997 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
998 /// AH does not have a super-reg whose sub-register 1 is AH.
1000 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
1003 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
1004 E = mri_->reg_end(); I != E; ++I) {
1005 MachineOperand &O = I.getOperand();
1006 MachineInstr *MI = &*I;
1007 if (MI == CopyMI || JoinedCopies.count(MI))
1009 unsigned SubIdx = O.getSubReg();
1010 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
1012 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1013 SubIdx = MI->getOperand(2).getImm();
1014 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
1017 unsigned SrcReg = MI->getOperand(1).getReg();
1018 const TargetRegisterClass *RC =
1019 TargetRegisterInfo::isPhysicalRegister(SrcReg)
1020 ? tri_->getPhysicalRegisterRegClass(SrcReg)
1021 : mri_->getRegClass(SrcReg);
1022 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1026 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1027 SubIdx = MI->getOperand(3).getImm();
1028 if (VirtReg == MI->getOperand(0).getReg()) {
1029 if (!tri_->getSubReg(PhysReg, SubIdx))
1032 unsigned DstReg = MI->getOperand(0).getReg();
1033 const TargetRegisterClass *RC =
1034 TargetRegisterInfo::isPhysicalRegister(DstReg)
1035 ? tri_->getPhysicalRegisterRegClass(DstReg)
1036 : mri_->getRegClass(DstReg);
1037 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
1046 /// CanJoinExtractSubRegToPhysReg - Return true if it's possible to coalesce
1047 /// an extract_subreg where dst is a physical register, e.g.
1048 /// cl = EXTRACT_SUBREG reg1024, 1
1050 SimpleRegisterCoalescing::CanJoinExtractSubRegToPhysReg(MachineInstr *CopyMI,
1051 unsigned DstReg, unsigned SrcReg,
1052 unsigned SubIdx, unsigned &RealDstReg) {
1053 if (CopyMI->getOperand(1).getSubReg()) {
1054 DOUT << "\tSrc of extract_subreg already coalesced with reg"
1055 << " of a super-class.\n";
1056 return false; // Not coalescable.
1059 const TargetRegisterClass *RC = mri_->getRegClass(SrcReg);
1060 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
1061 assert(RealDstReg && "Invalid extract_subreg instruction!");
1063 // For this type of EXTRACT_SUBREG, conservatively
1064 // check if the live interval of the source register interfere with the
1065 // actual super physical register we are trying to coalesce with.
1066 LiveInterval &RHS = li_->getInterval(SrcReg);
1067 if (li_->hasInterval(RealDstReg) &&
1068 RHS.overlaps(li_->getInterval(RealDstReg))) {
1069 DOUT << "Interfere with register ";
1070 DEBUG(li_->getInterval(RealDstReg).print(DOUT, tri_));
1071 return false; // Not coalescable
1073 for (const unsigned* SR = tri_->getSubRegisters(RealDstReg); *SR; ++SR)
1074 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1075 DOUT << "Interfere with sub-register ";
1076 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1077 return false; // Not coalescable
1082 /// CanJoinInsertSubRegToPhysReg - Return true if it's possible to coalesce
1083 /// an insert_subreg where src is a physical register, e.g.
1084 /// reg1024 = INSERT_SUBREG reg1024, c1, 0
1086 SimpleRegisterCoalescing::CanJoinInsertSubRegToPhysReg(MachineInstr *CopyMI,
1087 unsigned DstReg, unsigned SrcReg,
1088 unsigned SubIdx, unsigned &RealSrcReg) {
1089 if (CopyMI->getOperand(1).getSubReg()) {
1090 DOUT << "\tSrc of insert_subreg already coalesced with reg"
1091 << " of a super-class.\n";
1092 return false; // Not coalescable.
1094 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
1095 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
1096 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1098 LiveInterval &RHS = li_->getInterval(DstReg);
1099 if (li_->hasInterval(RealSrcReg) &&
1100 RHS.overlaps(li_->getInterval(RealSrcReg))) {
1101 DOUT << "Interfere with register ";
1102 DEBUG(li_->getInterval(RealSrcReg).print(DOUT, tri_));
1103 return false; // Not coalescable
1105 for (const unsigned* SR = tri_->getSubRegisters(RealSrcReg); *SR; ++SR)
1106 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1107 DOUT << "Interfere with sub-register ";
1108 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1109 return false; // Not coalescable
1115 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1116 /// which are the src/dst of the copy instruction CopyMI. This returns true
1117 /// if the copy was successfully coalesced away. If it is not currently
1118 /// possible to coalesce this interval, but it may be possible if other
1119 /// things get coalesced, then it returns true by reference in 'Again'.
1120 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
1121 MachineInstr *CopyMI = TheCopy.MI;
1124 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1125 return false; // Already done.
1127 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
1129 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1130 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
1131 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1132 unsigned SubIdx = 0;
1134 DstReg = CopyMI->getOperand(0).getReg();
1135 SrcReg = CopyMI->getOperand(1).getReg();
1136 } else if (isInsSubReg) {
1137 if (CopyMI->getOperand(2).getSubReg()) {
1138 DOUT << "\tSource of insert_subreg is already coalesced "
1139 << "to another register.\n";
1140 return false; // Not coalescable.
1142 DstReg = CopyMI->getOperand(0).getReg();
1143 SrcReg = CopyMI->getOperand(2).getReg();
1144 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)){
1145 assert(0 && "Unrecognized copy instruction!");
1149 // If they are already joined we continue.
1150 if (SrcReg == DstReg) {
1151 DOUT << "\tCopy already coalesced.\n";
1152 return false; // Not coalescable.
1155 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1156 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1158 // If they are both physical registers, we cannot join them.
1159 if (SrcIsPhys && DstIsPhys) {
1160 DOUT << "\tCan not coalesce physregs.\n";
1161 return false; // Not coalescable.
1164 // We only join virtual registers with allocatable physical registers.
1165 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1166 DOUT << "\tSrc reg is unallocatable physreg.\n";
1167 return false; // Not coalescable.
1169 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1170 DOUT << "\tDst reg is unallocatable physreg.\n";
1171 return false; // Not coalescable.
1174 // Should be non-null only when coalescing to a sub-register class.
1175 const TargetRegisterClass *SubRC = NULL;
1176 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1177 unsigned RealDstReg = 0;
1178 unsigned RealSrcReg = 0;
1179 if (isExtSubReg || isInsSubReg) {
1180 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1181 if (SrcIsPhys && isExtSubReg) {
1182 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1183 // coalesced with AX.
1184 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1186 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1187 // coalesced to a larger register so the subreg indices cancel out.
1188 if (DstSubIdx != SubIdx) {
1189 DOUT << "\t Sub-register indices mismatch.\n";
1190 return false; // Not coalescable.
1193 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1195 } else if (DstIsPhys && isInsSubReg) {
1196 // EAX = INSERT_SUBREG EAX, r1024, 0
1197 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1199 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1200 // coalesced to a larger register so the subreg indices cancel out.
1201 if (SrcSubIdx != SubIdx) {
1202 DOUT << "\t Sub-register indices mismatch.\n";
1203 return false; // Not coalescable.
1206 DstReg = tri_->getSubReg(DstReg, SubIdx);
1208 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
1210 if (!CanJoinExtractSubRegToPhysReg(CopyMI, DstReg, SrcReg, SubIdx,
1212 return false; // Not coalescable
1214 if (!CanJoinInsertSubRegToPhysReg(CopyMI, DstReg, SrcReg, SubIdx,
1216 return false; // Not coalescable
1220 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1221 : CopyMI->getOperand(2).getSubReg();
1223 if (OldSubIdx == SubIdx &&
1224 !differingRegisterClasses(SrcReg, DstReg, SubRC))
1225 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1226 // coalesced to a larger register so the subreg indices cancel out.
1227 // Also check if the other larger register is of the same register
1228 // class as the would be resulting register.
1231 DOUT << "\t Sub-register indices mismatch.\n";
1232 return false; // Not coalescable.
1236 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1237 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1238 unsigned LargeRegSize =
1239 li_->getApproximateInstructionCount(li_->getInterval(LargeReg));
1240 unsigned SmallRegSize =
1241 li_->getApproximateInstructionCount(li_->getInterval(SmallReg));
1242 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
1243 unsigned Threshold = allocatableRCRegs_[RC].count();
1244 // Be conservative. If both sides are virtual registers, do not coalesce
1245 // if this will cause a high use density interval to target a smaller
1246 // set of registers.
1247 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
1248 if ((float)std::distance(mri_->use_begin(SmallReg),
1249 mri_->use_end()) / SmallRegSize <
1250 (float)std::distance(mri_->use_begin(LargeReg),
1251 mri_->use_end()) / LargeRegSize) {
1252 Again = true; // May be possible to coalesce later.
1258 } else if (differingRegisterClasses(SrcReg, DstReg, SubRC)) {
1259 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
1260 // with another? If it's the resulting destination register, then
1261 // the subidx must be propagated to uses (but only those defined
1262 // by the EXTRACT_SUBREG). If it's being coalesced into another
1263 // register, it should be safe because register is assumed to have
1264 // the register class of the super-register.
1266 if (!SubRC || !isProfitableToCoalesceToSubRC(SrcReg, DstReg, CopyMBB)) {
1267 // If they are not of the same register class, we cannot join them.
1268 DOUT << "\tSrc/Dest are different register classes.\n";
1269 // Allow the coalescer to try again in case either side gets coalesced to
1270 // a physical register that's compatible with the other side. e.g.
1271 // r1024 = MOV32to32_ r1025
1272 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1273 Again = true; // May be possible to coalesce later.
1278 // Will it create illegal extract_subreg / insert_subreg?
1279 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1281 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1284 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1285 LiveInterval &DstInt = li_->getInterval(DstReg);
1286 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1287 "Register mapping is horribly broken!");
1289 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1290 DOUT << " and "; DstInt.print(DOUT, tri_);
1293 // Check if it is necessary to propagate "isDead" property.
1294 if (!isExtSubReg && !isInsSubReg) {
1295 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1296 bool isDead = mopd->isDead();
1298 // We need to be careful about coalescing a source physical register with a
1299 // virtual register. Once the coalescing is done, it cannot be broken and
1300 // these are not spillable! If the destination interval uses are far away,
1301 // think twice about coalescing them!
1302 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1303 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1304 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1305 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1306 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1307 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1308 if (TheCopy.isBackEdge)
1309 Threshold *= 2; // Favors back edge copies.
1311 // If the virtual register live interval is long but it has low use desity,
1312 // do not join them, instead mark the physical register as its allocation
1314 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1315 if (Length > Threshold &&
1316 (((float)std::distance(mri_->use_begin(JoinVReg), mri_->use_end())
1317 / Length) < (1.0 / Threshold))) {
1318 JoinVInt.preference = JoinPReg;
1320 DOUT << "\tMay tie down a physical register, abort!\n";
1321 Again = true; // May be possible to coalesce later.
1327 // Okay, attempt to join these two intervals. On failure, this returns false.
1328 // Otherwise, if one of the intervals being joined is a physreg, this method
1329 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1330 // been modified, so we can use this information below to update aliases.
1331 bool Swapped = false;
1332 // If SrcInt is implicitly defined, it's safe to coalesce.
1333 bool isEmpty = SrcInt.empty();
1334 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1335 // Only coalesce an empty interval (defined by implicit_def) with
1336 // another interval which has a valno defined by the CopyMI and the CopyMI
1337 // is a kill of the implicit def.
1338 DOUT << "Not profitable!\n";
1342 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1343 // Coalescing failed.
1345 // If definition of source is defined by trivial computation, try
1346 // rematerializing it.
1347 if (!isExtSubReg && !isInsSubReg &&
1348 ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1351 // If we can eliminate the copy without merging the live ranges, do so now.
1352 if (!isExtSubReg && !isInsSubReg &&
1353 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1354 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1355 JoinedCopies.insert(CopyMI);
1359 // Otherwise, we are unable to join the intervals.
1360 DOUT << "Interference!\n";
1361 Again = true; // May be possible to coalesce later.
1365 LiveInterval *ResSrcInt = &SrcInt;
1366 LiveInterval *ResDstInt = &DstInt;
1368 std::swap(SrcReg, DstReg);
1369 std::swap(ResSrcInt, ResDstInt);
1371 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1372 "LiveInterval::join didn't work right!");
1374 // If we're about to merge live ranges into a physical register live interval,
1375 // we have to update any aliased register's live ranges to indicate that they
1376 // have clobbered values for this range.
1377 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1378 // If this is a extract_subreg where dst is a physical register, e.g.
1379 // cl = EXTRACT_SUBREG reg1024, 1
1380 // then create and update the actual physical register allocated to RHS.
1381 if (RealDstReg || RealSrcReg) {
1382 LiveInterval &RealInt =
1383 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1384 SmallSet<const VNInfo*, 4> CopiedValNos;
1385 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1386 E = ResSrcInt->ranges.end(); I != E; ++I) {
1387 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1388 assert(DstLR && "Invalid joined interval!");
1389 const VNInfo *DstValNo = DstLR->valno;
1390 if (CopiedValNos.insert(DstValNo)) {
1391 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1392 li_->getVNInfoAllocator());
1393 ValNo->hasPHIKill = DstValNo->hasPHIKill;
1394 RealInt.addKills(ValNo, DstValNo->kills);
1395 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
1399 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1402 // Update the liveintervals of sub-registers.
1403 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1404 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1405 li_->getVNInfoAllocator());
1408 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1409 // larger super-register.
1410 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1411 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1412 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1413 std::swap(SrcReg, DstReg);
1414 std::swap(ResSrcInt, ResDstInt);
1418 // Coalescing to a virtual register that is of a sub-register class of the
1419 // other. Make sure the resulting register is set to the right register class.
1421 mri_->setRegClass(DstReg, SubRC);
1426 // Add all copies that define val# in the source interval into the queue.
1427 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1428 e = ResSrcInt->vni_end(); i != e; ++i) {
1429 const VNInfo *vni = *i;
1430 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1432 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1433 unsigned NewSrcReg, NewDstReg, NewSrcSubIdx, NewDstSubIdx;
1435 JoinedCopies.count(CopyMI) == 0 &&
1436 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg,
1437 NewSrcSubIdx, NewDstSubIdx)) {
1438 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
1439 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1440 isBackEdgeCopy(CopyMI, DstReg)));
1445 // Remember to delete the copy instruction.
1446 JoinedCopies.insert(CopyMI);
1448 // Some live range has been lengthened due to colaescing, eliminate the
1449 // unnecessary kills.
1450 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1451 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1452 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1457 // r1024 = implicit_def
1460 RemoveDeadImpDef(DstReg, *ResDstInt);
1461 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1463 // SrcReg is guarateed to be the register whose live interval that is
1465 li_->removeInterval(SrcReg);
1468 // Now the copy is being coalesced away, the val# previously defined
1469 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1470 // length interval. Remove the val#.
1471 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1472 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1473 VNInfo *ImpVal = LR->valno;
1474 assert(ImpVal->def == CopyIdx);
1475 unsigned NextDef = LR->end;
1476 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1477 ResDstInt->removeValNo(ImpVal);
1478 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1479 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1480 // Special case: vr1024 = implicit_def
1481 // vr1024 = insert_subreg vr1024, vr1025, c
1482 // The insert_subreg becomes a "copy" that defines a val# which can itself
1483 // be coalesced away.
1484 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1485 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1486 LR->valno->copy = DefMI;
1490 // If resulting interval has a preference that no longer fits because of subreg
1491 // coalescing, just clear the preference.
1492 if (ResDstInt->preference && (isExtSubReg || isInsSubReg) &&
1493 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1494 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1495 if (!RC->contains(ResDstInt->preference))
1496 ResDstInt->preference = 0;
1499 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1506 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1507 /// compute what the resultant value numbers for each value in the input two
1508 /// ranges will be. This is complicated by copies between the two which can
1509 /// and will commonly cause multiple value numbers to be merged into one.
1511 /// VN is the value number that we're trying to resolve. InstDefiningValue
1512 /// keeps track of the new InstDefiningValue assignment for the result
1513 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1514 /// whether a value in this or other is a copy from the opposite set.
1515 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1516 /// already been assigned.
1518 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1519 /// contains the value number the copy is from.
1521 static unsigned ComputeUltimateVN(VNInfo *VNI,
1522 SmallVector<VNInfo*, 16> &NewVNInfo,
1523 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1524 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1525 SmallVector<int, 16> &ThisValNoAssignments,
1526 SmallVector<int, 16> &OtherValNoAssignments) {
1527 unsigned VN = VNI->id;
1529 // If the VN has already been computed, just return it.
1530 if (ThisValNoAssignments[VN] >= 0)
1531 return ThisValNoAssignments[VN];
1532 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1534 // If this val is not a copy from the other val, then it must be a new value
1535 // number in the destination.
1536 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1537 if (I == ThisFromOther.end()) {
1538 NewVNInfo.push_back(VNI);
1539 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1541 VNInfo *OtherValNo = I->second;
1543 // Otherwise, this *is* a copy from the RHS. If the other side has already
1544 // been computed, return it.
1545 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1546 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1548 // Mark this value number as currently being computed, then ask what the
1549 // ultimate value # of the other value is.
1550 ThisValNoAssignments[VN] = -2;
1551 unsigned UltimateVN =
1552 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1553 OtherValNoAssignments, ThisValNoAssignments);
1554 return ThisValNoAssignments[VN] = UltimateVN;
1557 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1558 return std::find(V.begin(), V.end(), Val) != V.end();
1561 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1562 /// the specified live interval is defined by a copy from the specified
1564 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1567 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1570 if (LR->valno->def == ~0U &&
1571 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1572 *tri_->getSuperRegisters(li.reg)) {
1573 // It's a sub-register live interval, we may not have precise information.
1575 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1576 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1578 tii_->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
1579 DstReg == li.reg && SrcReg == Reg) {
1580 // Cache computed info.
1581 LR->valno->def = LR->start;
1582 LR->valno->copy = DefMI;
1589 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1590 /// caller of this method must guarantee that the RHS only contains a single
1591 /// value number and that the RHS is not defined by a copy from this
1592 /// interval. This returns false if the intervals are not joinable, or it
1593 /// joins them and returns true.
1594 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1595 assert(RHS.containsOneValue());
1597 // Some number (potentially more than one) value numbers in the current
1598 // interval may be defined as copies from the RHS. Scan the overlapping
1599 // portions of the LHS and RHS, keeping track of this and looking for
1600 // overlapping live ranges that are NOT defined as copies. If these exist, we
1603 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1604 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1606 if (LHSIt->start < RHSIt->start) {
1607 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1608 if (LHSIt != LHS.begin()) --LHSIt;
1609 } else if (RHSIt->start < LHSIt->start) {
1610 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1611 if (RHSIt != RHS.begin()) --RHSIt;
1614 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1617 // Determine if these live intervals overlap.
1618 bool Overlaps = false;
1619 if (LHSIt->start <= RHSIt->start)
1620 Overlaps = LHSIt->end > RHSIt->start;
1622 Overlaps = RHSIt->end > LHSIt->start;
1624 // If the live intervals overlap, there are two interesting cases: if the
1625 // LHS interval is defined by a copy from the RHS, it's ok and we record
1626 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1627 // coalesce these live ranges and we bail out.
1629 // If we haven't already recorded that this value # is safe, check it.
1630 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1631 // Copy from the RHS?
1632 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1633 return false; // Nope, bail out.
1635 if (LHSIt->contains(RHSIt->valno->def))
1636 // Here is an interesting situation:
1638 // vr1025 = copy vr1024
1643 // Even though vr1025 is copied from vr1024, it's not safe to
1644 // coalesced them since live range of vr1025 intersects the
1645 // def of vr1024. This happens because vr1025 is assigned the
1646 // value of the previous iteration of vr1024.
1648 EliminatedLHSVals.push_back(LHSIt->valno);
1651 // We know this entire LHS live range is okay, so skip it now.
1652 if (++LHSIt == LHSEnd) break;
1656 if (LHSIt->end < RHSIt->end) {
1657 if (++LHSIt == LHSEnd) break;
1659 // One interesting case to check here. It's possible that we have
1660 // something like "X3 = Y" which defines a new value number in the LHS,
1661 // and is the last use of this liverange of the RHS. In this case, we
1662 // want to notice this copy (so that it gets coalesced away) even though
1663 // the live ranges don't actually overlap.
1664 if (LHSIt->start == RHSIt->end) {
1665 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1666 // We already know that this value number is going to be merged in
1667 // if coalescing succeeds. Just skip the liverange.
1668 if (++LHSIt == LHSEnd) break;
1670 // Otherwise, if this is a copy from the RHS, mark it as being merged
1672 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1673 if (LHSIt->contains(RHSIt->valno->def))
1674 // Here is an interesting situation:
1676 // vr1025 = copy vr1024
1681 // Even though vr1025 is copied from vr1024, it's not safe to
1682 // coalesced them since live range of vr1025 intersects the
1683 // def of vr1024. This happens because vr1025 is assigned the
1684 // value of the previous iteration of vr1024.
1686 EliminatedLHSVals.push_back(LHSIt->valno);
1688 // We know this entire LHS live range is okay, so skip it now.
1689 if (++LHSIt == LHSEnd) break;
1694 if (++RHSIt == RHSEnd) break;
1698 // If we got here, we know that the coalescing will be successful and that
1699 // the value numbers in EliminatedLHSVals will all be merged together. Since
1700 // the most common case is that EliminatedLHSVals has a single number, we
1701 // optimize for it: if there is more than one value, we merge them all into
1702 // the lowest numbered one, then handle the interval as if we were merging
1703 // with one value number.
1704 VNInfo *LHSValNo = NULL;
1705 if (EliminatedLHSVals.size() > 1) {
1706 // Loop through all the equal value numbers merging them into the smallest
1708 VNInfo *Smallest = EliminatedLHSVals[0];
1709 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1710 if (EliminatedLHSVals[i]->id < Smallest->id) {
1711 // Merge the current notion of the smallest into the smaller one.
1712 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1713 Smallest = EliminatedLHSVals[i];
1715 // Merge into the smallest.
1716 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1719 LHSValNo = Smallest;
1720 } else if (EliminatedLHSVals.empty()) {
1721 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1722 *tri_->getSuperRegisters(LHS.reg))
1723 // Imprecise sub-register information. Can't handle it.
1725 assert(0 && "No copies from the RHS?");
1727 LHSValNo = EliminatedLHSVals[0];
1730 // Okay, now that there is a single LHS value number that we're merging the
1731 // RHS into, update the value number info for the LHS to indicate that the
1732 // value number is defined where the RHS value number was.
1733 const VNInfo *VNI = RHS.getValNumInfo(0);
1734 LHSValNo->def = VNI->def;
1735 LHSValNo->copy = VNI->copy;
1737 // Okay, the final step is to loop over the RHS live intervals, adding them to
1739 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1740 LHS.addKills(LHSValNo, VNI->kills);
1741 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1742 LHS.weight += RHS.weight;
1743 if (RHS.preference && !LHS.preference)
1744 LHS.preference = RHS.preference;
1749 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1750 /// returns false. Otherwise, if one of the intervals being joined is a
1751 /// physreg, this method always canonicalizes LHS to be it. The output
1752 /// "RHS" will not have been modified, so we can use this information
1753 /// below to update aliases.
1755 SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS,
1757 // Compute the final value assignment, assuming that the live ranges can be
1759 SmallVector<int, 16> LHSValNoAssignments;
1760 SmallVector<int, 16> RHSValNoAssignments;
1761 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1762 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1763 SmallVector<VNInfo*, 16> NewVNInfo;
1765 // If a live interval is a physical register, conservatively check if any
1766 // of its sub-registers is overlapping the live interval of the virtual
1767 // register. If so, do not coalesce.
1768 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1769 *tri_->getSubRegisters(LHS.reg)) {
1770 // If it's coalescing a virtual register to a physical register, estimate
1771 // its live interval length. This is the *cost* of scanning an entire live
1772 // interval. If the cost is low, we'll do an exhaustive check instead.
1774 // If this is something like this:
1782 // That is, the live interval of v1024 crosses a bb. Then we can't rely on
1783 // less conservative check. It's possible a sub-register is defined before
1784 // v1024 (or live in) and live out of BB1.
1785 if (RHS.containsOneValue() &&
1786 li_->intervalIsInOneMBB(RHS) &&
1787 li_->getApproximateInstructionCount(RHS) <= 10) {
1788 // Perform a more exhaustive check for some common cases.
1789 if (li_->conflictsWithPhysRegRef(RHS, LHS.reg, true, JoinedCopies))
1792 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1793 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1794 DOUT << "Interfere with sub-register ";
1795 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1799 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1800 *tri_->getSubRegisters(RHS.reg)) {
1801 if (LHS.containsOneValue() &&
1802 li_->getApproximateInstructionCount(LHS) <= 10) {
1803 // Perform a more exhaustive check for some common cases.
1804 if (li_->conflictsWithPhysRegRef(LHS, RHS.reg, false, JoinedCopies))
1807 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1808 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1809 DOUT << "Interfere with sub-register ";
1810 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1816 // Compute ultimate value numbers for the LHS and RHS values.
1817 if (RHS.containsOneValue()) {
1818 // Copies from a liveinterval with a single value are simple to handle and
1819 // very common, handle the special case here. This is important, because
1820 // often RHS is small and LHS is large (e.g. a physreg).
1822 // Find out if the RHS is defined as a copy from some value in the LHS.
1823 int RHSVal0DefinedFromLHS = -1;
1825 VNInfo *RHSValNoInfo = NULL;
1826 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1827 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1828 if (RHSSrcReg == 0 || RHSSrcReg != LHS.reg) {
1829 // If RHS is not defined as a copy from the LHS, we can use simpler and
1830 // faster checks to see if the live ranges are coalescable. This joiner
1831 // can't swap the LHS/RHS intervals though.
1832 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1833 return SimpleJoin(LHS, RHS);
1835 RHSValNoInfo = RHSValNoInfo0;
1838 // It was defined as a copy from the LHS, find out what value # it is.
1839 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1840 RHSValID = RHSValNoInfo->id;
1841 RHSVal0DefinedFromLHS = RHSValID;
1844 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1845 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1846 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1848 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1849 // should now get updated.
1850 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1853 unsigned VN = VNI->id;
1854 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1855 if (LHSSrcReg != RHS.reg) {
1856 // If this is not a copy from the RHS, its value number will be
1857 // unmodified by the coalescing.
1858 NewVNInfo[VN] = VNI;
1859 LHSValNoAssignments[VN] = VN;
1860 } else if (RHSValID == -1) {
1861 // Otherwise, it is a copy from the RHS, and we don't already have a
1862 // value# for it. Keep the current value number, but remember it.
1863 LHSValNoAssignments[VN] = RHSValID = VN;
1864 NewVNInfo[VN] = RHSValNoInfo;
1865 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1867 // Otherwise, use the specified value #.
1868 LHSValNoAssignments[VN] = RHSValID;
1869 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1870 NewVNInfo[VN] = RHSValNoInfo;
1871 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1875 NewVNInfo[VN] = VNI;
1876 LHSValNoAssignments[VN] = VN;
1880 assert(RHSValID != -1 && "Didn't find value #?");
1881 RHSValNoAssignments[0] = RHSValID;
1882 if (RHSVal0DefinedFromLHS != -1) {
1883 // This path doesn't go through ComputeUltimateVN so just set
1885 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1888 // Loop over the value numbers of the LHS, seeing if any are defined from
1890 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1893 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1896 // DstReg is known to be a register in the LHS interval. If the src is
1897 // from the RHS interval, we can use its value #.
1898 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1901 // Figure out the value # from the RHS.
1902 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1905 // Loop over the value numbers of the RHS, seeing if any are defined from
1907 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1910 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1913 // DstReg is known to be a register in the RHS interval. If the src is
1914 // from the LHS interval, we can use its value #.
1915 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1918 // Figure out the value # from the LHS.
1919 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1922 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1923 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1924 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1926 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1929 unsigned VN = VNI->id;
1930 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1932 ComputeUltimateVN(VNI, NewVNInfo,
1933 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1934 LHSValNoAssignments, RHSValNoAssignments);
1936 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1939 unsigned VN = VNI->id;
1940 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1942 // If this value number isn't a copy from the LHS, it's a new number.
1943 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1944 NewVNInfo.push_back(VNI);
1945 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1949 ComputeUltimateVN(VNI, NewVNInfo,
1950 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1951 RHSValNoAssignments, LHSValNoAssignments);
1955 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1956 // interval lists to see if these intervals are coalescable.
1957 LiveInterval::const_iterator I = LHS.begin();
1958 LiveInterval::const_iterator IE = LHS.end();
1959 LiveInterval::const_iterator J = RHS.begin();
1960 LiveInterval::const_iterator JE = RHS.end();
1962 // Skip ahead until the first place of potential sharing.
1963 if (I->start < J->start) {
1964 I = std::upper_bound(I, IE, J->start);
1965 if (I != LHS.begin()) --I;
1966 } else if (J->start < I->start) {
1967 J = std::upper_bound(J, JE, I->start);
1968 if (J != RHS.begin()) --J;
1972 // Determine if these two live ranges overlap.
1974 if (I->start < J->start) {
1975 Overlaps = I->end > J->start;
1977 Overlaps = J->end > I->start;
1980 // If so, check value # info to determine if they are really different.
1982 // If the live range overlap will map to the same value number in the
1983 // result liverange, we can still coalesce them. If not, we can't.
1984 if (LHSValNoAssignments[I->valno->id] !=
1985 RHSValNoAssignments[J->valno->id])
1989 if (I->end < J->end) {
1998 // Update kill info. Some live ranges are extended due to copy coalescing.
1999 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
2000 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
2001 VNInfo *VNI = I->first;
2002 unsigned LHSValID = LHSValNoAssignments[VNI->id];
2003 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
2004 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
2005 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
2008 // Update kill info. Some live ranges are extended due to copy coalescing.
2009 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
2010 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
2011 VNInfo *VNI = I->first;
2012 unsigned RHSValID = RHSValNoAssignments[VNI->id];
2013 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
2014 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
2015 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
2018 // If we get here, we know that we can coalesce the live ranges. Ask the
2019 // intervals to coalesce themselves now.
2020 if ((RHS.ranges.size() > LHS.ranges.size() &&
2021 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
2022 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
2023 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
2026 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
2033 // DepthMBBCompare - Comparison predicate that sort first based on the loop
2034 // depth of the basic block (the unsigned), and then on the MBB number.
2035 struct DepthMBBCompare {
2036 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
2037 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
2038 if (LHS.first > RHS.first) return true; // Deeper loops first
2039 return LHS.first == RHS.first &&
2040 LHS.second->getNumber() < RHS.second->getNumber();
2045 /// getRepIntervalSize - Returns the size of the interval that represents the
2046 /// specified register.
2048 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
2049 return Rc->getRepIntervalSize(Reg);
2052 /// CopyRecSort::operator - Join priority queue sorting function.
2054 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
2055 // Inner loops first.
2056 if (left.LoopDepth > right.LoopDepth)
2058 else if (left.LoopDepth == right.LoopDepth)
2059 if (left.isBackEdge && !right.isBackEdge)
2064 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
2065 std::vector<CopyRec> &TryAgain) {
2066 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
2068 std::vector<CopyRec> VirtCopies;
2069 std::vector<CopyRec> PhysCopies;
2070 std::vector<CopyRec> ImpDefCopies;
2071 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
2072 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2074 MachineInstr *Inst = MII++;
2076 // If this isn't a copy nor a extract_subreg, we can't join intervals.
2077 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2078 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
2079 DstReg = Inst->getOperand(0).getReg();
2080 SrcReg = Inst->getOperand(1).getReg();
2081 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
2082 DstReg = Inst->getOperand(0).getReg();
2083 SrcReg = Inst->getOperand(2).getReg();
2084 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
2087 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
2088 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
2090 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
2092 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
2093 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
2094 else if (SrcIsPhys || DstIsPhys)
2095 PhysCopies.push_back(CopyRec(Inst, 0, false));
2097 VirtCopies.push_back(CopyRec(Inst, 0, false));
2104 // Try coalescing implicit copies first, followed by copies to / from
2105 // physical registers, then finally copies from virtual registers to
2106 // virtual registers.
2107 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
2108 CopyRec &TheCopy = ImpDefCopies[i];
2110 if (!JoinCopy(TheCopy, Again))
2112 TryAgain.push_back(TheCopy);
2114 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
2115 CopyRec &TheCopy = PhysCopies[i];
2117 if (!JoinCopy(TheCopy, Again))
2119 TryAgain.push_back(TheCopy);
2121 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
2122 CopyRec &TheCopy = VirtCopies[i];
2124 if (!JoinCopy(TheCopy, Again))
2126 TryAgain.push_back(TheCopy);
2130 void SimpleRegisterCoalescing::joinIntervals() {
2131 DOUT << "********** JOINING INTERVALS ***********\n";
2134 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
2136 std::vector<CopyRec> TryAgainList;
2137 if (loopInfo->empty()) {
2138 // If there are no loops in the function, join intervals in function order.
2139 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2141 CopyCoalesceInMBB(I, TryAgainList);
2143 // Otherwise, join intervals in inner loops before other intervals.
2144 // Unfortunately we can't just iterate over loop hierarchy here because
2145 // there may be more MBB's than BB's. Collect MBB's for sorting.
2147 // Join intervals in the function prolog first. We want to join physical
2148 // registers with virtual registers before the intervals got too long.
2149 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2150 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2151 MachineBasicBlock *MBB = I;
2152 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2155 // Sort by loop depth.
2156 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2158 // Finally, join intervals in loop nest order.
2159 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2160 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2163 // Joining intervals can allow other intervals to be joined. Iteratively join
2164 // until we make no progress.
2166 SmallVector<CopyRec, 16> TryAgain;
2167 bool ProgressMade = true;
2168 while (ProgressMade) {
2169 ProgressMade = false;
2170 while (!JoinQueue->empty()) {
2171 CopyRec R = JoinQueue->pop();
2173 bool Success = JoinCopy(R, Again);
2175 ProgressMade = true;
2177 TryAgain.push_back(R);
2181 while (!TryAgain.empty()) {
2182 JoinQueue->push(TryAgain.back());
2183 TryAgain.pop_back();
2188 bool ProgressMade = true;
2189 while (ProgressMade) {
2190 ProgressMade = false;
2192 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2193 CopyRec &TheCopy = TryAgainList[i];
2196 bool Success = JoinCopy(TheCopy, Again);
2197 if (Success || !Again) {
2198 TheCopy.MI = 0; // Mark this one as done.
2199 ProgressMade = true;
2210 /// Return true if the two specified registers belong to different register
2211 /// classes. The registers may be either phys or virt regs. In the
2212 /// case where both registers are virtual registers, it would also returns
2213 /// true by reference the RegB register class in SubRC if it is a subset of
2214 /// RegA's register class.
2216 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA, unsigned RegB,
2217 const TargetRegisterClass *&SubRC) const {
2219 // Get the register classes for the first reg.
2220 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2221 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2222 "Shouldn't consider two physregs!");
2223 return !mri_->getRegClass(RegB)->contains(RegA);
2226 // Compare against the regclass for the second reg.
2227 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2228 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2229 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2230 if (RegClassA == RegClassB)
2232 SubRC = (RegClassA->hasSubClass(RegClassB)) ? RegClassB : NULL;
2235 return !RegClassA->contains(RegB);
2238 /// lastRegisterUse - Returns the last use of the specific register between
2239 /// cycles Start and End or NULL if there are no uses.
2241 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
2242 unsigned Reg, unsigned &UseIdx) const{
2244 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2245 MachineOperand *LastUse = NULL;
2246 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2247 E = mri_->use_end(); I != E; ++I) {
2248 MachineOperand &Use = I.getOperand();
2249 MachineInstr *UseMI = Use.getParent();
2250 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2251 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2253 // Ignore identity copies.
2255 unsigned Idx = li_->getInstructionIndex(UseMI);
2256 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2264 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2267 // Skip deleted instructions
2268 MachineInstr *MI = li_->getInstructionFromIndex(e);
2269 while ((e - InstrSlots::NUM) >= s && !MI) {
2270 e -= InstrSlots::NUM;
2271 MI = li_->getInstructionFromIndex(e);
2273 if (e < s || MI == NULL)
2276 // Ignore identity copies.
2277 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2278 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
2280 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2281 MachineOperand &Use = MI->getOperand(i);
2282 if (Use.isReg() && Use.isUse() && Use.getReg() &&
2283 tri_->regsOverlap(Use.getReg(), Reg)) {
2289 e -= InstrSlots::NUM;
2296 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2297 if (TargetRegisterInfo::isPhysicalRegister(reg))
2298 cerr << tri_->getName(reg);
2300 cerr << "%reg" << reg;
2303 void SimpleRegisterCoalescing::releaseMemory() {
2304 JoinedCopies.clear();
2305 ReMatCopies.clear();
2309 static bool isZeroLengthInterval(LiveInterval *li) {
2310 for (LiveInterval::Ranges::const_iterator
2311 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2312 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2317 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2318 /// turn the copy into an implicit def.
2320 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2321 MachineBasicBlock *MBB,
2322 unsigned DstReg, unsigned SrcReg) {
2323 MachineInstr *CopyMI = &*I;
2324 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2325 if (!li_->hasInterval(SrcReg))
2327 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2328 if (!SrcInt.empty())
2330 if (!li_->hasInterval(DstReg))
2332 LiveInterval &DstInt = li_->getInterval(DstReg);
2333 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
2334 DstInt.removeValNo(DstLR->valno);
2335 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2336 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2337 CopyMI->RemoveOperand(i);
2338 bool NoUse = mri_->use_empty(SrcReg);
2340 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2341 E = mri_->reg_end(); I != E; ) {
2342 assert(I.getOperand().isDef());
2343 MachineInstr *DefMI = &*I;
2345 // The implicit_def source has no other uses, delete it.
2346 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2347 li_->RemoveMachineInstrFromMaps(DefMI);
2348 DefMI->eraseFromParent();
2356 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2358 mri_ = &fn.getRegInfo();
2359 tm_ = &fn.getTarget();
2360 tri_ = tm_->getRegisterInfo();
2361 tii_ = tm_->getInstrInfo();
2362 li_ = &getAnalysis<LiveIntervals>();
2363 loopInfo = &getAnalysis<MachineLoopInfo>();
2365 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2366 << "********** Function: "
2367 << ((Value*)mf_->getFunction())->getName() << '\n';
2369 allocatableRegs_ = tri_->getAllocatableSet(fn);
2370 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2371 E = tri_->regclass_end(); I != E; ++I)
2372 allocatableRCRegs_.insert(std::make_pair(*I,
2373 tri_->getAllocatableSet(fn, *I)));
2375 // Join (coalesce) intervals if requested.
2376 if (EnableJoining) {
2379 DOUT << "********** INTERVALS POST JOINING **********\n";
2380 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2381 I->second->print(DOUT, tri_);
2387 // Perform a final pass over the instructions and compute spill weights
2388 // and remove identity moves.
2389 SmallVector<unsigned, 4> DeadDefs;
2390 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2391 mbbi != mbbe; ++mbbi) {
2392 MachineBasicBlock* mbb = mbbi;
2393 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2395 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2397 MachineInstr *MI = mii;
2398 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
2399 if (JoinedCopies.count(MI)) {
2400 // Delete all coalesced copies.
2401 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
2402 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2403 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2404 "Unrecognized copy instruction");
2405 DstReg = MI->getOperand(0).getReg();
2407 if (MI->registerDefIsDead(DstReg)) {
2408 LiveInterval &li = li_->getInterval(DstReg);
2409 if (!ShortenDeadCopySrcLiveRange(li, MI))
2410 ShortenDeadCopyLiveRange(li, MI);
2412 li_->RemoveMachineInstrFromMaps(MI);
2413 mii = mbbi->erase(mii);
2418 // Now check if this is a remat'ed def instruction which is now dead.
2419 if (ReMatDefs.count(MI)) {
2421 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2422 const MachineOperand &MO = MI->getOperand(i);
2425 unsigned Reg = MO.getReg();
2426 if (TargetRegisterInfo::isVirtualRegister(Reg))
2427 DeadDefs.push_back(Reg);
2430 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
2431 !mri_->use_empty(Reg)) {
2437 while (!DeadDefs.empty()) {
2438 unsigned DeadDef = DeadDefs.back();
2439 DeadDefs.pop_back();
2440 RemoveDeadDef(li_->getInterval(DeadDef), MI);
2442 li_->RemoveMachineInstrFromMaps(mii);
2443 mii = mbbi->erase(mii);
2449 // If the move will be an identity move delete it
2450 bool isMove= tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
2451 if (isMove && SrcReg == DstReg) {
2452 if (li_->hasInterval(SrcReg)) {
2453 LiveInterval &RegInt = li_->getInterval(SrcReg);
2454 // If def of this move instruction is dead, remove its live range
2455 // from the dstination register's live interval.
2456 if (MI->registerDefIsDead(DstReg)) {
2457 if (!ShortenDeadCopySrcLiveRange(RegInt, MI))
2458 ShortenDeadCopyLiveRange(RegInt, MI);
2461 li_->RemoveMachineInstrFromMaps(MI);
2462 mii = mbbi->erase(mii);
2464 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2465 SmallSet<unsigned, 4> UniqueUses;
2466 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2467 const MachineOperand &mop = MI->getOperand(i);
2468 if (mop.isReg() && mop.getReg() &&
2469 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2470 unsigned reg = mop.getReg();
2471 // Multiple uses of reg by the same instruction. It should not
2472 // contribute to spill weight again.
2473 if (UniqueUses.count(reg) != 0)
2475 LiveInterval &RegInt = li_->getInterval(reg);
2477 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2478 UniqueUses.insert(reg);
2486 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2487 LiveInterval &LI = *I->second;
2488 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2489 // If the live interval length is essentially zero, i.e. in every live
2490 // range the use follows def immediately, it doesn't make sense to spill
2491 // it and hope it will be easier to allocate for this li.
2492 if (isZeroLengthInterval(&LI))
2493 LI.weight = HUGE_VALF;
2495 bool isLoad = false;
2496 SmallVector<LiveInterval*, 4> SpillIs;
2497 if (li_->isReMaterializable(LI, SpillIs, isLoad)) {
2498 // If all of the definitions of the interval are re-materializable,
2499 // it is a preferred candidate for spilling. If non of the defs are
2500 // loads, then it's potentially very cheap to re-materialize.
2501 // FIXME: this gets much more complicated once we support non-trivial
2502 // re-materialization.
2510 // Slightly prefer live interval that has been assigned a preferred reg.
2514 // Divide the weight of the interval by its size. This encourages
2515 // spilling of intervals that are large and have few uses, and
2516 // discourages spilling of small intervals with many uses.
2517 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2525 /// print - Implement the dump method.
2526 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2530 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2531 return new SimpleRegisterCoalescing();
2534 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2535 DEFINING_FILE_FOR(SimpleRegisterCoalescing)