1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
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 the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "regalloc"
17 #include "RegisterCoalescer.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/LiveRangeEdit.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/CodeGen/VirtRegMap.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
45 STATISTIC(numJoins , "Number of interval joins performed");
46 STATISTIC(numCrossRCs , "Number of cross class joins performed");
47 STATISTIC(numCommutes , "Number of instruction commuting performed");
48 STATISTIC(numExtends , "Number of copies extended");
49 STATISTIC(NumReMats , "Number of instructions re-materialized");
50 STATISTIC(NumInflated , "Number of register classes inflated");
51 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
52 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
55 EnableJoining("join-liveintervals",
56 cl::desc("Coalesce copies (default=true)"),
59 // Temporary flag to test critical edge unsplitting.
61 EnableJoinSplits("join-splitedges",
62 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
64 // Temporary flag to test global copy optimization.
65 static cl::opt<cl::boolOrDefault>
66 EnableGlobalCopies("join-globalcopies",
67 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
68 cl::init(cl::BOU_UNSET), cl::Hidden);
71 VerifyCoalescing("verify-coalescing",
72 cl::desc("Verify machine instrs before and after register coalescing"),
76 class RegisterCoalescer : public MachineFunctionPass,
77 private LiveRangeEdit::Delegate {
79 MachineRegisterInfo* MRI;
80 const TargetMachine* TM;
81 const TargetRegisterInfo* TRI;
82 const TargetInstrInfo* TII;
84 const MachineLoopInfo* Loops;
86 RegisterClassInfo RegClassInfo;
88 /// \brief True if the coalescer should aggressively coalesce global copies
89 /// in favor of keeping local copies.
90 bool JoinGlobalCopies;
92 /// \brief True if the coalescer should aggressively coalesce fall-thru
93 /// blocks exclusively containing copies.
96 /// WorkList - Copy instructions yet to be coalesced.
97 SmallVector<MachineInstr*, 8> WorkList;
98 SmallVector<MachineInstr*, 8> LocalWorkList;
100 /// ErasedInstrs - Set of instruction pointers that have been erased, and
101 /// that may be present in WorkList.
102 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
104 /// Dead instructions that are about to be deleted.
105 SmallVector<MachineInstr*, 8> DeadDefs;
107 /// Virtual registers to be considered for register class inflation.
108 SmallVector<unsigned, 8> InflateRegs;
110 /// Recursively eliminate dead defs in DeadDefs.
111 void eliminateDeadDefs();
113 /// LiveRangeEdit callback.
114 void LRE_WillEraseInstruction(MachineInstr *MI) override;
116 /// coalesceLocals - coalesce the LocalWorkList.
117 void coalesceLocals();
119 /// joinAllIntervals - join compatible live intervals
120 void joinAllIntervals();
122 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
123 /// copies that cannot yet be coalesced into WorkList.
124 void copyCoalesceInMBB(MachineBasicBlock *MBB);
126 /// copyCoalesceWorkList - Try to coalesce all copies in CurrList. Return
127 /// true if any progress was made.
128 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
130 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
131 /// which are the src/dst of the copy instruction CopyMI. This returns
132 /// true if the copy was successfully coalesced away. If it is not
133 /// currently possible to coalesce this interval, but it may be possible if
134 /// other things get coalesced, then it returns true by reference in
136 bool joinCopy(MachineInstr *TheCopy, bool &Again);
138 /// joinIntervals - Attempt to join these two intervals. On failure, this
139 /// returns false. The output "SrcInt" will not have been modified, so we
140 /// can use this information below to update aliases.
141 bool joinIntervals(CoalescerPair &CP);
143 /// Attempt joining two virtual registers. Return true on success.
144 bool joinVirtRegs(CoalescerPair &CP);
146 /// Attempt joining with a reserved physreg.
147 bool joinReservedPhysReg(CoalescerPair &CP);
149 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
150 /// the source value number is defined by a copy from the destination reg
151 /// see if we can merge these two destination reg valno# into a single
152 /// value number, eliminating a copy.
153 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
155 /// hasOtherReachingDefs - Return true if there are definitions of IntB
156 /// other than BValNo val# that can reach uses of AValno val# of IntA.
157 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
158 VNInfo *AValNo, VNInfo *BValNo);
160 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
161 /// If the source value number is defined by a commutable instruction and
162 /// its other operand is coalesced to the copy dest register, see if we
163 /// can transform the copy into a noop by commuting the definition.
164 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
166 /// reMaterializeTrivialDef - If the source of a copy is defined by a
167 /// trivial computation, replace the copy by rematerialize the definition.
168 bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI,
171 /// canJoinPhys - Return true if a physreg copy should be joined.
172 bool canJoinPhys(const CoalescerPair &CP);
174 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
175 /// update the subregister number if it is not zero. If DstReg is a
176 /// physical register and the existing subregister number of the def / use
177 /// being updated is not zero, make sure to set it to the correct physical
179 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
181 /// eliminateUndefCopy - Handle copies of undef values.
182 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
185 static char ID; // Class identification, replacement for typeinfo
186 RegisterCoalescer() : MachineFunctionPass(ID) {
187 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
190 void getAnalysisUsage(AnalysisUsage &AU) const override;
192 void releaseMemory() override;
194 /// runOnMachineFunction - pass entry point
195 bool runOnMachineFunction(MachineFunction&) override;
197 /// print - Implement the dump method.
198 void print(raw_ostream &O, const Module* = 0) const override;
200 } /// end anonymous namespace
202 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
204 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
205 "Simple Register Coalescing", false, false)
206 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
207 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
208 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
209 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
210 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
211 "Simple Register Coalescing", false, false)
213 char RegisterCoalescer::ID = 0;
215 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
216 unsigned &Src, unsigned &Dst,
217 unsigned &SrcSub, unsigned &DstSub) {
219 Dst = MI->getOperand(0).getReg();
220 DstSub = MI->getOperand(0).getSubReg();
221 Src = MI->getOperand(1).getReg();
222 SrcSub = MI->getOperand(1).getSubReg();
223 } else if (MI->isSubregToReg()) {
224 Dst = MI->getOperand(0).getReg();
225 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
226 MI->getOperand(3).getImm());
227 Src = MI->getOperand(2).getReg();
228 SrcSub = MI->getOperand(2).getSubReg();
234 // Return true if this block should be vacated by the coalescer to eliminate
235 // branches. The important cases to handle in the coalescer are critical edges
236 // split during phi elimination which contain only copies. Simple blocks that
237 // contain non-branches should also be vacated, but this can be handled by an
238 // earlier pass similar to early if-conversion.
239 static bool isSplitEdge(const MachineBasicBlock *MBB) {
240 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
243 for (MachineBasicBlock::const_iterator MII = MBB->begin(), E = MBB->end();
245 if (!MII->isCopyLike() && !MII->isUnconditionalBranch())
251 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
255 Flipped = CrossClass = false;
257 unsigned Src, Dst, SrcSub, DstSub;
258 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
260 Partial = SrcSub || DstSub;
262 // If one register is a physreg, it must be Dst.
263 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
264 if (TargetRegisterInfo::isPhysicalRegister(Dst))
267 std::swap(SrcSub, DstSub);
271 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
273 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
274 // Eliminate DstSub on a physreg.
276 Dst = TRI.getSubReg(Dst, DstSub);
277 if (!Dst) return false;
281 // Eliminate SrcSub by picking a corresponding Dst superregister.
283 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
284 if (!Dst) return false;
286 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
290 // Both registers are virtual.
291 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
292 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
294 // Both registers have subreg indices.
295 if (SrcSub && DstSub) {
296 // Copies between different sub-registers are never coalescable.
297 if (Src == Dst && SrcSub != DstSub)
300 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
305 // SrcReg will be merged with a sub-register of DstReg.
307 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
309 // DstReg will be merged with a sub-register of SrcReg.
311 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
313 // This is a straight copy without sub-registers.
314 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
317 // The combined constraint may be impossible to satisfy.
321 // Prefer SrcReg to be a sub-register of DstReg.
322 // FIXME: Coalescer should support subregs symmetrically.
323 if (DstIdx && !SrcIdx) {
325 std::swap(SrcIdx, DstIdx);
329 CrossClass = NewRC != DstRC || NewRC != SrcRC;
331 // Check our invariants
332 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
333 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
334 "Cannot have a physical SubIdx");
340 bool CoalescerPair::flip() {
341 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
343 std::swap(SrcReg, DstReg);
344 std::swap(SrcIdx, DstIdx);
349 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
352 unsigned Src, Dst, SrcSub, DstSub;
353 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
356 // Find the virtual register that is SrcReg.
359 std::swap(SrcSub, DstSub);
360 } else if (Src != SrcReg) {
364 // Now check that Dst matches DstReg.
365 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
366 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
368 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
369 // DstSub could be set for a physreg from INSERT_SUBREG.
371 Dst = TRI.getSubReg(Dst, DstSub);
374 return DstReg == Dst;
375 // This is a partial register copy. Check that the parts match.
376 return TRI.getSubReg(DstReg, SrcSub) == Dst;
378 // DstReg is virtual.
381 // Registers match, do the subregisters line up?
382 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
383 TRI.composeSubRegIndices(DstIdx, DstSub);
387 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
388 AU.setPreservesCFG();
389 AU.addRequired<AliasAnalysis>();
390 AU.addRequired<LiveIntervals>();
391 AU.addPreserved<LiveIntervals>();
392 AU.addPreserved<SlotIndexes>();
393 AU.addRequired<MachineLoopInfo>();
394 AU.addPreserved<MachineLoopInfo>();
395 AU.addPreservedID(MachineDominatorsID);
396 MachineFunctionPass::getAnalysisUsage(AU);
399 void RegisterCoalescer::eliminateDeadDefs() {
400 SmallVector<unsigned, 8> NewRegs;
401 LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
404 // Callback from eliminateDeadDefs().
405 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
406 // MI may be in WorkList. Make sure we don't visit it.
407 ErasedInstrs.insert(MI);
410 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
411 /// being the source and IntB being the dest, thus this defines a value number
412 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
413 /// see if we can merge these two pieces of B into a single value number,
414 /// eliminating a copy. For example:
418 /// B1 = A3 <- this copy
420 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
421 /// value number to be replaced with B0 (which simplifies the B liveinterval).
423 /// This returns true if an interval was modified.
425 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
426 MachineInstr *CopyMI) {
427 assert(!CP.isPartial() && "This doesn't work for partial copies.");
428 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
431 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
433 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
434 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
436 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
437 // the example above.
438 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
439 if (BS == IntB.end()) return false;
440 VNInfo *BValNo = BS->valno;
442 // Get the location that B is defined at. Two options: either this value has
443 // an unknown definition point or it is defined at CopyIdx. If unknown, we
445 if (BValNo->def != CopyIdx) return false;
447 // AValNo is the value number in A that defines the copy, A3 in the example.
448 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
449 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
450 // The live segment might not exist after fun with physreg coalescing.
451 if (AS == IntA.end()) return false;
452 VNInfo *AValNo = AS->valno;
454 // If AValNo is defined as a copy from IntB, we can potentially process this.
455 // Get the instruction that defines this value number.
456 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
457 // Don't allow any partial copies, even if isCoalescable() allows them.
458 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
461 // Get the Segment in IntB that this value number starts with.
462 LiveInterval::iterator ValS =
463 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
464 if (ValS == IntB.end())
467 // Make sure that the end of the live segment is inside the same block as
469 MachineInstr *ValSEndInst =
470 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
471 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
474 // Okay, we now know that ValS ends in the same block that the CopyMI
475 // live-range starts. If there are no intervening live segments between them
476 // in IntB, we can merge them.
477 if (ValS+1 != BS) return false;
479 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
481 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
482 // We are about to delete CopyMI, so need to remove it as the 'instruction
483 // that defines this value #'. Update the valnum with the new defining
485 BValNo->def = FillerStart;
487 // Okay, we can merge them. We need to insert a new liverange:
488 // [ValS.end, BS.begin) of either value number, then we merge the
489 // two value numbers.
490 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
492 // Okay, merge "B1" into the same value number as "B0".
493 if (BValNo != ValS->valno)
494 IntB.MergeValueNumberInto(BValNo, ValS->valno);
495 DEBUG(dbgs() << " result = " << IntB << '\n');
497 // If the source instruction was killing the source register before the
498 // merge, unset the isKill marker given the live range has been extended.
499 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
501 ValSEndInst->getOperand(UIdx).setIsKill(false);
504 // Rewrite the copy. If the copy instruction was killing the destination
505 // register before the merge, find the last use and trim the live range. That
506 // will also add the isKill marker.
507 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
508 if (AS->end == CopyIdx)
509 LIS->shrinkToUses(&IntA);
515 /// hasOtherReachingDefs - Return true if there are definitions of IntB
516 /// other than BValNo val# that can reach uses of AValno val# of IntA.
517 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
521 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
523 if (LIS->hasPHIKill(IntA, AValNo))
526 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
528 if (AI->valno != AValNo) continue;
529 LiveInterval::iterator BI =
530 std::upper_bound(IntB.begin(), IntB.end(), AI->start);
531 if (BI != IntB.begin())
533 for (; BI != IntB.end() && AI->end >= BI->start; ++BI) {
534 if (BI->valno == BValNo)
536 if (BI->start <= AI->start && BI->end > AI->start)
538 if (BI->start > AI->start && BI->start < AI->end)
545 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
546 /// IntA being the source and IntB being the dest, thus this defines a value
547 /// number in IntB. If the source value number (in IntA) is defined by a
548 /// commutable instruction and its other operand is coalesced to the copy dest
549 /// register, see if we can transform the copy into a noop by commuting the
550 /// definition. For example,
552 /// A3 = op A2 B0<kill>
554 /// B1 = A3 <- this copy
556 /// = op A3 <- more uses
560 /// B2 = op B0 A2<kill>
562 /// B1 = B2 <- now an identify copy
564 /// = op B2 <- more uses
566 /// This returns true if an interval was modified.
568 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
569 MachineInstr *CopyMI) {
570 assert (!CP.isPhys());
572 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
575 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
577 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
579 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
580 // the example above.
581 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
582 if (!BValNo || BValNo->def != CopyIdx)
585 // AValNo is the value number in A that defines the copy, A3 in the example.
586 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
587 assert(AValNo && "COPY source not live");
588 if (AValNo->isPHIDef() || AValNo->isUnused())
590 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
593 if (!DefMI->isCommutable())
595 // If DefMI is a two-address instruction then commuting it will change the
596 // destination register.
597 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
598 assert(DefIdx != -1);
600 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
602 unsigned Op1, Op2, NewDstIdx;
603 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
607 else if (Op2 == UseOpIdx)
612 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
613 unsigned NewReg = NewDstMO.getReg();
614 if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
617 // Make sure there are no other definitions of IntB that would reach the
618 // uses which the new definition can reach.
619 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
622 // If some of the uses of IntA.reg is already coalesced away, return false.
623 // It's not possible to determine whether it's safe to perform the coalescing.
624 for (MachineRegisterInfo::use_nodbg_iterator UI =
625 MRI->use_nodbg_begin(IntA.reg),
626 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
627 MachineInstr *UseMI = &*UI;
628 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
629 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
630 if (US == IntA.end() || US->valno != AValNo)
632 // If this use is tied to a def, we can't rewrite the register.
633 if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
637 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
640 // At this point we have decided that it is legal to do this
641 // transformation. Start by commuting the instruction.
642 MachineBasicBlock *MBB = DefMI->getParent();
643 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
646 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
647 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
648 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
650 if (NewMI != DefMI) {
651 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
652 MachineBasicBlock::iterator Pos = DefMI;
653 MBB->insert(Pos, NewMI);
656 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
657 NewMI->getOperand(OpIdx).setIsKill();
659 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
668 // Update uses of IntA of the specific Val# with IntB.
669 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
670 UE = MRI->use_end(); UI != UE;) {
671 MachineOperand &UseMO = UI.getOperand();
672 MachineInstr *UseMI = &*UI;
674 if (UseMI->isDebugValue()) {
675 // FIXME These don't have an instruction index. Not clear we have enough
676 // info to decide whether to do this replacement or not. For now do it.
677 UseMO.setReg(NewReg);
680 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
681 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
682 if (US == IntA.end() || US->valno != AValNo)
684 // Kill flags are no longer accurate. They are recomputed after RA.
685 UseMO.setIsKill(false);
686 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
687 UseMO.substPhysReg(NewReg, *TRI);
689 UseMO.setReg(NewReg);
692 if (!UseMI->isCopy())
694 if (UseMI->getOperand(0).getReg() != IntB.reg ||
695 UseMI->getOperand(0).getSubReg())
698 // This copy will become a noop. If it's defining a new val#, merge it into
700 SlotIndex DefIdx = UseIdx.getRegSlot();
701 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
704 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
705 assert(DVNI->def == DefIdx);
706 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
707 ErasedInstrs.insert(UseMI);
708 LIS->RemoveMachineInstrFromMaps(UseMI);
709 UseMI->eraseFromParent();
712 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
714 VNInfo *ValNo = BValNo;
715 ValNo->def = AValNo->def;
716 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
718 if (AI->valno != AValNo) continue;
719 IntB.addSegment(LiveInterval::Segment(AI->start, AI->end, ValNo));
721 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
723 IntA.removeValNo(AValNo);
724 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
729 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
730 /// computation, replace the copy by rematerialize the definition.
731 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP,
732 MachineInstr *CopyMI,
735 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
736 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
737 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
738 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
739 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
742 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
743 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
744 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
745 assert(ValNo && "CopyMI input register not live");
746 if (ValNo->isPHIDef() || ValNo->isUnused())
748 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
751 if (DefMI->isCopyLike()) {
755 if (!DefMI->isAsCheapAsAMove())
757 if (!TII->isTriviallyReMaterializable(DefMI, AA))
759 bool SawStore = false;
760 if (!DefMI->isSafeToMove(TII, AA, SawStore))
762 const MCInstrDesc &MCID = DefMI->getDesc();
763 if (MCID.getNumDefs() != 1)
765 // Only support subregister destinations when the def is read-undef.
766 MachineOperand &DstOperand = CopyMI->getOperand(0);
767 unsigned CopyDstReg = DstOperand.getReg();
768 if (DstOperand.getSubReg() && !DstOperand.isUndef())
771 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
772 // the register substantially (beyond both source and dest size). This is bad
773 // for performance since it can cascade through a function, introducing many
774 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
775 // around after a few subreg copies).
776 if (SrcIdx && DstIdx)
779 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
780 if (!DefMI->isImplicitDef()) {
781 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
782 unsigned NewDstReg = DstReg;
784 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
785 DefMI->getOperand(0).getSubReg());
787 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
789 // Finally, make sure that the physical subregister that will be
790 // constructed later is permitted for the instruction.
791 if (!DefRC->contains(NewDstReg))
794 // Theoretically, some stack frame reference could exist. Just make sure
795 // it hasn't actually happened.
796 assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
797 "Only expect to deal with virtual or physical registers");
801 MachineBasicBlock *MBB = CopyMI->getParent();
802 MachineBasicBlock::iterator MII =
803 std::next(MachineBasicBlock::iterator(CopyMI));
804 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
805 MachineInstr *NewMI = std::prev(MII);
807 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
808 CopyMI->eraseFromParent();
809 ErasedInstrs.insert(CopyMI);
811 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
812 // We need to remember these so we can add intervals once we insert
813 // NewMI into SlotIndexes.
814 SmallVector<unsigned, 4> NewMIImplDefs;
815 for (unsigned i = NewMI->getDesc().getNumOperands(),
816 e = NewMI->getNumOperands(); i != e; ++i) {
817 MachineOperand &MO = NewMI->getOperand(i);
819 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
820 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
821 NewMIImplDefs.push_back(MO.getReg());
825 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
826 const TargetRegisterClass *NewRC = CP.getNewRC();
827 unsigned NewIdx = NewMI->getOperand(0).getSubReg();
830 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
832 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
834 assert(NewRC && "subreg chosen for remat incompatible with instruction");
835 MRI->setRegClass(DstReg, NewRC);
837 updateRegDefsUses(DstReg, DstReg, DstIdx);
838 NewMI->getOperand(0).setSubReg(NewIdx);
839 } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
840 // The New instruction may be defining a sub-register of what's actually
841 // been asked for. If so it must implicitly define the whole thing.
842 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
843 "Only expect virtual or physical registers in remat");
844 NewMI->getOperand(0).setIsDead(true);
845 NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
851 if (NewMI->getOperand(0).getSubReg())
852 NewMI->getOperand(0).setIsUndef();
854 // CopyMI may have implicit operands, transfer them over to the newly
855 // rematerialized instruction. And update implicit def interval valnos.
856 for (unsigned i = CopyMI->getDesc().getNumOperands(),
857 e = CopyMI->getNumOperands(); i != e; ++i) {
858 MachineOperand &MO = CopyMI->getOperand(i);
860 assert(MO.isImplicit() && "No explicit operands after implict operands.");
861 // Discard VReg implicit defs.
862 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
863 NewMI->addOperand(MO);
868 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
869 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
870 unsigned Reg = NewMIImplDefs[i];
871 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
872 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
873 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
876 DEBUG(dbgs() << "Remat: " << *NewMI);
879 // The source interval can become smaller because we removed a use.
880 LIS->shrinkToUses(&SrcInt, &DeadDefs);
881 if (!DeadDefs.empty())
887 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
888 /// values, it only removes local variables. When we have a copy like:
890 /// %vreg1 = COPY %vreg2<undef>
892 /// We delete the copy and remove the corresponding value number from %vreg1.
893 /// Any uses of that value number are marked as <undef>.
894 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
895 const CoalescerPair &CP) {
896 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
897 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
898 if (SrcInt->liveAt(Idx))
900 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
901 if (DstInt->liveAt(Idx))
904 // No intervals are live-in to CopyMI - it is undef.
909 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
910 assert(DeadVNI && "No value defined in DstInt");
911 DstInt->removeValNo(DeadVNI);
913 // Find new undef uses.
914 for (MachineRegisterInfo::reg_nodbg_iterator
915 I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
917 MachineOperand &MO = I.getOperand();
918 if (MO.isDef() || MO.isUndef())
920 MachineInstr *MI = MO.getParent();
921 SlotIndex Idx = LIS->getInstructionIndex(MI);
922 if (DstInt->liveAt(Idx))
925 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
930 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
931 /// update the subregister number if it is not zero. If DstReg is a
932 /// physical register and the existing subregister number of the def / use
933 /// being updated is not zero, make sure to set it to the correct physical
935 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
938 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
939 LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
941 SmallPtrSet<MachineInstr*, 8> Visited;
942 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
943 MachineInstr *UseMI = I.skipInstruction();) {
944 // Each instruction can only be rewritten once because sub-register
945 // composition is not always idempotent. When SrcReg != DstReg, rewriting
946 // the UseMI operands removes them from the SrcReg use-def chain, but when
947 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
948 // operands mentioning the virtual register.
949 if (SrcReg == DstReg && !Visited.insert(UseMI))
952 SmallVector<unsigned,8> Ops;
954 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
956 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
957 // because SrcReg is a sub-register.
958 if (DstInt && !Reads && SubIdx)
959 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
961 // Replace SrcReg with DstReg in all UseMI operands.
962 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
963 MachineOperand &MO = UseMI->getOperand(Ops[i]);
965 // Adjust <undef> flags in case of sub-register joins. We don't want to
966 // turn a full def into a read-modify-write sub-register def and vice
968 if (SubIdx && MO.isDef())
969 MO.setIsUndef(!Reads);
972 MO.substPhysReg(DstReg, *TRI);
974 MO.substVirtReg(DstReg, SubIdx, *TRI);
978 dbgs() << "\t\tupdated: ";
979 if (!UseMI->isDebugValue())
980 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
986 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
987 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
988 /// Always join simple intervals that are defined by a single copy from a
989 /// reserved register. This doesn't increase register pressure, so it is
990 /// always beneficial.
991 if (!MRI->isReserved(CP.getDstReg())) {
992 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
996 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
997 if (CP.isFlipped() && JoinVInt.containsOneValue())
1000 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
1004 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1005 /// which are the src/dst of the copy instruction CopyMI. This returns true
1006 /// if the copy was successfully coalesced away. If it is not currently
1007 /// possible to coalesce this interval, but it may be possible if other
1008 /// things get coalesced, then it returns true by reference in 'Again'.
1009 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1012 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1014 CoalescerPair CP(*TRI);
1015 if (!CP.setRegisters(CopyMI)) {
1016 DEBUG(dbgs() << "\tNot coalescable.\n");
1020 // Dead code elimination. This really should be handled by MachineDCE, but
1021 // sometimes dead copies slip through, and we can't generate invalid live
1023 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1024 DEBUG(dbgs() << "\tCopy is dead.\n");
1025 DeadDefs.push_back(CopyMI);
1026 eliminateDeadDefs();
1030 // Eliminate undefs.
1031 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1032 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1033 LIS->RemoveMachineInstrFromMaps(CopyMI);
1034 CopyMI->eraseFromParent();
1035 return false; // Not coalescable.
1038 // Coalesced copies are normally removed immediately, but transformations
1039 // like removeCopyByCommutingDef() can inadvertently create identity copies.
1040 // When that happens, just join the values and remove the copy.
1041 if (CP.getSrcReg() == CP.getDstReg()) {
1042 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1043 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1044 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(CopyMI));
1045 if (VNInfo *DefVNI = LRQ.valueDefined()) {
1046 VNInfo *ReadVNI = LRQ.valueIn();
1047 assert(ReadVNI && "No value before copy and no <undef> flag.");
1048 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1049 LI.MergeValueNumberInto(DefVNI, ReadVNI);
1050 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
1052 LIS->RemoveMachineInstrFromMaps(CopyMI);
1053 CopyMI->eraseFromParent();
1057 // Enforce policies.
1059 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1060 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1062 if (!canJoinPhys(CP)) {
1063 // Before giving up coalescing, if definition of source is defined by
1064 // trivial computation, try rematerializing it.
1066 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1069 Again = true; // May be possible to coalesce later.
1074 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1076 if (CP.getDstIdx() && CP.getSrcIdx())
1077 dbgs() << PrintReg(CP.getDstReg()) << " in "
1078 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1079 << PrintReg(CP.getSrcReg()) << " in "
1080 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1082 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1083 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1086 // When possible, let DstReg be the larger interval.
1087 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1088 LIS->getInterval(CP.getDstReg()).size())
1092 // Okay, attempt to join these two intervals. On failure, this returns false.
1093 // Otherwise, if one of the intervals being joined is a physreg, this method
1094 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1095 // been modified, so we can use this information below to update aliases.
1096 if (!joinIntervals(CP)) {
1097 // Coalescing failed.
1099 // If definition of source is defined by trivial computation, try
1100 // rematerializing it.
1102 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1105 // If we can eliminate the copy without merging the live segments, do so
1107 if (!CP.isPartial() && !CP.isPhys()) {
1108 if (adjustCopiesBackFrom(CP, CopyMI) ||
1109 removeCopyByCommutingDef(CP, CopyMI)) {
1110 LIS->RemoveMachineInstrFromMaps(CopyMI);
1111 CopyMI->eraseFromParent();
1112 DEBUG(dbgs() << "\tTrivial!\n");
1117 // Otherwise, we are unable to join the intervals.
1118 DEBUG(dbgs() << "\tInterference!\n");
1119 Again = true; // May be possible to coalesce later.
1123 // Coalescing to a virtual register that is of a sub-register class of the
1124 // other. Make sure the resulting register is set to the right register class.
1125 if (CP.isCrossClass()) {
1127 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1130 // Removing sub-register copies can ease the register class constraints.
1131 // Make sure we attempt to inflate the register class of DstReg.
1132 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1133 InflateRegs.push_back(CP.getDstReg());
1135 // CopyMI has been erased by joinIntervals at this point. Remove it from
1136 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1137 // to the work list. This keeps ErasedInstrs from growing needlessly.
1138 ErasedInstrs.erase(CopyMI);
1140 // Rewrite all SrcReg operands to DstReg.
1141 // Also update DstReg operands to include DstIdx if it is set.
1143 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1144 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1146 // SrcReg is guaranteed to be the register whose live interval that is
1148 LIS->removeInterval(CP.getSrcReg());
1150 // Update regalloc hint.
1151 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1154 dbgs() << "\tJoined. Result = ";
1156 dbgs() << PrintReg(CP.getDstReg(), TRI);
1158 dbgs() << LIS->getInterval(CP.getDstReg());
1166 /// Attempt joining with a reserved physreg.
1167 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1168 assert(CP.isPhys() && "Must be a physreg copy");
1169 assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
1170 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1171 DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1173 assert(CP.isFlipped() && RHS.containsOneValue() &&
1174 "Invalid join with reserved register");
1176 // Optimization for reserved registers like ESP. We can only merge with a
1177 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1178 // The live range of the reserved register will look like a set of dead defs
1179 // - we don't properly track the live range of reserved registers.
1181 // Deny any overlapping intervals. This depends on all the reserved
1182 // register live ranges to look like dead defs.
1183 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1184 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1185 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1189 // Skip any value computations, we are not adding new values to the
1190 // reserved register. Also skip merging the live ranges, the reserved
1191 // register live range doesn't need to be accurate as long as all the
1194 // Delete the identity copy.
1195 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1196 LIS->RemoveMachineInstrFromMaps(CopyMI);
1197 CopyMI->eraseFromParent();
1199 // We don't track kills for reserved registers.
1200 MRI->clearKillFlags(CP.getSrcReg());
1205 //===----------------------------------------------------------------------===//
1206 // Interference checking and interval joining
1207 //===----------------------------------------------------------------------===//
1209 // In the easiest case, the two live ranges being joined are disjoint, and
1210 // there is no interference to consider. It is quite common, though, to have
1211 // overlapping live ranges, and we need to check if the interference can be
1214 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1215 // This means that two SSA values overlap if and only if the def of one value
1216 // is contained in the live range of the other value. As a special case, the
1217 // overlapping values can be defined at the same index.
1219 // The interference from an overlapping def can be resolved in these cases:
1221 // 1. Coalescable copies. The value is defined by a copy that would become an
1222 // identity copy after joining SrcReg and DstReg. The copy instruction will
1223 // be removed, and the value will be merged with the source value.
1225 // There can be several copies back and forth, causing many values to be
1226 // merged into one. We compute a list of ultimate values in the joined live
1227 // range as well as a mappings from the old value numbers.
1229 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1230 // predecessors have a live out value. It doesn't cause real interference,
1231 // and can be merged into the value it overlaps. Like a coalescable copy, it
1232 // can be erased after joining.
1234 // 3. Copy of external value. The overlapping def may be a copy of a value that
1235 // is already in the other register. This is like a coalescable copy, but
1236 // the live range of the source register must be trimmed after erasing the
1237 // copy instruction:
1240 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1242 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1243 // defining one lane at a time:
1245 // %dst:ssub0<def,read-undef> = FOO
1247 // %dst:ssub1<def> = COPY %src
1249 // The live range of %src overlaps the %dst value defined by FOO, but
1250 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1251 // which was undef anyway.
1253 // The value mapping is more complicated in this case. The final live range
1254 // will have different value numbers for both FOO and BAR, but there is no
1255 // simple mapping from old to new values. It may even be necessary to add
1258 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1259 // is live, but never read. This can happen because we don't compute
1260 // individual live ranges per lane.
1264 // %dst:ssub1<def> = COPY %src
1266 // This kind of interference is only resolved locally. If the clobbered
1267 // lane value escapes the block, the join is aborted.
1270 /// Track information about values in a single virtual register about to be
1271 /// joined. Objects of this class are always created in pairs - one for each
1272 /// side of the CoalescerPair.
1276 // Location of this register in the final joined register.
1277 // Either CP.DstIdx or CP.SrcIdx.
1280 // Values that will be present in the final live range.
1281 SmallVectorImpl<VNInfo*> &NewVNInfo;
1283 const CoalescerPair &CP;
1285 SlotIndexes *Indexes;
1286 const TargetRegisterInfo *TRI;
1288 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1289 // This is suitable for passing to LiveInterval::join().
1290 SmallVector<int, 8> Assignments;
1292 // Conflict resolution for overlapping values.
1293 enum ConflictResolution {
1294 // No overlap, simply keep this value.
1297 // Merge this value into OtherVNI and erase the defining instruction.
1298 // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1302 // Merge this value into OtherVNI but keep the defining instruction.
1303 // This is for the special case where OtherVNI is defined by the same
1307 // Keep this value, and have it replace OtherVNI where possible. This
1308 // complicates value mapping since OtherVNI maps to two different values
1309 // before and after this def.
1310 // Used when clobbering undefined or dead lanes.
1313 // Unresolved conflict. Visit later when all values have been mapped.
1316 // Unresolvable conflict. Abort the join.
1320 // Per-value info for LI. The lane bit masks are all relative to the final
1321 // joined register, so they can be compared directly between SrcReg and
1324 ConflictResolution Resolution;
1326 // Lanes written by this def, 0 for unanalyzed values.
1327 unsigned WriteLanes;
1329 // Lanes with defined values in this register. Other lanes are undef and
1331 unsigned ValidLanes;
1333 // Value in LI being redefined by this def.
1336 // Value in the other live range that overlaps this def, if any.
1339 // Is this value an IMPLICIT_DEF that can be erased?
1341 // IMPLICIT_DEF values should only exist at the end of a basic block that
1342 // is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1343 // safely erased if they are overlapping a live value in the other live
1346 // Weird control flow graphs and incomplete PHI handling in
1347 // ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1348 // longer live ranges. Such IMPLICIT_DEF values should be treated like
1350 bool ErasableImplicitDef;
1352 // True when the live range of this value will be pruned because of an
1353 // overlapping CR_Replace value in the other live range.
1356 // True once Pruned above has been computed.
1357 bool PrunedComputed;
1359 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1360 RedefVNI(0), OtherVNI(0), ErasableImplicitDef(false),
1361 Pruned(false), PrunedComputed(false) {}
1363 bool isAnalyzed() const { return WriteLanes != 0; }
1366 // One entry per value number in LI.
1367 SmallVector<Val, 8> Vals;
1369 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1370 VNInfo *stripCopies(VNInfo *VNI);
1371 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1372 void computeAssignment(unsigned ValNo, JoinVals &Other);
1373 bool taintExtent(unsigned, unsigned, JoinVals&,
1374 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1375 bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned);
1376 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1379 JoinVals(LiveInterval &li, unsigned subIdx,
1380 SmallVectorImpl<VNInfo*> &newVNInfo,
1381 const CoalescerPair &cp,
1383 const TargetRegisterInfo *tri)
1384 : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1385 Indexes(LIS->getSlotIndexes()), TRI(tri),
1386 Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1389 /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1390 /// Returns false if any conflicts were impossible to resolve.
1391 bool mapValues(JoinVals &Other);
1393 /// Try to resolve conflicts that require all values to be mapped.
1394 /// Returns false if any conflicts were impossible to resolve.
1395 bool resolveConflicts(JoinVals &Other);
1397 /// Prune the live range of values in Other.LI where they would conflict with
1398 /// CR_Replace values in LI. Collect end points for restoring the live range
1400 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1402 /// Erase any machine instructions that have been coalesced away.
1403 /// Add erased instructions to ErasedInstrs.
1404 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1405 /// the erased instrs.
1406 void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1407 SmallVectorImpl<unsigned> &ShrinkRegs);
1409 /// Get the value assignments suitable for passing to LiveInterval::join.
1410 const int *getAssignments() const { return Assignments.data(); }
1412 } // end anonymous namespace
1414 /// Compute the bitmask of lanes actually written by DefMI.
1415 /// Set Redef if there are any partial register definitions that depend on the
1416 /// previous value of the register.
1417 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1419 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1420 if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1422 L |= TRI->getSubRegIndexLaneMask(
1423 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1430 /// Find the ultimate value that VNI was copied from.
1431 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1432 while (!VNI->isPHIDef()) {
1433 MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1434 assert(MI && "No defining instruction");
1435 if (!MI->isFullCopy())
1437 unsigned Reg = MI->getOperand(1).getReg();
1438 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1440 LiveQueryResult LRQ = LIS->getInterval(Reg).Query(VNI->def);
1443 VNI = LRQ.valueIn();
1448 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1449 /// Return a conflict resolution when possible, but leave the hard cases as
1451 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1452 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1453 /// The recursion always goes upwards in the dominator tree, making loops
1455 JoinVals::ConflictResolution
1456 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1457 Val &V = Vals[ValNo];
1458 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1459 VNInfo *VNI = LI.getValNumInfo(ValNo);
1460 if (VNI->isUnused()) {
1465 // Get the instruction defining this value, compute the lanes written.
1466 const MachineInstr *DefMI = 0;
1467 if (VNI->isPHIDef()) {
1468 // Conservatively assume that all lanes in a PHI are valid.
1469 V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1471 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1473 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1475 // If this is a read-modify-write instruction, there may be more valid
1476 // lanes than the ones written by this instruction.
1477 // This only covers partial redef operands. DefMI may have normal use
1478 // operands reading the register. They don't contribute valid lanes.
1480 // This adds ssub1 to the set of valid lanes in %src:
1482 // %src:ssub1<def> = FOO
1484 // This leaves only ssub1 valid, making any other lanes undef:
1486 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1488 // The <read-undef> flag on the def operand means that old lane values are
1491 V.RedefVNI = LI.Query(VNI->def).valueIn();
1492 assert(V.RedefVNI && "Instruction is reading nonexistent value");
1493 computeAssignment(V.RedefVNI->id, Other);
1494 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1497 // An IMPLICIT_DEF writes undef values.
1498 if (DefMI->isImplicitDef()) {
1499 // We normally expect IMPLICIT_DEF values to be live only until the end
1500 // of their block. If the value is really live longer and gets pruned in
1501 // another block, this flag is cleared again.
1502 V.ErasableImplicitDef = true;
1503 V.ValidLanes &= ~V.WriteLanes;
1507 // Find the value in Other that overlaps VNI->def, if any.
1508 LiveQueryResult OtherLRQ = Other.LI.Query(VNI->def);
1510 // It is possible that both values are defined by the same instruction, or
1511 // the values are PHIs defined in the same block. When that happens, the two
1512 // values should be merged into one, but not into any preceding value.
1513 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1514 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1515 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1517 // One value stays, the other is merged. Keep the earlier one, or the first
1519 if (OtherVNI->def < VNI->def)
1520 Other.computeAssignment(OtherVNI->id, *this);
1521 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1522 // This is an early-clobber def overlapping a live-in value in the other
1523 // register. Not mergeable.
1524 V.OtherVNI = OtherLRQ.valueIn();
1525 return CR_Impossible;
1527 V.OtherVNI = OtherVNI;
1528 Val &OtherV = Other.Vals[OtherVNI->id];
1529 // Keep this value, check for conflicts when analyzing OtherVNI.
1530 if (!OtherV.isAnalyzed())
1532 // Both sides have been analyzed now.
1533 // Allow overlapping PHI values. Any real interference would show up in a
1534 // predecessor, the PHI itself can't introduce any conflicts.
1535 if (VNI->isPHIDef())
1537 if (V.ValidLanes & OtherV.ValidLanes)
1538 // Overlapping lanes can't be resolved.
1539 return CR_Impossible;
1544 // No simultaneous def. Is Other live at the def?
1545 V.OtherVNI = OtherLRQ.valueIn();
1547 // No overlap, no conflict.
1550 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1552 // We have overlapping values, or possibly a kill of Other.
1553 // Recursively compute assignments up the dominator tree.
1554 Other.computeAssignment(V.OtherVNI->id, *this);
1555 Val &OtherV = Other.Vals[V.OtherVNI->id];
1557 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
1558 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
1559 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
1562 // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
1563 // to erase the IMPLICIT_DEF instruction.
1564 if (OtherV.ErasableImplicitDef && DefMI &&
1565 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
1566 DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
1567 << " extends into BB#" << DefMI->getParent()->getNumber()
1568 << ", keeping it.\n");
1569 OtherV.ErasableImplicitDef = false;
1572 // Allow overlapping PHI values. Any real interference would show up in a
1573 // predecessor, the PHI itself can't introduce any conflicts.
1574 if (VNI->isPHIDef())
1577 // Check for simple erasable conflicts.
1578 if (DefMI->isImplicitDef())
1581 // Include the non-conflict where DefMI is a coalescable copy that kills
1582 // OtherVNI. We still want the copy erased and value numbers merged.
1583 if (CP.isCoalescable(DefMI)) {
1584 // Some of the lanes copied from OtherVNI may be undef, making them undef
1586 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1590 // This may not be a real conflict if DefMI simply kills Other and defines
1592 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1595 // Handle the case where VNI and OtherVNI can be proven to be identical:
1597 // %other = COPY %ext
1598 // %this = COPY %ext <-- Erase this copy
1600 if (DefMI->isFullCopy() && !CP.isPartial() &&
1601 stripCopies(VNI) == stripCopies(V.OtherVNI))
1604 // If the lanes written by this instruction were all undef in OtherVNI, it is
1605 // still safe to join the live ranges. This can't be done with a simple value
1606 // mapping, though - OtherVNI will map to multiple values:
1608 // 1 %dst:ssub0 = FOO <-- OtherVNI
1609 // 2 %src = BAR <-- VNI
1610 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
1612 // 5 QUUX %src<kill>
1614 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1615 // handles this complex value mapping.
1616 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1619 // If the other live range is killed by DefMI and the live ranges are still
1620 // overlapping, it must be because we're looking at an early clobber def:
1622 // %dst<def,early-clobber> = ASM %src<kill>
1624 // In this case, it is illegal to merge the two live ranges since the early
1625 // clobber def would clobber %src before it was read.
1626 if (OtherLRQ.isKill()) {
1627 // This case where the def doesn't overlap the kill is handled above.
1628 assert(VNI->def.isEarlyClobber() &&
1629 "Only early clobber defs can overlap a kill");
1630 return CR_Impossible;
1633 // VNI is clobbering live lanes in OtherVNI, but there is still the
1634 // possibility that no instructions actually read the clobbered lanes.
1635 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1636 // Otherwise Other.LI wouldn't be live here.
1637 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1638 return CR_Impossible;
1640 // We need to verify that no instructions are reading the clobbered lanes. To
1641 // save compile time, we'll only check that locally. Don't allow the tainted
1642 // value to escape the basic block.
1643 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1644 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1645 return CR_Impossible;
1647 // There are still some things that could go wrong besides clobbered lanes
1648 // being read, for example OtherVNI may be only partially redefined in MBB,
1649 // and some clobbered lanes could escape the block. Save this analysis for
1650 // resolveConflicts() when all values have been mapped. We need to know
1651 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1652 // that now - the recursive analyzeValue() calls must go upwards in the
1654 return CR_Unresolved;
1657 /// Compute the value assignment for ValNo in LI.
1658 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1660 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1661 Val &V = Vals[ValNo];
1662 if (V.isAnalyzed()) {
1663 // Recursion should always move up the dominator tree, so ValNo is not
1664 // supposed to reappear before it has been assigned.
1665 assert(Assignments[ValNo] != -1 && "Bad recursion?");
1668 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1671 // Merge this ValNo into OtherVNI.
1672 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1673 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1674 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1675 DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1676 << LI.getValNumInfo(ValNo)->def << " into "
1677 << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1678 << V.OtherVNI->def << " --> @"
1679 << NewVNInfo[Assignments[ValNo]]->def << '\n');
1683 // The other value is going to be pruned if this join is successful.
1684 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
1685 Other.Vals[V.OtherVNI->id].Pruned = true;
1688 // This value number needs to go in the final joined live range.
1689 Assignments[ValNo] = NewVNInfo.size();
1690 NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1695 bool JoinVals::mapValues(JoinVals &Other) {
1696 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1697 computeAssignment(i, Other);
1698 if (Vals[i].Resolution == CR_Impossible) {
1699 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1700 << '@' << LI.getValNumInfo(i)->def << '\n');
1707 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute
1708 /// the extent of the tainted lanes in the block.
1710 /// Multiple values in Other.LI can be affected since partial redefinitions can
1711 /// preserve previously tainted lanes.
1713 /// 1 %dst = VLOAD <-- Define all lanes in %dst
1714 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
1715 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
1716 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1718 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1719 /// entry to TaintedVals.
1721 /// Returns false if the tainted lanes extend beyond the basic block.
1723 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
1724 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
1725 VNInfo *VNI = LI.getValNumInfo(ValNo);
1726 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1727 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
1729 // Scan Other.LI from VNI.def to MBBEnd.
1730 LiveInterval::iterator OtherI = Other.LI.find(VNI->def);
1731 assert(OtherI != Other.LI.end() && "No conflict?");
1733 // OtherI is pointing to a tainted value. Abort the join if the tainted
1734 // lanes escape the block.
1735 SlotIndex End = OtherI->end;
1736 if (End >= MBBEnd) {
1737 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':'
1738 << OtherI->valno->id << '@' << OtherI->start << '\n');
1741 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':'
1742 << OtherI->valno->id << '@' << OtherI->start
1743 << " to " << End << '\n');
1744 // A dead def is not a problem.
1747 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
1749 // Check for another def in the MBB.
1750 if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd)
1753 // Lanes written by the new def are no longer tainted.
1754 const Val &OV = Other.Vals[OtherI->valno->id];
1755 TaintedLanes &= ~OV.WriteLanes;
1758 } while (TaintedLanes);
1762 /// Return true if MI uses any of the given Lanes from Reg.
1763 /// This does not include partial redefinitions of Reg.
1764 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx,
1766 if (MI->isDebugValue())
1768 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1769 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
1771 if (!MO->readsReg())
1773 if (Lanes & TRI->getSubRegIndexLaneMask(
1774 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
1780 bool JoinVals::resolveConflicts(JoinVals &Other) {
1781 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1783 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
1784 if (V.Resolution != CR_Unresolved)
1786 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1787 << '@' << LI.getValNumInfo(i)->def << '\n');
1789 assert(V.OtherVNI && "Inconsistent conflict resolution.");
1790 VNInfo *VNI = LI.getValNumInfo(i);
1791 const Val &OtherV = Other.Vals[V.OtherVNI->id];
1793 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
1794 // join, those lanes will be tainted with a wrong value. Get the extent of
1795 // the tainted lanes.
1796 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
1797 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
1798 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
1799 // Tainted lanes would extend beyond the basic block.
1802 assert(!TaintExtent.empty() && "There should be at least one conflict.");
1804 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
1805 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1806 MachineBasicBlock::iterator MI = MBB->begin();
1807 if (!VNI->isPHIDef()) {
1808 MI = Indexes->getInstructionFromIndex(VNI->def);
1809 // No need to check the instruction defining VNI for reads.
1812 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
1813 "Interference ends on VNI->def. Should have been handled earlier");
1814 MachineInstr *LastMI =
1815 Indexes->getInstructionFromIndex(TaintExtent.front().first);
1816 assert(LastMI && "Range must end at a proper instruction");
1817 unsigned TaintNum = 0;
1819 assert(MI != MBB->end() && "Bad LastMI");
1820 if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) {
1821 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
1824 // LastMI is the last instruction to use the current value.
1825 if (&*MI == LastMI) {
1826 if (++TaintNum == TaintExtent.size())
1828 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
1829 assert(LastMI && "Range must end at a proper instruction");
1830 TaintedLanes = TaintExtent[TaintNum].second;
1835 // The tainted lanes are unused.
1836 V.Resolution = CR_Replace;
1842 // Determine if ValNo is a copy of a value number in LI or Other.LI that will
1846 // %src = COPY %dst <-- This value to be pruned.
1847 // %dst = COPY %src <-- This value is a copy of a pruned value.
1849 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
1850 Val &V = Vals[ValNo];
1851 if (V.Pruned || V.PrunedComputed)
1854 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
1857 // Follow copies up the dominator tree and check if any intermediate value
1859 V.PrunedComputed = true;
1860 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
1864 void JoinVals::pruneValues(JoinVals &Other,
1865 SmallVectorImpl<SlotIndex> &EndPoints) {
1866 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1867 SlotIndex Def = LI.getValNumInfo(i)->def;
1868 switch (Vals[i].Resolution) {
1872 // This value takes precedence over the value in Other.LI.
1873 LIS->pruneValue(&Other.LI, Def, &EndPoints);
1874 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
1875 // instructions are only inserted to provide a live-out value for PHI
1876 // predecessors, so the instruction should simply go away once its value
1877 // has been replaced.
1878 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
1879 bool EraseImpDef = OtherV.ErasableImplicitDef &&
1880 OtherV.Resolution == CR_Keep;
1881 if (!Def.isBlock()) {
1882 // Remove <def,read-undef> flags. This def is now a partial redef.
1883 // Also remove <def,dead> flags since the joined live range will
1884 // continue past this instruction.
1885 for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
1887 if (MO->isReg() && MO->isDef() && MO->getReg() == LI.reg) {
1888 MO->setIsUndef(EraseImpDef);
1889 MO->setIsDead(false);
1891 // This value will reach instructions below, but we need to make sure
1892 // the live range also reaches the instruction at Def.
1894 EndPoints.push_back(Def);
1896 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1897 << ": " << Other.LI << '\n');
1902 if (isPrunedValue(i, Other)) {
1903 // This value is ultimately a copy of a pruned value in LI or Other.LI.
1904 // We can no longer trust the value mapping computed by
1905 // computeAssignment(), the value that was originally copied could have
1907 LIS->pruneValue(&LI, Def, &EndPoints);
1908 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at "
1909 << Def << ": " << LI << '\n');
1914 llvm_unreachable("Unresolved conflicts");
1919 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1920 SmallVectorImpl<unsigned> &ShrinkRegs) {
1921 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1922 // Get the def location before markUnused() below invalidates it.
1923 SlotIndex Def = LI.getValNumInfo(i)->def;
1924 switch (Vals[i].Resolution) {
1926 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
1927 // longer. The IMPLICIT_DEF instructions are only inserted by
1928 // PHIElimination to guarantee that all PHI predecessors have a value.
1929 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
1931 // Remove value number i from LI. Note that this VNInfo is still present
1932 // in NewVNInfo, so it will appear as an unused value number in the final
1934 LI.getValNumInfo(i)->markUnused();
1935 LI.removeValNo(LI.getValNumInfo(i));
1936 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LI << '\n');
1940 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1941 assert(MI && "No instruction to erase");
1943 unsigned Reg = MI->getOperand(1).getReg();
1944 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1945 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1946 ShrinkRegs.push_back(Reg);
1948 ErasedInstrs.insert(MI);
1949 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1950 LIS->RemoveMachineInstrFromMaps(MI);
1951 MI->eraseFromParent();
1960 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1961 SmallVector<VNInfo*, 16> NewVNInfo;
1962 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1963 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1964 JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1965 JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1967 DEBUG(dbgs() << "\t\tRHS = " << RHS
1968 << "\n\t\tLHS = " << LHS
1971 // First compute NewVNInfo and the simple value mappings.
1972 // Detect impossible conflicts early.
1973 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1976 // Some conflicts can only be resolved after all values have been mapped.
1977 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1980 // All clear, the live ranges can be merged.
1982 // The merging algorithm in LiveInterval::join() can't handle conflicting
1983 // value mappings, so we need to remove any live ranges that overlap a
1984 // CR_Replace resolution. Collect a set of end points that can be used to
1985 // restore the live range after joining.
1986 SmallVector<SlotIndex, 8> EndPoints;
1987 LHSVals.pruneValues(RHSVals, EndPoints);
1988 RHSVals.pruneValues(LHSVals, EndPoints);
1990 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1991 // registers to require trimming.
1992 SmallVector<unsigned, 8> ShrinkRegs;
1993 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1994 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1995 while (!ShrinkRegs.empty())
1996 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1998 // Join RHS into LHS.
1999 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
2001 // Kill flags are going to be wrong if the live ranges were overlapping.
2002 // Eventually, we should simply clear all kill flags when computing live
2003 // ranges. They are reinserted after register allocation.
2004 MRI->clearKillFlags(LHS.reg);
2005 MRI->clearKillFlags(RHS.reg);
2007 if (EndPoints.empty())
2010 // Recompute the parts of the live range we had to remove because of
2011 // CR_Replace conflicts.
2012 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2013 << " points: " << LHS << '\n');
2014 LIS->extendToIndices(LHS, EndPoints);
2018 /// joinIntervals - Attempt to join these two intervals. On failure, this
2020 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
2021 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
2025 // Information concerning MBB coalescing priority.
2026 struct MBBPriorityInfo {
2027 MachineBasicBlock *MBB;
2031 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
2032 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
2036 // C-style comparator that sorts first based on the loop depth of the basic
2037 // block (the unsigned), and then on the MBB number.
2039 // EnableGlobalCopies assumes that the primary sort key is loop depth.
2040 static int compareMBBPriority(const MBBPriorityInfo *LHS,
2041 const MBBPriorityInfo *RHS) {
2042 // Deeper loops first
2043 if (LHS->Depth != RHS->Depth)
2044 return LHS->Depth > RHS->Depth ? -1 : 1;
2046 // Try to unsplit critical edges next.
2047 if (LHS->IsSplit != RHS->IsSplit)
2048 return LHS->IsSplit ? -1 : 1;
2050 // Prefer blocks that are more connected in the CFG. This takes care of
2051 // the most difficult copies first while intervals are short.
2052 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
2053 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
2055 return cl > cr ? -1 : 1;
2057 // As a last resort, sort by block number.
2058 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
2061 /// \returns true if the given copy uses or defines a local live range.
2062 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
2063 if (!Copy->isCopy())
2066 if (Copy->getOperand(1).isUndef())
2069 unsigned SrcReg = Copy->getOperand(1).getReg();
2070 unsigned DstReg = Copy->getOperand(0).getReg();
2071 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
2072 || TargetRegisterInfo::isPhysicalRegister(DstReg))
2075 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
2076 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
2079 // Try joining WorkList copies starting from index From.
2080 // Null out any successful joins.
2081 bool RegisterCoalescer::
2082 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2083 bool Progress = false;
2084 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2087 // Skip instruction pointers that have already been erased, for example by
2088 // dead code elimination.
2089 if (ErasedInstrs.erase(CurrList[i])) {
2094 bool Success = joinCopy(CurrList[i], Again);
2095 Progress |= Success;
2096 if (Success || !Again)
2103 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2104 DEBUG(dbgs() << MBB->getName() << ":\n");
2106 // Collect all copy-like instructions in MBB. Don't start coalescing anything
2107 // yet, it might invalidate the iterator.
2108 const unsigned PrevSize = WorkList.size();
2109 if (JoinGlobalCopies) {
2110 // Coalesce copies bottom-up to coalesce local defs before local uses. They
2111 // are not inherently easier to resolve, but slightly preferable until we
2112 // have local live range splitting. In particular this is required by
2113 // cmp+jmp macro fusion.
2114 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2116 if (!MII->isCopyLike())
2118 if (isLocalCopy(&(*MII), LIS))
2119 LocalWorkList.push_back(&(*MII));
2121 WorkList.push_back(&(*MII));
2125 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2127 if (MII->isCopyLike())
2128 WorkList.push_back(MII);
2130 // Try coalescing the collected copies immediately, and remove the nulls.
2131 // This prevents the WorkList from getting too large since most copies are
2132 // joinable on the first attempt.
2133 MutableArrayRef<MachineInstr*>
2134 CurrList(WorkList.begin() + PrevSize, WorkList.end());
2135 if (copyCoalesceWorkList(CurrList))
2136 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2137 (MachineInstr*)0), WorkList.end());
2140 void RegisterCoalescer::coalesceLocals() {
2141 copyCoalesceWorkList(LocalWorkList);
2142 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2143 if (LocalWorkList[j])
2144 WorkList.push_back(LocalWorkList[j]);
2146 LocalWorkList.clear();
2149 void RegisterCoalescer::joinAllIntervals() {
2150 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2151 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2153 std::vector<MBBPriorityInfo> MBBs;
2154 MBBs.reserve(MF->size());
2155 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2156 MachineBasicBlock *MBB = I;
2157 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2158 JoinSplitEdges && isSplitEdge(MBB)));
2160 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
2162 // Coalesce intervals in MBB priority order.
2163 unsigned CurrDepth = UINT_MAX;
2164 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2165 // Try coalescing the collected local copies for deeper loops.
2166 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
2168 CurrDepth = MBBs[i].Depth;
2170 copyCoalesceInMBB(MBBs[i].MBB);
2174 // Joining intervals can allow other intervals to be joined. Iteratively join
2175 // until we make no progress.
2176 while (copyCoalesceWorkList(WorkList))
2180 void RegisterCoalescer::releaseMemory() {
2181 ErasedInstrs.clear();
2184 InflateRegs.clear();
2187 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2189 MRI = &fn.getRegInfo();
2190 TM = &fn.getTarget();
2191 TRI = TM->getRegisterInfo();
2192 TII = TM->getInstrInfo();
2193 LIS = &getAnalysis<LiveIntervals>();
2194 AA = &getAnalysis<AliasAnalysis>();
2195 Loops = &getAnalysis<MachineLoopInfo>();
2197 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
2198 if (EnableGlobalCopies == cl::BOU_UNSET)
2199 JoinGlobalCopies = ST.useMachineScheduler();
2201 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2203 // The MachineScheduler does not currently require JoinSplitEdges. This will
2204 // either be enabled unconditionally or replaced by a more general live range
2205 // splitting optimization.
2206 JoinSplitEdges = EnableJoinSplits;
2208 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2209 << "********** Function: " << MF->getName() << '\n');
2211 if (VerifyCoalescing)
2212 MF->verify(this, "Before register coalescing");
2214 RegClassInfo.runOnMachineFunction(fn);
2216 // Join (coalesce) intervals if requested.
2220 // After deleting a lot of copies, register classes may be less constrained.
2221 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2223 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2224 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2226 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2227 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2228 unsigned Reg = InflateRegs[i];
2229 if (MRI->reg_nodbg_empty(Reg))
2231 if (MRI->recomputeRegClass(Reg, *TM)) {
2232 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2233 << MRI->getRegClass(Reg)->getName() << '\n');
2239 if (VerifyCoalescing)
2240 MF->verify(this, "After register coalescing");
2244 /// print - Implement the dump method.
2245 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {