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 #include "RegisterCoalescer.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/LiveRangeEdit.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/RegisterClassInfo.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Format.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 #define DEBUG_TYPE "regalloc"
47 STATISTIC(numJoins , "Number of interval joins performed");
48 STATISTIC(numCrossRCs , "Number of cross class joins performed");
49 STATISTIC(numCommutes , "Number of instruction commuting performed");
50 STATISTIC(numExtends , "Number of copies extended");
51 STATISTIC(NumReMats , "Number of instructions re-materialized");
52 STATISTIC(NumInflated , "Number of register classes inflated");
53 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
54 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
57 EnableJoining("join-liveintervals",
58 cl::desc("Coalesce copies (default=true)"),
61 // Temporary flag to test critical edge unsplitting.
63 EnableJoinSplits("join-splitedges",
64 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
66 // Temporary flag to test global copy optimization.
67 static cl::opt<cl::boolOrDefault>
68 EnableGlobalCopies("join-globalcopies",
69 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
70 cl::init(cl::BOU_UNSET), cl::Hidden);
73 VerifyCoalescing("verify-coalescing",
74 cl::desc("Verify machine instrs before and after register coalescing"),
78 class RegisterCoalescer : public MachineFunctionPass,
79 private LiveRangeEdit::Delegate {
81 MachineRegisterInfo* MRI;
82 const TargetMachine* TM;
83 const TargetRegisterInfo* TRI;
84 const TargetInstrInfo* TII;
86 const MachineLoopInfo* Loops;
88 RegisterClassInfo RegClassInfo;
90 /// A LaneMask to remember on which subregister live ranges we need to call
91 /// shrinkToUses() later.
94 /// True if the main range of the currently coalesced intervals should be
95 /// checked for smaller live intervals.
98 /// \brief True if the coalescer should aggressively coalesce global copies
99 /// in favor of keeping local copies.
100 bool JoinGlobalCopies;
102 /// \brief True if the coalescer should aggressively coalesce fall-thru
103 /// blocks exclusively containing copies.
106 /// Copy instructions yet to be coalesced.
107 SmallVector<MachineInstr*, 8> WorkList;
108 SmallVector<MachineInstr*, 8> LocalWorkList;
110 /// Set of instruction pointers that have been erased, and
111 /// that may be present in WorkList.
112 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
114 /// Dead instructions that are about to be deleted.
115 SmallVector<MachineInstr*, 8> DeadDefs;
117 /// Virtual registers to be considered for register class inflation.
118 SmallVector<unsigned, 8> InflateRegs;
120 /// Recursively eliminate dead defs in DeadDefs.
121 void eliminateDeadDefs();
123 /// LiveRangeEdit callback.
124 void LRE_WillEraseInstruction(MachineInstr *MI) override;
126 /// Coalesce the LocalWorkList.
127 void coalesceLocals();
129 /// Join compatible live intervals
130 void joinAllIntervals();
132 /// Coalesce copies in the specified MBB, putting
133 /// copies that cannot yet be coalesced into WorkList.
134 void copyCoalesceInMBB(MachineBasicBlock *MBB);
136 /// Try to coalesce all copies in CurrList. Return
137 /// true if any progress was made.
138 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
140 /// Attempt to join intervals corresponding to SrcReg/DstReg,
141 /// which are the src/dst of the copy instruction CopyMI. This returns
142 /// true if the copy was successfully coalesced away. If it is not
143 /// currently possible to coalesce this interval, but it may be possible if
144 /// other things get coalesced, then it returns true by reference in
146 bool joinCopy(MachineInstr *TheCopy, bool &Again);
148 /// Attempt to join these two intervals. On failure, this
149 /// returns false. The output "SrcInt" will not have been modified, so we
150 /// can use this information below to update aliases.
151 bool joinIntervals(CoalescerPair &CP);
153 /// Attempt joining two virtual registers. Return true on success.
154 bool joinVirtRegs(CoalescerPair &CP);
156 /// Attempt joining with a reserved physreg.
157 bool joinReservedPhysReg(CoalescerPair &CP);
159 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
160 /// Subranges in @p LI which only partially interfere with the desired
161 /// LaneMask are split as necessary.
162 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
163 unsigned LaneMask, CoalescerPair &CP);
165 /// Join the liveranges of two subregisters. Joins @p RRange into
166 /// @p LRange, @p RRange may be invalid afterwards.
167 void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
168 const CoalescerPair &CP);
170 /// We found a non-trivially-coalescable copy. If
171 /// the source value number is defined by a copy from the destination reg
172 /// see if we can merge these two destination reg valno# into a single
173 /// value number, eliminating a copy.
174 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
176 /// Return true if there are definitions of IntB
177 /// other than BValNo val# that can reach uses of AValno val# of IntA.
178 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
179 VNInfo *AValNo, VNInfo *BValNo);
181 /// We found a non-trivially-coalescable copy.
182 /// If the source value number is defined by a commutable instruction and
183 /// its other operand is coalesced to the copy dest register, see if we
184 /// can transform the copy into a noop by commuting the definition.
185 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
187 /// If the source of a copy is defined by a
188 /// trivial computation, replace the copy by rematerialize the definition.
189 bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI,
192 /// Return true if a physreg copy should be joined.
193 bool canJoinPhys(const CoalescerPair &CP);
195 /// Replace all defs and uses of SrcReg to DstReg and
196 /// update the subregister number if it is not zero. If DstReg is a
197 /// physical register and the existing subregister number of the def / use
198 /// being updated is not zero, make sure to set it to the correct physical
200 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
202 /// Handle copies of undef values.
203 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
206 static char ID; // Class identification, replacement for typeinfo
207 RegisterCoalescer() : MachineFunctionPass(ID) {
208 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
211 void getAnalysisUsage(AnalysisUsage &AU) const override;
213 void releaseMemory() override;
215 /// This is the pass entry point.
216 bool runOnMachineFunction(MachineFunction&) override;
218 /// Implement the dump method.
219 void print(raw_ostream &O, const Module* = nullptr) const override;
221 } /// end anonymous namespace
223 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
225 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
226 "Simple Register Coalescing", false, false)
227 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
228 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
229 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
230 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
231 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
232 "Simple Register Coalescing", false, false)
234 char RegisterCoalescer::ID = 0;
236 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
237 unsigned &Src, unsigned &Dst,
238 unsigned &SrcSub, unsigned &DstSub) {
240 Dst = MI->getOperand(0).getReg();
241 DstSub = MI->getOperand(0).getSubReg();
242 Src = MI->getOperand(1).getReg();
243 SrcSub = MI->getOperand(1).getSubReg();
244 } else if (MI->isSubregToReg()) {
245 Dst = MI->getOperand(0).getReg();
246 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
247 MI->getOperand(3).getImm());
248 Src = MI->getOperand(2).getReg();
249 SrcSub = MI->getOperand(2).getSubReg();
255 // Return true if this block should be vacated by the coalescer to eliminate
256 // branches. The important cases to handle in the coalescer are critical edges
257 // split during phi elimination which contain only copies. Simple blocks that
258 // contain non-branches should also be vacated, but this can be handled by an
259 // earlier pass similar to early if-conversion.
260 static bool isSplitEdge(const MachineBasicBlock *MBB) {
261 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
264 for (const auto &MI : *MBB) {
265 if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
271 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
275 Flipped = CrossClass = false;
277 unsigned Src, Dst, SrcSub, DstSub;
278 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
280 Partial = SrcSub || DstSub;
282 // If one register is a physreg, it must be Dst.
283 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
284 if (TargetRegisterInfo::isPhysicalRegister(Dst))
287 std::swap(SrcSub, DstSub);
291 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
293 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
294 // Eliminate DstSub on a physreg.
296 Dst = TRI.getSubReg(Dst, DstSub);
297 if (!Dst) return false;
301 // Eliminate SrcSub by picking a corresponding Dst superregister.
303 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
304 if (!Dst) return false;
305 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
309 // Both registers are virtual.
310 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
311 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
313 // Both registers have subreg indices.
314 if (SrcSub && DstSub) {
315 // Copies between different sub-registers are never coalescable.
316 if (Src == Dst && SrcSub != DstSub)
319 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
324 // SrcReg will be merged with a sub-register of DstReg.
326 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
328 // DstReg will be merged with a sub-register of SrcReg.
330 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
332 // This is a straight copy without sub-registers.
333 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
336 // The combined constraint may be impossible to satisfy.
340 // Prefer SrcReg to be a sub-register of DstReg.
341 // FIXME: Coalescer should support subregs symmetrically.
342 if (DstIdx && !SrcIdx) {
344 std::swap(SrcIdx, DstIdx);
348 CrossClass = NewRC != DstRC || NewRC != SrcRC;
350 // Check our invariants
351 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
352 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
353 "Cannot have a physical SubIdx");
359 bool CoalescerPair::flip() {
360 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
362 std::swap(SrcReg, DstReg);
363 std::swap(SrcIdx, DstIdx);
368 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
371 unsigned Src, Dst, SrcSub, DstSub;
372 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
375 // Find the virtual register that is SrcReg.
378 std::swap(SrcSub, DstSub);
379 } else if (Src != SrcReg) {
383 // Now check that Dst matches DstReg.
384 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
385 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
387 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
388 // DstSub could be set for a physreg from INSERT_SUBREG.
390 Dst = TRI.getSubReg(Dst, DstSub);
393 return DstReg == Dst;
394 // This is a partial register copy. Check that the parts match.
395 return TRI.getSubReg(DstReg, SrcSub) == Dst;
397 // DstReg is virtual.
400 // Registers match, do the subregisters line up?
401 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
402 TRI.composeSubRegIndices(DstIdx, DstSub);
406 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
407 AU.setPreservesCFG();
408 AU.addRequired<AliasAnalysis>();
409 AU.addRequired<LiveIntervals>();
410 AU.addPreserved<LiveIntervals>();
411 AU.addPreserved<SlotIndexes>();
412 AU.addRequired<MachineLoopInfo>();
413 AU.addPreserved<MachineLoopInfo>();
414 AU.addPreservedID(MachineDominatorsID);
415 MachineFunctionPass::getAnalysisUsage(AU);
418 void RegisterCoalescer::eliminateDeadDefs() {
419 SmallVector<unsigned, 8> NewRegs;
420 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
421 nullptr, this).eliminateDeadDefs(DeadDefs);
424 // Callback from eliminateDeadDefs().
425 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
426 // MI may be in WorkList. Make sure we don't visit it.
427 ErasedInstrs.insert(MI);
430 /// We found a non-trivially-coalescable copy with IntA
431 /// being the source and IntB being the dest, thus this defines a value number
432 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
433 /// see if we can merge these two pieces of B into a single value number,
434 /// eliminating a copy. For example:
438 /// B1 = A3 <- this copy
440 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
441 /// value number to be replaced with B0 (which simplifies the B liveinterval).
443 /// This returns true if an interval was modified.
445 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
446 MachineInstr *CopyMI) {
447 assert(!CP.isPartial() && "This doesn't work for partial copies.");
448 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
451 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
453 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
454 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
456 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
457 // the example above.
458 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
459 if (BS == IntB.end()) return false;
460 VNInfo *BValNo = BS->valno;
462 // Get the location that B is defined at. Two options: either this value has
463 // an unknown definition point or it is defined at CopyIdx. If unknown, we
465 if (BValNo->def != CopyIdx) return false;
467 // AValNo is the value number in A that defines the copy, A3 in the example.
468 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
469 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
470 // The live segment might not exist after fun with physreg coalescing.
471 if (AS == IntA.end()) return false;
472 VNInfo *AValNo = AS->valno;
474 // If AValNo is defined as a copy from IntB, we can potentially process this.
475 // Get the instruction that defines this value number.
476 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
477 // Don't allow any partial copies, even if isCoalescable() allows them.
478 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
481 // Get the Segment in IntB that this value number starts with.
482 LiveInterval::iterator ValS =
483 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
484 if (ValS == IntB.end())
487 // Make sure that the end of the live segment is inside the same block as
489 MachineInstr *ValSEndInst =
490 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
491 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
494 // Okay, we now know that ValS ends in the same block that the CopyMI
495 // live-range starts. If there are no intervening live segments between them
496 // in IntB, we can merge them.
497 if (ValS+1 != BS) return false;
499 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
501 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
502 // We are about to delete CopyMI, so need to remove it as the 'instruction
503 // that defines this value #'. Update the valnum with the new defining
505 BValNo->def = FillerStart;
507 // Okay, we can merge them. We need to insert a new liverange:
508 // [ValS.end, BS.begin) of either value number, then we merge the
509 // two value numbers.
510 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
512 // Okay, merge "B1" into the same value number as "B0".
513 if (BValNo != ValS->valno)
514 IntB.MergeValueNumberInto(BValNo, ValS->valno);
516 // Do the same for the subregister segments.
517 for (LiveInterval::SubRange &S : IntB.subranges()) {
518 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
519 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
520 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
521 if (SubBValNo != SubValSNo)
522 S.MergeValueNumberInto(SubBValNo, SubValSNo);
525 DEBUG(dbgs() << " result = " << IntB << '\n');
527 // If the source instruction was killing the source register before the
528 // merge, unset the isKill marker given the live range has been extended.
529 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
531 ValSEndInst->getOperand(UIdx).setIsKill(false);
534 // Rewrite the copy. If the copy instruction was killing the destination
535 // register before the merge, find the last use and trim the live range. That
536 // will also add the isKill marker.
537 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
538 if (AS->end == CopyIdx)
539 LIS->shrinkToUses(&IntA);
545 /// Return true if there are definitions of IntB
546 /// other than BValNo val# that can reach uses of AValno val# of IntA.
547 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
551 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
553 if (LIS->hasPHIKill(IntA, AValNo))
556 for (LiveRange::Segment &ASeg : IntA.segments) {
557 if (ASeg.valno != AValNo) continue;
558 LiveInterval::iterator BI =
559 std::upper_bound(IntB.begin(), IntB.end(), ASeg.start);
560 if (BI != IntB.begin())
562 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
563 if (BI->valno == BValNo)
565 if (BI->start <= ASeg.start && BI->end > ASeg.start)
567 if (BI->start > ASeg.start && BI->start < ASeg.end)
574 /// Copy segements with value number @p SrcValNo from liverange @p Src to live
575 /// range @Dst and use value number @p DstValNo there.
576 static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo,
577 const LiveRange &Src, const VNInfo *SrcValNo)
579 for (const LiveRange::Segment &S : Src.segments) {
580 if (S.valno != SrcValNo)
582 Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo));
586 /// We found a non-trivially-coalescable copy with
587 /// IntA being the source and IntB being the dest, thus this defines a value
588 /// number in IntB. If the source value number (in IntA) is defined by a
589 /// commutable instruction and its other operand is coalesced to the copy dest
590 /// register, see if we can transform the copy into a noop by commuting the
591 /// definition. For example,
593 /// A3 = op A2 B0<kill>
595 /// B1 = A3 <- this copy
597 /// = op A3 <- more uses
601 /// B2 = op B0 A2<kill>
603 /// B1 = B2 <- now an identify copy
605 /// = op B2 <- more uses
607 /// This returns true if an interval was modified.
609 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
610 MachineInstr *CopyMI) {
611 assert (!CP.isPhys());
613 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
616 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
618 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
620 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
621 // the example above.
622 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
623 if (!BValNo || BValNo->def != CopyIdx)
626 // AValNo is the value number in A that defines the copy, A3 in the example.
627 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
628 assert(AValNo && "COPY source not live");
629 if (AValNo->isPHIDef() || AValNo->isUnused())
631 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
634 if (!DefMI->isCommutable())
636 // If DefMI is a two-address instruction then commuting it will change the
637 // destination register.
638 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
639 assert(DefIdx != -1);
641 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
643 unsigned Op1, Op2, NewDstIdx;
644 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
648 else if (Op2 == UseOpIdx)
653 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
654 unsigned NewReg = NewDstMO.getReg();
655 if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
658 // Make sure there are no other definitions of IntB that would reach the
659 // uses which the new definition can reach.
660 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
663 // If some of the uses of IntA.reg is already coalesced away, return false.
664 // It's not possible to determine whether it's safe to perform the coalescing.
665 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
666 MachineInstr *UseMI = MO.getParent();
667 unsigned OpNo = &MO - &UseMI->getOperand(0);
668 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
669 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
670 if (US == IntA.end() || US->valno != AValNo)
672 // If this use is tied to a def, we can't rewrite the register.
673 if (UseMI->isRegTiedToDefOperand(OpNo))
677 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
680 // At this point we have decided that it is legal to do this
681 // transformation. Start by commuting the instruction.
682 MachineBasicBlock *MBB = DefMI->getParent();
683 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
686 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
687 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
688 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
690 if (NewMI != DefMI) {
691 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
692 MachineBasicBlock::iterator Pos = DefMI;
693 MBB->insert(Pos, NewMI);
696 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
697 NewMI->getOperand(OpIdx).setIsKill();
699 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
708 // Update uses of IntA of the specific Val# with IntB.
709 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
710 UE = MRI->use_end(); UI != UE;) {
711 MachineOperand &UseMO = *UI;
712 MachineInstr *UseMI = UseMO.getParent();
714 if (UseMI->isDebugValue()) {
715 // FIXME These don't have an instruction index. Not clear we have enough
716 // info to decide whether to do this replacement or not. For now do it.
717 UseMO.setReg(NewReg);
720 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
721 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
722 if (US == IntA.end() || US->valno != AValNo)
724 // Kill flags are no longer accurate. They are recomputed after RA.
725 UseMO.setIsKill(false);
726 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
727 UseMO.substPhysReg(NewReg, *TRI);
729 UseMO.setReg(NewReg);
732 if (!UseMI->isCopy())
734 if (UseMI->getOperand(0).getReg() != IntB.reg ||
735 UseMI->getOperand(0).getSubReg())
738 // This copy will become a noop. If it's defining a new val#, merge it into
740 SlotIndex DefIdx = UseIdx.getRegSlot();
741 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
744 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
745 assert(DVNI->def == DefIdx);
746 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
747 for (LiveInterval::SubRange &S : IntB.subranges()) {
748 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
751 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
752 S.MergeValueNumberInto(SubBValNo, SubDVNI);
755 ErasedInstrs.insert(UseMI);
756 LIS->RemoveMachineInstrFromMaps(UseMI);
757 UseMI->eraseFromParent();
760 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
762 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
763 if (IntB.hasSubRanges()) {
764 if (!IntA.hasSubRanges()) {
765 unsigned Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
766 IntA.createSubRangeFrom(Allocator, Mask, IntA);
768 SlotIndex AIdx = CopyIdx.getRegSlot(true);
769 for (LiveInterval::SubRange &SA : IntA.subranges()) {
770 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
771 if (ASubValNo == nullptr) {
772 DEBUG(dbgs() << "No A Range at " << AIdx << " with mask "
773 << format("%04X", SA.LaneMask) << "\n");
777 unsigned AMask = SA.LaneMask;
778 for (LiveInterval::SubRange &SB : IntB.subranges()) {
779 unsigned BMask = SB.LaneMask;
780 unsigned Common = BMask & AMask;
784 DEBUG(dbgs() << format("\t\tCopy+Merge %04X into %04X\n", BMask, Common));
785 unsigned BRest = BMask & ~AMask;
786 LiveInterval::SubRange *CommonRange;
789 DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", BRest));
790 // Duplicate SubRange for newly merged common stuff.
791 CommonRange = IntB.createSubRangeFrom(Allocator, Common, SB);
793 // We van reuse the L SubRange.
794 SB.LaneMask = Common;
797 LiveRange RangeCopy(SB, Allocator);
799 VNInfo *BSubValNo = CommonRange->getVNInfoAt(CopyIdx);
800 assert(BSubValNo->def == CopyIdx);
801 BSubValNo->def = ASubValNo->def;
802 addSegmentsWithValNo(*CommonRange, BSubValNo, SA, ASubValNo);
806 DEBUG(dbgs() << format("\t\tNew Lane %04X\n", AMask));
807 LiveRange *NewRange = IntB.createSubRange(Allocator, AMask);
808 VNInfo *BSubValNo = NewRange->getNextValue(CopyIdx, Allocator);
809 addSegmentsWithValNo(*NewRange, BSubValNo, SA, ASubValNo);
811 SA.removeValNo(ASubValNo);
813 } else if (IntA.hasSubRanges()) {
814 SlotIndex AIdx = CopyIdx.getRegSlot(true);
815 for (LiveInterval::SubRange &SA : IntA.subranges()) {
816 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
817 if (ASubValNo == nullptr) {
818 DEBUG(dbgs() << "No A Range at " << AIdx << " with mask "
819 << format("%04X", SA.LaneMask) << "\n");
822 SA.removeValNo(ASubValNo);
826 BValNo->def = AValNo->def;
827 addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
828 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
830 IntA.removeValNo(AValNo);
831 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
836 /// If the source of a copy is defined by a trivial
837 /// computation, replace the copy by rematerialize the definition.
838 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP,
839 MachineInstr *CopyMI,
842 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
843 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
844 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
845 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
846 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
849 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
850 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
851 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
852 assert(ValNo && "CopyMI input register not live");
853 if (ValNo->isPHIDef() || ValNo->isUnused())
855 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
858 if (DefMI->isCopyLike()) {
862 if (!TII->isAsCheapAsAMove(DefMI))
864 if (!TII->isTriviallyReMaterializable(DefMI, AA))
866 bool SawStore = false;
867 if (!DefMI->isSafeToMove(TII, AA, SawStore))
869 const MCInstrDesc &MCID = DefMI->getDesc();
870 if (MCID.getNumDefs() != 1)
872 // Only support subregister destinations when the def is read-undef.
873 MachineOperand &DstOperand = CopyMI->getOperand(0);
874 unsigned CopyDstReg = DstOperand.getReg();
875 if (DstOperand.getSubReg() && !DstOperand.isUndef())
878 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
879 // the register substantially (beyond both source and dest size). This is bad
880 // for performance since it can cascade through a function, introducing many
881 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
882 // around after a few subreg copies).
883 if (SrcIdx && DstIdx)
886 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
887 if (!DefMI->isImplicitDef()) {
888 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
889 unsigned NewDstReg = DstReg;
891 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
892 DefMI->getOperand(0).getSubReg());
894 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
896 // Finally, make sure that the physical subregister that will be
897 // constructed later is permitted for the instruction.
898 if (!DefRC->contains(NewDstReg))
901 // Theoretically, some stack frame reference could exist. Just make sure
902 // it hasn't actually happened.
903 assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
904 "Only expect to deal with virtual or physical registers");
908 MachineBasicBlock *MBB = CopyMI->getParent();
909 MachineBasicBlock::iterator MII =
910 std::next(MachineBasicBlock::iterator(CopyMI));
911 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
912 MachineInstr *NewMI = std::prev(MII);
914 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
915 CopyMI->eraseFromParent();
916 ErasedInstrs.insert(CopyMI);
918 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
919 // We need to remember these so we can add intervals once we insert
920 // NewMI into SlotIndexes.
921 SmallVector<unsigned, 4> NewMIImplDefs;
922 for (unsigned i = NewMI->getDesc().getNumOperands(),
923 e = NewMI->getNumOperands(); i != e; ++i) {
924 MachineOperand &MO = NewMI->getOperand(i);
926 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
927 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
928 NewMIImplDefs.push_back(MO.getReg());
932 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
933 const TargetRegisterClass *NewRC = CP.getNewRC();
934 unsigned NewIdx = NewMI->getOperand(0).getSubReg();
937 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
939 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
941 assert(NewRC && "subreg chosen for remat incompatible with instruction");
942 MRI->setRegClass(DstReg, NewRC);
944 updateRegDefsUses(DstReg, DstReg, DstIdx);
945 NewMI->getOperand(0).setSubReg(NewIdx);
946 } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
947 // The New instruction may be defining a sub-register of what's actually
948 // been asked for. If so it must implicitly define the whole thing.
949 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
950 "Only expect virtual or physical registers in remat");
951 NewMI->getOperand(0).setIsDead(true);
952 NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
956 // Record small dead def live-ranges for all the subregisters
957 // of the destination register.
958 // Otherwise, variables that live through may miss some
959 // interferences, thus creating invalid allocation.
961 // vreg1 = somedef ; vreg1 GR8
962 // vreg2 = remat ; vreg2 GR32
963 // CL = COPY vreg2.sub_8bit
964 // = somedef vreg1 ; vreg1 GR8
966 // vreg1 = somedef ; vreg1 GR8
967 // ECX<def, dead> = remat ; CL<imp-def>
968 // = somedef vreg1 ; vreg1 GR8
969 // vreg1 will see the inteferences with CL but not with CH since
970 // no live-ranges would have been created for ECX.
972 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
973 for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI);
974 Units.isValid(); ++Units)
975 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
976 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
979 if (NewMI->getOperand(0).getSubReg())
980 NewMI->getOperand(0).setIsUndef();
982 // CopyMI may have implicit operands, transfer them over to the newly
983 // rematerialized instruction. And update implicit def interval valnos.
984 for (unsigned i = CopyMI->getDesc().getNumOperands(),
985 e = CopyMI->getNumOperands(); i != e; ++i) {
986 MachineOperand &MO = CopyMI->getOperand(i);
988 assert(MO.isImplicit() && "No explicit operands after implict operands.");
989 // Discard VReg implicit defs.
990 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
991 NewMI->addOperand(MO);
996 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
997 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
998 unsigned Reg = NewMIImplDefs[i];
999 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1000 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1001 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1004 DEBUG(dbgs() << "Remat: " << *NewMI);
1007 // The source interval can become smaller because we removed a use.
1008 LIS->shrinkToUses(&SrcInt, &DeadDefs);
1009 if (!DeadDefs.empty()) {
1010 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1011 // to describe DstReg instead.
1012 for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
1013 MachineInstr *UseMI = UseMO.getParent();
1014 if (UseMI->isDebugValue()) {
1015 UseMO.setReg(DstReg);
1016 DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1019 eliminateDeadDefs();
1025 /// ProcessImpicitDefs may leave some copies of <undef>
1026 /// values, it only removes local variables. When we have a copy like:
1028 /// %vreg1 = COPY %vreg2<undef>
1030 /// We delete the copy and remove the corresponding value number from %vreg1.
1031 /// Any uses of that value number are marked as <undef>.
1032 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
1033 const CoalescerPair &CP) {
1034 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
1035 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
1036 if (SrcInt->liveAt(Idx))
1038 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
1039 if (DstInt->liveAt(Idx))
1042 // No intervals are live-in to CopyMI - it is undef.
1047 SlotIndex RegIndex = Idx.getRegSlot();
1048 VNInfo *DeadVNI = DstInt->getVNInfoAt(RegIndex);
1049 assert(DeadVNI && "No value defined in DstInt");
1050 DstInt->removeValNo(DeadVNI);
1051 // Eliminate the corresponding values in the subregister ranges.
1052 for (LiveInterval::SubRange &S : DstInt->subranges()) {
1053 VNInfo *DeadVNI = S.getVNInfoAt(RegIndex);
1054 if (DeadVNI == nullptr)
1056 S.removeValNo(DeadVNI);
1059 // Find new undef uses.
1060 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstInt->reg)) {
1061 if (MO.isDef() || MO.isUndef())
1063 MachineInstr *MI = MO.getParent();
1064 SlotIndex Idx = LIS->getInstructionIndex(MI);
1065 if (DstInt->liveAt(Idx))
1067 MO.setIsUndef(true);
1068 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
1073 /// Replace all defs and uses of SrcReg to DstReg and update the subregister
1074 /// number if it is not zero. If DstReg is a physical register and the existing
1075 /// subregister number of the def / use being updated is not zero, make sure to
1076 /// set it to the correct physical subregister.
1077 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
1080 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1081 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1083 SmallPtrSet<MachineInstr*, 8> Visited;
1084 for (MachineRegisterInfo::reg_instr_iterator
1085 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1087 MachineInstr *UseMI = &*(I++);
1089 // Each instruction can only be rewritten once because sub-register
1090 // composition is not always idempotent. When SrcReg != DstReg, rewriting
1091 // the UseMI operands removes them from the SrcReg use-def chain, but when
1092 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1093 // operands mentioning the virtual register.
1094 if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1097 SmallVector<unsigned,8> Ops;
1099 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1101 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1102 // because SrcReg is a sub-register.
1103 if (DstInt && !Reads && SubIdx)
1104 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
1106 // Replace SrcReg with DstReg in all UseMI operands.
1107 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1108 MachineOperand &MO = UseMI->getOperand(Ops[i]);
1110 // Adjust <undef> flags in case of sub-register joins. We don't want to
1111 // turn a full def into a read-modify-write sub-register def and vice
1113 if (SubIdx && MO.isDef())
1114 MO.setIsUndef(!Reads);
1116 // A subreg use of a partially undef (super) register may be a complete
1117 // undef use now and then has to be marked that way.
1118 if (SubIdx != 0 && MO.isUse() && MRI->tracksSubRegLiveness()) {
1119 if (!DstInt->hasSubRanges()) {
1120 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1121 unsigned Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
1122 DstInt->createSubRangeFrom(Allocator, Mask, *DstInt);
1124 unsigned Mask = TRI->getSubRegIndexLaneMask(SubIdx);
1125 bool IsUndef = true;
1126 SlotIndex MIIdx = UseMI->isDebugValue()
1127 ? LIS->getSlotIndexes()->getIndexBefore(UseMI)
1128 : LIS->getInstructionIndex(UseMI);
1129 SlotIndex UseIdx = MIIdx.getRegSlot(true);
1130 for (LiveInterval::SubRange &S : DstInt->subranges()) {
1131 if ((S.LaneMask & Mask) == 0)
1133 if (S.liveAt(UseIdx)) {
1139 MO.setIsUndef(true);
1140 // We found out some subregister use is actually reading an undefined
1141 // value. In some cases the whole vreg has become undefined at this
1142 // point so we have to potentially shrink the main range if the
1143 // use was ending a live segment there.
1144 LiveQueryResult Q = DstInt->Query(MIIdx);
1145 if (Q.valueOut() == nullptr)
1146 ShrinkMainRange = true;
1151 MO.substPhysReg(DstReg, *TRI);
1153 MO.substVirtReg(DstReg, SubIdx, *TRI);
1157 dbgs() << "\t\tupdated: ";
1158 if (!UseMI->isDebugValue())
1159 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
1165 /// Return true if a copy involving a physreg should be joined.
1166 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1167 /// Always join simple intervals that are defined by a single copy from a
1168 /// reserved register. This doesn't increase register pressure, so it is
1169 /// always beneficial.
1170 if (!MRI->isReserved(CP.getDstReg())) {
1171 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1175 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1176 if (CP.isFlipped() && JoinVInt.containsOneValue())
1179 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
1183 /// Attempt to join intervals corresponding to SrcReg/DstReg,
1184 /// which are the src/dst of the copy instruction CopyMI. This returns true
1185 /// if the copy was successfully coalesced away. If it is not currently
1186 /// possible to coalesce this interval, but it may be possible if other
1187 /// things get coalesced, then it returns true by reference in 'Again'.
1188 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1191 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1193 CoalescerPair CP(*TRI);
1194 if (!CP.setRegisters(CopyMI)) {
1195 DEBUG(dbgs() << "\tNot coalescable.\n");
1199 if (CP.getNewRC()) {
1200 auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1201 auto DstRC = MRI->getRegClass(CP.getDstReg());
1202 unsigned SrcIdx = CP.getSrcIdx();
1203 unsigned DstIdx = CP.getDstIdx();
1204 if (CP.isFlipped()) {
1205 std::swap(SrcIdx, DstIdx);
1206 std::swap(SrcRC, DstRC);
1208 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1210 DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
1215 // Dead code elimination. This really should be handled by MachineDCE, but
1216 // sometimes dead copies slip through, and we can't generate invalid live
1218 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1219 DEBUG(dbgs() << "\tCopy is dead.\n");
1220 DeadDefs.push_back(CopyMI);
1221 eliminateDeadDefs();
1225 // Eliminate undefs.
1226 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1227 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1228 LIS->RemoveMachineInstrFromMaps(CopyMI);
1229 CopyMI->eraseFromParent();
1230 return false; // Not coalescable.
1233 // Coalesced copies are normally removed immediately, but transformations
1234 // like removeCopyByCommutingDef() can inadvertently create identity copies.
1235 // When that happens, just join the values and remove the copy.
1236 if (CP.getSrcReg() == CP.getDstReg()) {
1237 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1238 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1239 const SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
1240 LiveQueryResult LRQ = LI.Query(CopyIdx);
1241 if (VNInfo *DefVNI = LRQ.valueDefined()) {
1242 VNInfo *ReadVNI = LRQ.valueIn();
1243 assert(ReadVNI && "No value before copy and no <undef> flag.");
1244 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1245 LI.MergeValueNumberInto(DefVNI, ReadVNI);
1247 // Process subregister liveranges.
1248 for (LiveInterval::SubRange &S : LI.subranges()) {
1249 LiveQueryResult SLRQ = S.Query(CopyIdx);
1250 if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
1251 VNInfo *SReadVNI = SLRQ.valueIn();
1252 S.MergeValueNumberInto(SDefVNI, SReadVNI);
1255 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
1257 LIS->RemoveMachineInstrFromMaps(CopyMI);
1258 CopyMI->eraseFromParent();
1262 // Enforce policies.
1264 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1265 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1267 if (!canJoinPhys(CP)) {
1268 // Before giving up coalescing, if definition of source is defined by
1269 // trivial computation, try rematerializing it.
1271 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1274 Again = true; // May be possible to coalesce later.
1278 // When possible, let DstReg be the larger interval.
1279 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1280 LIS->getInterval(CP.getDstReg()).size())
1284 dbgs() << "\tConsidering merging to "
1285 << TRI->getRegClassName(CP.getNewRC()) << " with ";
1286 if (CP.getDstIdx() && CP.getSrcIdx())
1287 dbgs() << PrintReg(CP.getDstReg()) << " in "
1288 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1289 << PrintReg(CP.getSrcReg()) << " in "
1290 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1292 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1293 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1298 ShrinkMainRange = false;
1300 // Okay, attempt to join these two intervals. On failure, this returns false.
1301 // Otherwise, if one of the intervals being joined is a physreg, this method
1302 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1303 // been modified, so we can use this information below to update aliases.
1304 if (!joinIntervals(CP)) {
1305 // Coalescing failed.
1307 // If definition of source is defined by trivial computation, try
1308 // rematerializing it.
1310 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1313 // If we can eliminate the copy without merging the live segments, do so
1315 if (!CP.isPartial() && !CP.isPhys()) {
1316 if (adjustCopiesBackFrom(CP, CopyMI) ||
1317 removeCopyByCommutingDef(CP, CopyMI)) {
1318 LIS->RemoveMachineInstrFromMaps(CopyMI);
1319 CopyMI->eraseFromParent();
1320 DEBUG(dbgs() << "\tTrivial!\n");
1325 // Otherwise, we are unable to join the intervals.
1326 DEBUG(dbgs() << "\tInterference!\n");
1327 Again = true; // May be possible to coalesce later.
1331 // Coalescing to a virtual register that is of a sub-register class of the
1332 // other. Make sure the resulting register is set to the right register class.
1333 if (CP.isCrossClass()) {
1335 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1338 // Removing sub-register copies can ease the register class constraints.
1339 // Make sure we attempt to inflate the register class of DstReg.
1340 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1341 InflateRegs.push_back(CP.getDstReg());
1343 // CopyMI has been erased by joinIntervals at this point. Remove it from
1344 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1345 // to the work list. This keeps ErasedInstrs from growing needlessly.
1346 ErasedInstrs.erase(CopyMI);
1348 // Rewrite all SrcReg operands to DstReg.
1349 // Also update DstReg operands to include DstIdx if it is set.
1351 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1352 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1354 // Shrink subregister ranges if necessary.
1355 if (ShrinkMask != 0) {
1356 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1357 for (LiveInterval::SubRange &S : LI.subranges()) {
1358 if ((S.LaneMask & ShrinkMask) == 0)
1360 DEBUG(dbgs() << "Shrink LaneUses (Lane "
1361 << format("%04X", S.LaneMask) << ")\n");
1362 LIS->shrinkToUses(S, LI.reg);
1365 if (ShrinkMainRange) {
1366 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1367 LIS->shrinkToUses(&LI);
1370 // SrcReg is guaranteed to be the register whose live interval that is
1372 LIS->removeInterval(CP.getSrcReg());
1374 // Update regalloc hint.
1375 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1378 dbgs() << "\tSuccess: " << PrintReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
1379 << " -> " << PrintReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
1380 dbgs() << "\tResult = ";
1382 dbgs() << PrintReg(CP.getDstReg(), TRI);
1384 dbgs() << LIS->getInterval(CP.getDstReg());
1392 /// Attempt joining with a reserved physreg.
1393 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1394 assert(CP.isPhys() && "Must be a physreg copy");
1395 assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
1396 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1397 DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1399 assert(CP.isFlipped() && RHS.containsOneValue() &&
1400 "Invalid join with reserved register");
1402 // Optimization for reserved registers like ESP. We can only merge with a
1403 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1404 // The live range of the reserved register will look like a set of dead defs
1405 // - we don't properly track the live range of reserved registers.
1407 // Deny any overlapping intervals. This depends on all the reserved
1408 // register live ranges to look like dead defs.
1409 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1410 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1411 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1415 // Skip any value computations, we are not adding new values to the
1416 // reserved register. Also skip merging the live ranges, the reserved
1417 // register live range doesn't need to be accurate as long as all the
1420 // Delete the identity copy.
1421 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1422 LIS->RemoveMachineInstrFromMaps(CopyMI);
1423 CopyMI->eraseFromParent();
1425 // We don't track kills for reserved registers.
1426 MRI->clearKillFlags(CP.getSrcReg());
1431 //===----------------------------------------------------------------------===//
1432 // Interference checking and interval joining
1433 //===----------------------------------------------------------------------===//
1435 // In the easiest case, the two live ranges being joined are disjoint, and
1436 // there is no interference to consider. It is quite common, though, to have
1437 // overlapping live ranges, and we need to check if the interference can be
1440 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1441 // This means that two SSA values overlap if and only if the def of one value
1442 // is contained in the live range of the other value. As a special case, the
1443 // overlapping values can be defined at the same index.
1445 // The interference from an overlapping def can be resolved in these cases:
1447 // 1. Coalescable copies. The value is defined by a copy that would become an
1448 // identity copy after joining SrcReg and DstReg. The copy instruction will
1449 // be removed, and the value will be merged with the source value.
1451 // There can be several copies back and forth, causing many values to be
1452 // merged into one. We compute a list of ultimate values in the joined live
1453 // range as well as a mappings from the old value numbers.
1455 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1456 // predecessors have a live out value. It doesn't cause real interference,
1457 // and can be merged into the value it overlaps. Like a coalescable copy, it
1458 // can be erased after joining.
1460 // 3. Copy of external value. The overlapping def may be a copy of a value that
1461 // is already in the other register. This is like a coalescable copy, but
1462 // the live range of the source register must be trimmed after erasing the
1463 // copy instruction:
1466 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1468 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1469 // defining one lane at a time:
1471 // %dst:ssub0<def,read-undef> = FOO
1473 // %dst:ssub1<def> = COPY %src
1475 // The live range of %src overlaps the %dst value defined by FOO, but
1476 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1477 // which was undef anyway.
1479 // The value mapping is more complicated in this case. The final live range
1480 // will have different value numbers for both FOO and BAR, but there is no
1481 // simple mapping from old to new values. It may even be necessary to add
1484 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1485 // is live, but never read. This can happen because we don't compute
1486 // individual live ranges per lane.
1490 // %dst:ssub1<def> = COPY %src
1492 // This kind of interference is only resolved locally. If the clobbered
1493 // lane value escapes the block, the join is aborted.
1496 /// Track information about values in a single virtual register about to be
1497 /// joined. Objects of this class are always created in pairs - one for each
1498 /// side of the CoalescerPair (or one for each lane of a side of the coalescer
1501 /// Live range we work on.
1503 /// (Main) register we work on.
1506 /// This is true when joining sub register ranges, false when joining main
1508 const bool SubRangeJoin;
1509 /// Whether the current LiveInterval tracks subregister liveness.
1510 const bool TrackSubRegLiveness;
1512 // Location of this register in the final joined register.
1513 // Either CP.DstIdx or CP.SrcIdx.
1514 const unsigned SubIdx;
1516 // Values that will be present in the final live range.
1517 SmallVectorImpl<VNInfo*> &NewVNInfo;
1519 const CoalescerPair &CP;
1521 SlotIndexes *Indexes;
1522 const TargetRegisterInfo *TRI;
1524 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1525 // This is suitable for passing to LiveInterval::join().
1526 SmallVector<int, 8> Assignments;
1528 // Conflict resolution for overlapping values.
1529 enum ConflictResolution {
1530 // No overlap, simply keep this value.
1533 // Merge this value into OtherVNI and erase the defining instruction.
1534 // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1538 // Merge this value into OtherVNI but keep the defining instruction.
1539 // This is for the special case where OtherVNI is defined by the same
1543 // Keep this value, and have it replace OtherVNI where possible. This
1544 // complicates value mapping since OtherVNI maps to two different values
1545 // before and after this def.
1546 // Used when clobbering undefined or dead lanes.
1549 // Unresolved conflict. Visit later when all values have been mapped.
1552 // Unresolvable conflict. Abort the join.
1556 // Per-value info for LI. The lane bit masks are all relative to the final
1557 // joined register, so they can be compared directly between SrcReg and
1560 ConflictResolution Resolution;
1562 // Lanes written by this def, 0 for unanalyzed values.
1563 unsigned WriteLanes;
1565 // Lanes with defined values in this register. Other lanes are undef and
1567 unsigned ValidLanes;
1569 // Value in LI being redefined by this def.
1572 // Value in the other live range that overlaps this def, if any.
1575 // Is this value an IMPLICIT_DEF that can be erased?
1577 // IMPLICIT_DEF values should only exist at the end of a basic block that
1578 // is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1579 // safely erased if they are overlapping a live value in the other live
1582 // Weird control flow graphs and incomplete PHI handling in
1583 // ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1584 // longer live ranges. Such IMPLICIT_DEF values should be treated like
1586 bool ErasableImplicitDef;
1588 // True when the live range of this value will be pruned because of an
1589 // overlapping CR_Replace value in the other live range.
1592 // True once Pruned above has been computed.
1593 bool PrunedComputed;
1595 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1596 RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false),
1597 Pruned(false), PrunedComputed(false) {}
1599 bool isAnalyzed() const { return WriteLanes != 0; }
1602 // One entry per value number in LI.
1603 SmallVector<Val, 8> Vals;
1605 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
1606 VNInfo *stripCopies(VNInfo *VNI) const;
1607 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1608 void computeAssignment(unsigned ValNo, JoinVals &Other);
1609 bool taintExtent(unsigned, unsigned, JoinVals&,
1610 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1611 bool usesLanes(const MachineInstr *MI, unsigned, unsigned, unsigned) const;
1612 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1615 JoinVals(LiveRange &LR, unsigned Reg, unsigned subIdx,
1616 SmallVectorImpl<VNInfo*> &newVNInfo,
1617 const CoalescerPair &cp, LiveIntervals *lis,
1618 const TargetRegisterInfo *tri, bool SubRangeJoin,
1619 bool TrackSubRegLiveness)
1620 : LR(LR), Reg(Reg), SubRangeJoin(SubRangeJoin),
1621 TrackSubRegLiveness(TrackSubRegLiveness), SubIdx(subIdx),
1622 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
1623 TRI(tri), Assignments(LR.getNumValNums(), -1),
1624 Vals(LR.getNumValNums())
1627 /// Analyze defs in LR and compute a value mapping in NewVNInfo.
1628 /// Returns false if any conflicts were impossible to resolve.
1629 bool mapValues(JoinVals &Other);
1631 /// Try to resolve conflicts that require all values to be mapped.
1632 /// Returns false if any conflicts were impossible to resolve.
1633 bool resolveConflicts(JoinVals &Other);
1635 /// Prune the live range of values in Other.LR where they would conflict with
1636 /// CR_Replace values in LR. Collect end points for restoring the live range
1638 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
1641 // Removes subranges starting at copies that get removed. This sometimes
1642 // happens when undefined subranges are copied around. These ranges contain
1643 // no usefull information and can be removed.
1644 void pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask);
1646 /// Erase any machine instructions that have been coalesced away.
1647 /// Add erased instructions to ErasedInstrs.
1648 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1649 /// the erased instrs.
1650 void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
1651 SmallVectorImpl<unsigned> &ShrinkRegs);
1653 /// Get the value assignments suitable for passing to LiveInterval::join.
1654 const int *getAssignments() const { return Assignments.data(); }
1656 } // end anonymous namespace
1658 /// Compute the bitmask of lanes actually written by DefMI.
1659 /// Set Redef if there are any partial register definitions that depend on the
1660 /// previous value of the register.
1661 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
1664 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1665 if (!MO->isReg() || MO->getReg() != Reg || !MO->isDef())
1667 L |= TRI->getSubRegIndexLaneMask(
1668 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1675 /// Find the ultimate value that VNI was copied from.
1676 VNInfo *JoinVals::stripCopies(VNInfo *VNI) const {
1677 while (!VNI->isPHIDef()) {
1678 MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1679 assert(MI && "No defining instruction");
1680 if (!MI->isFullCopy())
1682 unsigned Reg = MI->getOperand(1).getReg();
1683 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1685 LiveQueryResult LRQ = LIS->getInterval(Reg).Query(VNI->def);
1688 VNI = LRQ.valueIn();
1693 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1694 /// Return a conflict resolution when possible, but leave the hard cases as
1696 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1697 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1698 /// The recursion always goes upwards in the dominator tree, making loops
1700 JoinVals::ConflictResolution
1701 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1702 Val &V = Vals[ValNo];
1703 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1704 VNInfo *VNI = LR.getValNumInfo(ValNo);
1705 if (VNI->isUnused()) {
1710 // Get the instruction defining this value, compute the lanes written.
1711 const MachineInstr *DefMI = nullptr;
1712 if (VNI->isPHIDef()) {
1713 // Conservatively assume that all lanes in a PHI are valid.
1714 unsigned Lanes = SubRangeJoin ? 1 : TRI->getSubRegIndexLaneMask(SubIdx);
1715 V.ValidLanes = V.WriteLanes = Lanes;
1717 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1718 assert(DefMI != nullptr);
1720 // We don't care about the lanes when joining subregister ranges.
1721 V.ValidLanes = V.WriteLanes = 1;
1724 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1726 // If this is a read-modify-write instruction, there may be more valid
1727 // lanes than the ones written by this instruction.
1728 // This only covers partial redef operands. DefMI may have normal use
1729 // operands reading the register. They don't contribute valid lanes.
1731 // This adds ssub1 to the set of valid lanes in %src:
1733 // %src:ssub1<def> = FOO
1735 // This leaves only ssub1 valid, making any other lanes undef:
1737 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1739 // The <read-undef> flag on the def operand means that old lane values are
1742 V.RedefVNI = LR.Query(VNI->def).valueIn();
1743 assert(V.RedefVNI && "Instruction is reading nonexistent value");
1744 computeAssignment(V.RedefVNI->id, Other);
1745 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1748 // An IMPLICIT_DEF writes undef values.
1749 if (DefMI->isImplicitDef()) {
1750 // We normally expect IMPLICIT_DEF values to be live only until the end
1751 // of their block. If the value is really live longer and gets pruned in
1752 // another block, this flag is cleared again.
1753 V.ErasableImplicitDef = true;
1754 V.ValidLanes &= ~V.WriteLanes;
1759 // Find the value in Other that overlaps VNI->def, if any.
1760 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
1762 // It is possible that both values are defined by the same instruction, or
1763 // the values are PHIs defined in the same block. When that happens, the two
1764 // values should be merged into one, but not into any preceding value.
1765 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1766 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1767 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1769 // One value stays, the other is merged. Keep the earlier one, or the first
1771 if (OtherVNI->def < VNI->def)
1772 Other.computeAssignment(OtherVNI->id, *this);
1773 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1774 // This is an early-clobber def overlapping a live-in value in the other
1775 // register. Not mergeable.
1776 V.OtherVNI = OtherLRQ.valueIn();
1777 return CR_Impossible;
1779 V.OtherVNI = OtherVNI;
1780 Val &OtherV = Other.Vals[OtherVNI->id];
1781 // Keep this value, check for conflicts when analyzing OtherVNI.
1782 if (!OtherV.isAnalyzed())
1784 // Both sides have been analyzed now.
1785 // Allow overlapping PHI values. Any real interference would show up in a
1786 // predecessor, the PHI itself can't introduce any conflicts.
1787 if (VNI->isPHIDef())
1789 if (V.ValidLanes & OtherV.ValidLanes)
1790 // Overlapping lanes can't be resolved.
1791 return CR_Impossible;
1796 // No simultaneous def. Is Other live at the def?
1797 V.OtherVNI = OtherLRQ.valueIn();
1799 // No overlap, no conflict.
1802 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1804 // We have overlapping values, or possibly a kill of Other.
1805 // Recursively compute assignments up the dominator tree.
1806 Other.computeAssignment(V.OtherVNI->id, *this);
1807 Val &OtherV = Other.Vals[V.OtherVNI->id];
1809 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
1810 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
1811 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
1814 // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
1815 // to erase the IMPLICIT_DEF instruction.
1816 if (OtherV.ErasableImplicitDef && DefMI &&
1817 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
1818 DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
1819 << " extends into BB#" << DefMI->getParent()->getNumber()
1820 << ", keeping it.\n");
1821 OtherV.ErasableImplicitDef = false;
1824 // Allow overlapping PHI values. Any real interference would show up in a
1825 // predecessor, the PHI itself can't introduce any conflicts.
1826 if (VNI->isPHIDef())
1829 // Check for simple erasable conflicts.
1830 if (DefMI->isImplicitDef())
1833 // Include the non-conflict where DefMI is a coalescable copy that kills
1834 // OtherVNI. We still want the copy erased and value numbers merged.
1835 if (CP.isCoalescable(DefMI)) {
1836 // Some of the lanes copied from OtherVNI may be undef, making them undef
1838 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1842 // This may not be a real conflict if DefMI simply kills Other and defines
1844 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1847 // Handle the case where VNI and OtherVNI can be proven to be identical:
1849 // %other = COPY %ext
1850 // %this = COPY %ext <-- Erase this copy
1852 if (DefMI->isFullCopy() && !CP.isPartial()) {
1853 VNInfo *TVNI = stripCopies(VNI);
1854 VNInfo *OVNI = stripCopies(V.OtherVNI);
1855 // Map our subrange values to main range as stripCopies() follows the main
1857 if (SubRangeJoin && TVNI != OVNI) {
1859 LiveInterval &LI = LIS->getInterval(Reg);
1860 TVNI = LI.getVNInfoAt(TVNI->def);
1862 if (OVNI == V.OtherVNI) {
1863 LiveInterval &LI = LIS->getInterval(Other.Reg);
1864 OVNI = LI.getVNInfoAt(OVNI->def);
1873 // If the lanes written by this instruction were all undef in OtherVNI, it is
1874 // still safe to join the live ranges. This can't be done with a simple value
1875 // mapping, though - OtherVNI will map to multiple values:
1877 // 1 %dst:ssub0 = FOO <-- OtherVNI
1878 // 2 %src = BAR <-- VNI
1879 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
1881 // 5 QUUX %src<kill>
1883 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1884 // handles this complex value mapping.
1885 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1888 // If the other live range is killed by DefMI and the live ranges are still
1889 // overlapping, it must be because we're looking at an early clobber def:
1891 // %dst<def,early-clobber> = ASM %src<kill>
1893 // In this case, it is illegal to merge the two live ranges since the early
1894 // clobber def would clobber %src before it was read.
1895 if (OtherLRQ.isKill()) {
1896 // This case where the def doesn't overlap the kill is handled above.
1897 assert(VNI->def.isEarlyClobber() &&
1898 "Only early clobber defs can overlap a kill");
1899 return CR_Impossible;
1902 // VNI is clobbering live lanes in OtherVNI, but there is still the
1903 // possibility that no instructions actually read the clobbered lanes.
1904 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1905 // Otherwise Other.RI wouldn't be live here.
1906 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1907 return CR_Impossible;
1909 // We need to verify that no instructions are reading the clobbered lanes. To
1910 // save compile time, we'll only check that locally. Don't allow the tainted
1911 // value to escape the basic block.
1912 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1913 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1914 return CR_Impossible;
1916 // There are still some things that could go wrong besides clobbered lanes
1917 // being read, for example OtherVNI may be only partially redefined in MBB,
1918 // and some clobbered lanes could escape the block. Save this analysis for
1919 // resolveConflicts() when all values have been mapped. We need to know
1920 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1921 // that now - the recursive analyzeValue() calls must go upwards in the
1923 return CR_Unresolved;
1926 /// Compute the value assignment for ValNo in RI.
1927 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1929 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1930 Val &V = Vals[ValNo];
1931 if (V.isAnalyzed()) {
1932 // Recursion should always move up the dominator tree, so ValNo is not
1933 // supposed to reappear before it has been assigned.
1934 assert(Assignments[ValNo] != -1 && "Bad recursion?");
1937 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1940 // Merge this ValNo into OtherVNI.
1941 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1942 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1943 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1944 DEBUG(dbgs() << "\t\tmerge " << PrintReg(Reg) << ':' << ValNo << '@'
1945 << LR.getValNumInfo(ValNo)->def << " into "
1946 << PrintReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
1947 << V.OtherVNI->def << " --> @"
1948 << NewVNInfo[Assignments[ValNo]]->def << '\n');
1951 case CR_Unresolved: {
1952 // The other value is going to be pruned if this join is successful.
1953 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
1954 Val &OtherV = Other.Vals[V.OtherVNI->id];
1955 // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
1957 if ((OtherV.WriteLanes & ~V.ValidLanes) != 0 && TrackSubRegLiveness)
1958 OtherV.ErasableImplicitDef = false;
1959 OtherV.Pruned = true;
1963 // This value number needs to go in the final joined live range.
1964 Assignments[ValNo] = NewVNInfo.size();
1965 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
1970 bool JoinVals::mapValues(JoinVals &Other) {
1971 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
1972 computeAssignment(i, Other);
1973 if (Vals[i].Resolution == CR_Impossible) {
1974 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(Reg) << ':' << i
1975 << '@' << LR.getValNumInfo(i)->def << '\n');
1982 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
1983 /// the extent of the tainted lanes in the block.
1985 /// Multiple values in Other.LR can be affected since partial redefinitions can
1986 /// preserve previously tainted lanes.
1988 /// 1 %dst = VLOAD <-- Define all lanes in %dst
1989 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
1990 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
1991 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1993 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1994 /// entry to TaintedVals.
1996 /// Returns false if the tainted lanes extend beyond the basic block.
1998 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
1999 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
2000 VNInfo *VNI = LR.getValNumInfo(ValNo);
2001 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2002 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2004 // Scan Other.LR from VNI.def to MBBEnd.
2005 LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
2006 assert(OtherI != Other.LR.end() && "No conflict?");
2008 // OtherI is pointing to a tainted value. Abort the join if the tainted
2009 // lanes escape the block.
2010 SlotIndex End = OtherI->end;
2011 if (End >= MBBEnd) {
2012 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.Reg) << ':'
2013 << OtherI->valno->id << '@' << OtherI->start << '\n');
2016 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.Reg) << ':'
2017 << OtherI->valno->id << '@' << OtherI->start
2018 << " to " << End << '\n');
2019 // A dead def is not a problem.
2022 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2024 // Check for another def in the MBB.
2025 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2028 // Lanes written by the new def are no longer tainted.
2029 const Val &OV = Other.Vals[OtherI->valno->id];
2030 TaintedLanes &= ~OV.WriteLanes;
2033 } while (TaintedLanes);
2037 /// Return true if MI uses any of the given Lanes from Reg.
2038 /// This does not include partial redefinitions of Reg.
2039 bool JoinVals::usesLanes(const MachineInstr *MI, unsigned Reg, unsigned SubIdx,
2040 unsigned Lanes) const {
2041 if (MI->isDebugValue())
2043 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
2044 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
2046 if (!MO->readsReg())
2048 if (Lanes & TRI->getSubRegIndexLaneMask(
2049 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
2055 bool JoinVals::resolveConflicts(JoinVals &Other) {
2056 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2058 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
2059 if (V.Resolution != CR_Unresolved)
2061 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(Reg) << ':' << i
2062 << '@' << LR.getValNumInfo(i)->def << '\n');
2067 assert(V.OtherVNI && "Inconsistent conflict resolution.");
2068 VNInfo *VNI = LR.getValNumInfo(i);
2069 const Val &OtherV = Other.Vals[V.OtherVNI->id];
2071 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
2072 // join, those lanes will be tainted with a wrong value. Get the extent of
2073 // the tainted lanes.
2074 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2075 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
2076 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2077 // Tainted lanes would extend beyond the basic block.
2080 assert(!TaintExtent.empty() && "There should be at least one conflict.");
2082 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
2083 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2084 MachineBasicBlock::iterator MI = MBB->begin();
2085 if (!VNI->isPHIDef()) {
2086 MI = Indexes->getInstructionFromIndex(VNI->def);
2087 // No need to check the instruction defining VNI for reads.
2090 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
2091 "Interference ends on VNI->def. Should have been handled earlier");
2092 MachineInstr *LastMI =
2093 Indexes->getInstructionFromIndex(TaintExtent.front().first);
2094 assert(LastMI && "Range must end at a proper instruction");
2095 unsigned TaintNum = 0;
2097 assert(MI != MBB->end() && "Bad LastMI");
2098 if (usesLanes(MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2099 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
2102 // LastMI is the last instruction to use the current value.
2103 if (&*MI == LastMI) {
2104 if (++TaintNum == TaintExtent.size())
2106 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
2107 assert(LastMI && "Range must end at a proper instruction");
2108 TaintedLanes = TaintExtent[TaintNum].second;
2113 // The tainted lanes are unused.
2114 V.Resolution = CR_Replace;
2120 // Determine if ValNo is a copy of a value number in LR or Other.LR that will
2124 // %src = COPY %dst <-- This value to be pruned.
2125 // %dst = COPY %src <-- This value is a copy of a pruned value.
2127 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
2128 Val &V = Vals[ValNo];
2129 if (V.Pruned || V.PrunedComputed)
2132 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2135 // Follow copies up the dominator tree and check if any intermediate value
2137 V.PrunedComputed = true;
2138 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
2142 void JoinVals::pruneValues(JoinVals &Other,
2143 SmallVectorImpl<SlotIndex> &EndPoints,
2144 bool changeInstrs) {
2145 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2146 SlotIndex Def = LR.getValNumInfo(i)->def;
2147 switch (Vals[i].Resolution) {
2151 // This value takes precedence over the value in Other.LR.
2152 LIS->pruneValue(Other.LR, Def, &EndPoints);
2153 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
2154 // instructions are only inserted to provide a live-out value for PHI
2155 // predecessors, so the instruction should simply go away once its value
2156 // has been replaced.
2157 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2158 bool EraseImpDef = OtherV.ErasableImplicitDef &&
2159 OtherV.Resolution == CR_Keep;
2160 if (!Def.isBlock()) {
2162 // Remove <def,read-undef> flags. This def is now a partial redef.
2163 // Also remove <def,dead> flags since the joined live range will
2164 // continue past this instruction.
2165 for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
2166 MO.isValid(); ++MO) {
2167 if (MO->isReg() && MO->isDef() && MO->getReg() == Reg) {
2168 MO->setIsUndef(EraseImpDef);
2169 MO->setIsDead(false);
2173 // This value will reach instructions below, but we need to make sure
2174 // the live range also reaches the instruction at Def.
2176 EndPoints.push_back(Def);
2178 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.Reg) << " at " << Def
2179 << ": " << Other.LR << '\n');
2184 if (isPrunedValue(i, Other)) {
2185 // This value is ultimately a copy of a pruned value in LR or Other.LR.
2186 // We can no longer trust the value mapping computed by
2187 // computeAssignment(), the value that was originally copied could have
2189 LIS->pruneValue(LR, Def, &EndPoints);
2190 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(Reg) << " at "
2191 << Def << ": " << LR << '\n');
2196 llvm_unreachable("Unresolved conflicts");
2201 void JoinVals::pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask)
2203 // Look for values being erased.
2204 bool DidPrune = false;
2205 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2206 if (Vals[i].Resolution != CR_Erase)
2209 // Check subranges at the point where the copy will be removed.
2210 SlotIndex Def = LR.getValNumInfo(i)->def;
2211 for (LiveInterval::SubRange &S : LI.subranges()) {
2212 LiveQueryResult Q = S.Query(Def);
2214 // If a subrange starts at the copy then an undefined value has been
2215 // copied and we must remove that subrange value as well.
2216 VNInfo *ValueOut = Q.valueOutOrDead();
2217 if (ValueOut != nullptr && Q.valueIn() == nullptr) {
2218 DEBUG(dbgs() << "\t\tPrune sublane " << format("%04X", S.LaneMask)
2219 << " at " << Def << "\n");
2220 LIS->pruneValue(S, Def, nullptr);
2222 // Mark value number as unused.
2223 ValueOut->markUnused();
2226 // If a subrange ends at the copy, then a value was copied but only
2227 // partially used later. Shrink the subregister range apropriately.
2228 if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
2229 DEBUG(dbgs() << "\t\tDead uses at sublane "
2230 << format("%04X", S.LaneMask) << " at " << Def << "\n");
2231 ShrinkMask |= S.LaneMask;
2236 LI.removeEmptySubRanges();
2239 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2240 SmallVectorImpl<unsigned> &ShrinkRegs) {
2241 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2242 // Get the def location before markUnused() below invalidates it.
2243 SlotIndex Def = LR.getValNumInfo(i)->def;
2244 switch (Vals[i].Resolution) {
2246 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
2247 // longer. The IMPLICIT_DEF instructions are only inserted by
2248 // PHIElimination to guarantee that all PHI predecessors have a value.
2249 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
2251 // Remove value number i from LR. Note that this VNInfo is still present
2252 // in NewVNInfo, so it will appear as an unused value number in the final
2254 LR.getValNumInfo(i)->markUnused();
2255 LR.removeValNo(LR.getValNumInfo(i));
2256 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n');
2260 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2261 assert(MI && "No instruction to erase");
2263 unsigned Reg = MI->getOperand(1).getReg();
2264 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
2265 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
2266 ShrinkRegs.push_back(Reg);
2268 ErasedInstrs.insert(MI);
2269 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
2270 LIS->RemoveMachineInstrFromMaps(MI);
2271 MI->eraseFromParent();
2280 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
2281 const CoalescerPair &CP) {
2282 SmallVector<VNInfo*, 16> NewVNInfo;
2283 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(),
2284 NewVNInfo, CP, LIS, TRI, true, true);
2285 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(),
2286 NewVNInfo, CP, LIS, TRI, true, true);
2288 /// Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
2289 /// Conflicts should already be resolved so the mapping/resolution should
2291 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2292 llvm_unreachable("Can't join subrange although main ranges are compatible");
2293 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2294 llvm_unreachable("Can't join subrange although main ranges are compatible");
2296 // The merging algorithm in LiveInterval::join() can't handle conflicting
2297 // value mappings, so we need to remove any live ranges that overlap a
2298 // CR_Replace resolution. Collect a set of end points that can be used to
2299 // restore the live range after joining.
2300 SmallVector<SlotIndex, 8> EndPoints;
2301 LHSVals.pruneValues(RHSVals, EndPoints, false);
2302 RHSVals.pruneValues(LHSVals, EndPoints, false);
2307 // Join RRange into LHS.
2308 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
2311 DEBUG(dbgs() << "\t\tjoined lanes: " << LRange << "\n");
2312 if (EndPoints.empty())
2315 // Recompute the parts of the live range we had to remove because of
2316 // CR_Replace conflicts.
2317 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2318 << " points: " << LRange << '\n');
2319 LIS->extendToIndices(LRange, EndPoints);
2322 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
2323 const LiveRange &ToMerge,
2325 CoalescerPair &CP) {
2326 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2327 for (LiveInterval::SubRange &R : LI.subranges()) {
2328 unsigned RMask = R.LaneMask;
2329 // LaneMask of subregisters common to subrange R and ToMerge.
2330 unsigned Common = RMask & LaneMask;
2331 // There is nothing to do without common subregs.
2335 DEBUG(dbgs() << format("\t\tCopy+Merge %04X into %04X\n", RMask, Common));
2336 // LaneMask of subregisters contained in the R range but not in ToMerge,
2337 // they have to split into their own subrange.
2338 unsigned LRest = RMask & ~LaneMask;
2339 LiveInterval::SubRange *CommonRange;
2342 DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", LRest));
2343 // Duplicate SubRange for newly merged common stuff.
2344 CommonRange = LI.createSubRangeFrom(Allocator, Common, R);
2346 // Reuse the existing range.
2347 R.LaneMask = Common;
2350 LiveRange RangeCopy(ToMerge, Allocator);
2351 joinSubRegRanges(*CommonRange, RangeCopy, CP);
2355 if (LaneMask != 0) {
2356 DEBUG(dbgs() << format("\t\tNew Lane %04X\n", LaneMask));
2357 LI.createSubRangeFrom(Allocator, LaneMask, ToMerge);
2361 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
2362 SmallVector<VNInfo*, 16> NewVNInfo;
2363 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
2364 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
2365 bool TrackSubRegLiveness = MRI->tracksSubRegLiveness();
2366 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI,
2367 false, TrackSubRegLiveness);
2368 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), NewVNInfo, CP, LIS, TRI,
2369 false, TrackSubRegLiveness);
2371 DEBUG(dbgs() << "\t\tRHS = " << RHS
2372 << "\n\t\tLHS = " << LHS
2375 // First compute NewVNInfo and the simple value mappings.
2376 // Detect impossible conflicts early.
2377 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2380 // Some conflicts can only be resolved after all values have been mapped.
2381 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2384 // All clear, the live ranges can be merged.
2385 if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
2386 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2387 unsigned DstIdx = CP.getDstIdx();
2388 if (!LHS.hasSubRanges()) {
2389 unsigned Mask = CP.getNewRC()->getLaneMask();
2390 unsigned DstMask = TRI->composeSubRegIndexLaneMask(DstIdx, Mask);
2391 // LHS must support subregs or we wouldn't be in this codepath.
2392 assert(DstMask != 0);
2393 LHS.createSubRangeFrom(Allocator, DstMask, LHS);
2394 DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
2395 << ' ' << LHS << '\n');
2396 } else if (DstIdx != 0) {
2397 // Transform LHS lanemasks to new register class if necessary.
2398 for (LiveInterval::SubRange &R : LHS.subranges()) {
2399 unsigned DstMask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
2400 R.LaneMask = DstMask;
2402 DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
2403 << ' ' << LHS << '\n');
2406 unsigned SrcIdx = CP.getSrcIdx();
2407 if (!RHS.hasSubRanges()) {
2408 unsigned Mask = SrcIdx != 0
2409 ? TRI->getSubRegIndexLaneMask(SrcIdx)
2410 : MRI->getMaxLaneMaskForVReg(LHS.reg);
2412 DEBUG(dbgs() << "\t\tRHS Mask: "
2413 << format("%04X", Mask) << "\n");
2414 mergeSubRangeInto(LHS, RHS, Mask, CP);
2416 // Pair up subranges and merge.
2417 for (LiveInterval::SubRange &R : RHS.subranges()) {
2418 unsigned RMask = R.LaneMask;
2420 // Transform LaneMask of RHS subranges to the ones on LHS.
2421 RMask = TRI->composeSubRegIndexLaneMask(SrcIdx, RMask);
2422 DEBUG(dbgs() << "\t\tTransform RHS Mask "
2423 << format("%04X", R.LaneMask) << " to subreg "
2424 << TRI->getSubRegIndexName(SrcIdx)
2425 << " => " << format("%04X", RMask) << "\n");
2428 mergeSubRangeInto(LHS, R, RMask, CP);
2432 DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
2434 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
2435 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
2438 // The merging algorithm in LiveInterval::join() can't handle conflicting
2439 // value mappings, so we need to remove any live ranges that overlap a
2440 // CR_Replace resolution. Collect a set of end points that can be used to
2441 // restore the live range after joining.
2442 SmallVector<SlotIndex, 8> EndPoints;
2443 LHSVals.pruneValues(RHSVals, EndPoints, true);
2444 RHSVals.pruneValues(LHSVals, EndPoints, true);
2446 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
2447 // registers to require trimming.
2448 SmallVector<unsigned, 8> ShrinkRegs;
2449 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2450 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2451 while (!ShrinkRegs.empty())
2452 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
2454 // Join RHS into LHS.
2455 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
2457 // Kill flags are going to be wrong if the live ranges were overlapping.
2458 // Eventually, we should simply clear all kill flags when computing live
2459 // ranges. They are reinserted after register allocation.
2460 MRI->clearKillFlags(LHS.reg);
2461 MRI->clearKillFlags(RHS.reg);
2463 if (!EndPoints.empty()) {
2464 // Recompute the parts of the live range we had to remove because of
2465 // CR_Replace conflicts.
2466 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2467 << " points: " << LHS << '\n');
2468 LIS->extendToIndices((LiveRange&)LHS, EndPoints);
2474 /// Attempt to join these two intervals. On failure, this returns false.
2475 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
2476 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
2480 // Information concerning MBB coalescing priority.
2481 struct MBBPriorityInfo {
2482 MachineBasicBlock *MBB;
2486 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
2487 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
2491 // C-style comparator that sorts first based on the loop depth of the basic
2492 // block (the unsigned), and then on the MBB number.
2494 // EnableGlobalCopies assumes that the primary sort key is loop depth.
2495 static int compareMBBPriority(const MBBPriorityInfo *LHS,
2496 const MBBPriorityInfo *RHS) {
2497 // Deeper loops first
2498 if (LHS->Depth != RHS->Depth)
2499 return LHS->Depth > RHS->Depth ? -1 : 1;
2501 // Try to unsplit critical edges next.
2502 if (LHS->IsSplit != RHS->IsSplit)
2503 return LHS->IsSplit ? -1 : 1;
2505 // Prefer blocks that are more connected in the CFG. This takes care of
2506 // the most difficult copies first while intervals are short.
2507 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
2508 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
2510 return cl > cr ? -1 : 1;
2512 // As a last resort, sort by block number.
2513 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
2516 /// \returns true if the given copy uses or defines a local live range.
2517 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
2518 if (!Copy->isCopy())
2521 if (Copy->getOperand(1).isUndef())
2524 unsigned SrcReg = Copy->getOperand(1).getReg();
2525 unsigned DstReg = Copy->getOperand(0).getReg();
2526 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
2527 || TargetRegisterInfo::isPhysicalRegister(DstReg))
2530 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
2531 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
2534 // Try joining WorkList copies starting from index From.
2535 // Null out any successful joins.
2536 bool RegisterCoalescer::
2537 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2538 bool Progress = false;
2539 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2542 // Skip instruction pointers that have already been erased, for example by
2543 // dead code elimination.
2544 if (ErasedInstrs.erase(CurrList[i])) {
2545 CurrList[i] = nullptr;
2549 bool Success = joinCopy(CurrList[i], Again);
2550 Progress |= Success;
2551 if (Success || !Again)
2552 CurrList[i] = nullptr;
2558 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2559 DEBUG(dbgs() << MBB->getName() << ":\n");
2561 // Collect all copy-like instructions in MBB. Don't start coalescing anything
2562 // yet, it might invalidate the iterator.
2563 const unsigned PrevSize = WorkList.size();
2564 if (JoinGlobalCopies) {
2565 // Coalesce copies bottom-up to coalesce local defs before local uses. They
2566 // are not inherently easier to resolve, but slightly preferable until we
2567 // have local live range splitting. In particular this is required by
2568 // cmp+jmp macro fusion.
2569 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2571 if (!MII->isCopyLike())
2573 if (isLocalCopy(&(*MII), LIS))
2574 LocalWorkList.push_back(&(*MII));
2576 WorkList.push_back(&(*MII));
2580 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2582 if (MII->isCopyLike())
2583 WorkList.push_back(MII);
2585 // Try coalescing the collected copies immediately, and remove the nulls.
2586 // This prevents the WorkList from getting too large since most copies are
2587 // joinable on the first attempt.
2588 MutableArrayRef<MachineInstr*>
2589 CurrList(WorkList.begin() + PrevSize, WorkList.end());
2590 if (copyCoalesceWorkList(CurrList))
2591 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2592 (MachineInstr*)nullptr), WorkList.end());
2595 void RegisterCoalescer::coalesceLocals() {
2596 copyCoalesceWorkList(LocalWorkList);
2597 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2598 if (LocalWorkList[j])
2599 WorkList.push_back(LocalWorkList[j]);
2601 LocalWorkList.clear();
2604 void RegisterCoalescer::joinAllIntervals() {
2605 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2606 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2608 std::vector<MBBPriorityInfo> MBBs;
2609 MBBs.reserve(MF->size());
2610 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2611 MachineBasicBlock *MBB = I;
2612 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2613 JoinSplitEdges && isSplitEdge(MBB)));
2615 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
2617 // Coalesce intervals in MBB priority order.
2618 unsigned CurrDepth = UINT_MAX;
2619 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2620 // Try coalescing the collected local copies for deeper loops.
2621 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
2623 CurrDepth = MBBs[i].Depth;
2625 copyCoalesceInMBB(MBBs[i].MBB);
2629 // Joining intervals can allow other intervals to be joined. Iteratively join
2630 // until we make no progress.
2631 while (copyCoalesceWorkList(WorkList))
2635 void RegisterCoalescer::releaseMemory() {
2636 ErasedInstrs.clear();
2639 InflateRegs.clear();
2642 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2644 MRI = &fn.getRegInfo();
2645 TM = &fn.getTarget();
2646 TRI = TM->getSubtargetImpl()->getRegisterInfo();
2647 TII = TM->getSubtargetImpl()->getInstrInfo();
2648 LIS = &getAnalysis<LiveIntervals>();
2649 AA = &getAnalysis<AliasAnalysis>();
2650 Loops = &getAnalysis<MachineLoopInfo>();
2652 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
2653 if (EnableGlobalCopies == cl::BOU_UNSET)
2654 JoinGlobalCopies = ST.useMachineScheduler();
2656 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2658 // The MachineScheduler does not currently require JoinSplitEdges. This will
2659 // either be enabled unconditionally or replaced by a more general live range
2660 // splitting optimization.
2661 JoinSplitEdges = EnableJoinSplits;
2663 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2664 << "********** Function: " << MF->getName() << '\n');
2666 if (VerifyCoalescing)
2667 MF->verify(this, "Before register coalescing");
2669 RegClassInfo.runOnMachineFunction(fn);
2671 // Join (coalesce) intervals if requested.
2675 // After deleting a lot of copies, register classes may be less constrained.
2676 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2678 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2679 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2681 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2682 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2683 unsigned Reg = InflateRegs[i];
2684 if (MRI->reg_nodbg_empty(Reg))
2686 if (MRI->recomputeRegClass(Reg, *TM)) {
2687 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2688 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
2689 LiveInterval &LI = LIS->getInterval(Reg);
2690 unsigned MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2692 // If the inflated register class does not support subregisters anymore
2693 // remove the subranges.
2694 LI.clearSubRanges();
2696 // If subranges are still supported, then the same subregs should still
2699 for (LiveInterval::SubRange &S : LI.subranges()) {
2700 assert ((S.LaneMask & ~MaxMask) == 0);
2709 if (VerifyCoalescing)
2710 MF->verify(this, "After register coalescing");
2714 /// Implement the dump method.
2715 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {