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 /// @p DestLaneMask are the lanes that @p ToMerge will end up in after the
163 /// merge, @p PrevLaneMask the ones it currently occupies.
164 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
165 unsigned DstLaneMask, unsigned PrevLaneMask,
168 /// Join the liveranges of two subregisters. Joins @p RRange into
169 /// @p LRange, @p RRange may be invalid afterwards.
170 void joinSubRegRanges(LiveRange &LRange, unsigned LMask,
171 LiveRange &RRange, unsigned RMask,
172 const CoalescerPair &CP);
174 /// We found a non-trivially-coalescable copy. If
175 /// the source value number is defined by a copy from the destination reg
176 /// see if we can merge these two destination reg valno# into a single
177 /// value number, eliminating a copy.
178 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
180 /// Return true if there are definitions of IntB
181 /// other than BValNo val# that can reach uses of AValno val# of IntA.
182 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
183 VNInfo *AValNo, VNInfo *BValNo);
185 /// We found a non-trivially-coalescable copy.
186 /// If the source value number is defined by a commutable instruction and
187 /// its other operand is coalesced to the copy dest register, see if we
188 /// can transform the copy into a noop by commuting the definition.
189 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
191 /// If the source of a copy is defined by a
192 /// trivial computation, replace the copy by rematerialize the definition.
193 bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI,
196 /// Return true if a physreg copy should be joined.
197 bool canJoinPhys(const CoalescerPair &CP);
199 /// Replace all defs and uses of SrcReg to DstReg and
200 /// update the subregister number if it is not zero. If DstReg is a
201 /// physical register and the existing subregister number of the def / use
202 /// being updated is not zero, make sure to set it to the correct physical
204 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
206 /// Handle copies of undef values.
207 bool eliminateUndefCopy(MachineInstr *CopyMI);
210 static char ID; // Class identification, replacement for typeinfo
211 RegisterCoalescer() : MachineFunctionPass(ID) {
212 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
215 void getAnalysisUsage(AnalysisUsage &AU) const override;
217 void releaseMemory() override;
219 /// This is the pass entry point.
220 bool runOnMachineFunction(MachineFunction&) override;
222 /// Implement the dump method.
223 void print(raw_ostream &O, const Module* = nullptr) const override;
225 } /// end anonymous namespace
227 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
229 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
230 "Simple Register Coalescing", false, false)
231 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
232 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
233 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
234 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
235 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
236 "Simple Register Coalescing", false, false)
238 char RegisterCoalescer::ID = 0;
240 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
241 unsigned &Src, unsigned &Dst,
242 unsigned &SrcSub, unsigned &DstSub) {
244 Dst = MI->getOperand(0).getReg();
245 DstSub = MI->getOperand(0).getSubReg();
246 Src = MI->getOperand(1).getReg();
247 SrcSub = MI->getOperand(1).getSubReg();
248 } else if (MI->isSubregToReg()) {
249 Dst = MI->getOperand(0).getReg();
250 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
251 MI->getOperand(3).getImm());
252 Src = MI->getOperand(2).getReg();
253 SrcSub = MI->getOperand(2).getSubReg();
259 // Return true if this block should be vacated by the coalescer to eliminate
260 // branches. The important cases to handle in the coalescer are critical edges
261 // split during phi elimination which contain only copies. Simple blocks that
262 // contain non-branches should also be vacated, but this can be handled by an
263 // earlier pass similar to early if-conversion.
264 static bool isSplitEdge(const MachineBasicBlock *MBB) {
265 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
268 for (const auto &MI : *MBB) {
269 if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
275 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
279 Flipped = CrossClass = false;
281 unsigned Src, Dst, SrcSub, DstSub;
282 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
284 Partial = SrcSub || DstSub;
286 // If one register is a physreg, it must be Dst.
287 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
288 if (TargetRegisterInfo::isPhysicalRegister(Dst))
291 std::swap(SrcSub, DstSub);
295 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
297 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
298 // Eliminate DstSub on a physreg.
300 Dst = TRI.getSubReg(Dst, DstSub);
301 if (!Dst) return false;
305 // Eliminate SrcSub by picking a corresponding Dst superregister.
307 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
308 if (!Dst) return false;
309 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
313 // Both registers are virtual.
314 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
315 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
317 // Both registers have subreg indices.
318 if (SrcSub && DstSub) {
319 // Copies between different sub-registers are never coalescable.
320 if (Src == Dst && SrcSub != DstSub)
323 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
328 // SrcReg will be merged with a sub-register of DstReg.
330 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
332 // DstReg will be merged with a sub-register of SrcReg.
334 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
336 // This is a straight copy without sub-registers.
337 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
340 // The combined constraint may be impossible to satisfy.
344 // Prefer SrcReg to be a sub-register of DstReg.
345 // FIXME: Coalescer should support subregs symmetrically.
346 if (DstIdx && !SrcIdx) {
348 std::swap(SrcIdx, DstIdx);
352 CrossClass = NewRC != DstRC || NewRC != SrcRC;
354 // Check our invariants
355 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
356 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
357 "Cannot have a physical SubIdx");
363 bool CoalescerPair::flip() {
364 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
366 std::swap(SrcReg, DstReg);
367 std::swap(SrcIdx, DstIdx);
372 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
375 unsigned Src, Dst, SrcSub, DstSub;
376 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
379 // Find the virtual register that is SrcReg.
382 std::swap(SrcSub, DstSub);
383 } else if (Src != SrcReg) {
387 // Now check that Dst matches DstReg.
388 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
389 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
391 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
392 // DstSub could be set for a physreg from INSERT_SUBREG.
394 Dst = TRI.getSubReg(Dst, DstSub);
397 return DstReg == Dst;
398 // This is a partial register copy. Check that the parts match.
399 return TRI.getSubReg(DstReg, SrcSub) == Dst;
401 // DstReg is virtual.
404 // Registers match, do the subregisters line up?
405 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
406 TRI.composeSubRegIndices(DstIdx, DstSub);
410 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
411 AU.setPreservesCFG();
412 AU.addRequired<AliasAnalysis>();
413 AU.addRequired<LiveIntervals>();
414 AU.addPreserved<LiveIntervals>();
415 AU.addPreserved<SlotIndexes>();
416 AU.addRequired<MachineLoopInfo>();
417 AU.addPreserved<MachineLoopInfo>();
418 AU.addPreservedID(MachineDominatorsID);
419 MachineFunctionPass::getAnalysisUsage(AU);
422 void RegisterCoalescer::eliminateDeadDefs() {
423 SmallVector<unsigned, 8> NewRegs;
424 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
425 nullptr, this).eliminateDeadDefs(DeadDefs);
428 // Callback from eliminateDeadDefs().
429 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
430 // MI may be in WorkList. Make sure we don't visit it.
431 ErasedInstrs.insert(MI);
434 /// We found a non-trivially-coalescable copy with IntA
435 /// being the source and IntB being the dest, thus this defines a value number
436 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
437 /// see if we can merge these two pieces of B into a single value number,
438 /// eliminating a copy. For example:
442 /// B1 = A3 <- this copy
444 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
445 /// value number to be replaced with B0 (which simplifies the B liveinterval).
447 /// This returns true if an interval was modified.
449 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
450 MachineInstr *CopyMI) {
451 assert(!CP.isPartial() && "This doesn't work for partial copies.");
452 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
455 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
457 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
458 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
460 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
461 // the example above.
462 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
463 if (BS == IntB.end()) return false;
464 VNInfo *BValNo = BS->valno;
466 // Get the location that B is defined at. Two options: either this value has
467 // an unknown definition point or it is defined at CopyIdx. If unknown, we
469 if (BValNo->def != CopyIdx) return false;
471 // AValNo is the value number in A that defines the copy, A3 in the example.
472 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
473 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
474 // The live segment might not exist after fun with physreg coalescing.
475 if (AS == IntA.end()) return false;
476 VNInfo *AValNo = AS->valno;
478 // If AValNo is defined as a copy from IntB, we can potentially process this.
479 // Get the instruction that defines this value number.
480 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
481 // Don't allow any partial copies, even if isCoalescable() allows them.
482 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
485 // Get the Segment in IntB that this value number starts with.
486 LiveInterval::iterator ValS =
487 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
488 if (ValS == IntB.end())
491 // Make sure that the end of the live segment is inside the same block as
493 MachineInstr *ValSEndInst =
494 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
495 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
498 // Okay, we now know that ValS ends in the same block that the CopyMI
499 // live-range starts. If there are no intervening live segments between them
500 // in IntB, we can merge them.
501 if (ValS+1 != BS) return false;
503 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
505 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
506 // We are about to delete CopyMI, so need to remove it as the 'instruction
507 // that defines this value #'. Update the valnum with the new defining
509 BValNo->def = FillerStart;
511 // Okay, we can merge them. We need to insert a new liverange:
512 // [ValS.end, BS.begin) of either value number, then we merge the
513 // two value numbers.
514 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
516 // Okay, merge "B1" into the same value number as "B0".
517 if (BValNo != ValS->valno)
518 IntB.MergeValueNumberInto(BValNo, ValS->valno);
520 // Do the same for the subregister segments.
521 for (LiveInterval::SubRange &S : IntB.subranges()) {
522 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
523 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
524 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
525 if (SubBValNo != SubValSNo)
526 S.MergeValueNumberInto(SubBValNo, SubValSNo);
529 DEBUG(dbgs() << " result = " << IntB << '\n');
531 // If the source instruction was killing the source register before the
532 // merge, unset the isKill marker given the live range has been extended.
533 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
535 ValSEndInst->getOperand(UIdx).setIsKill(false);
538 // Rewrite the copy. If the copy instruction was killing the destination
539 // register before the merge, find the last use and trim the live range. That
540 // will also add the isKill marker.
541 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
542 if (AS->end == CopyIdx)
543 LIS->shrinkToUses(&IntA);
549 /// Return true if there are definitions of IntB
550 /// other than BValNo val# that can reach uses of AValno val# of IntA.
551 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
555 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
557 if (LIS->hasPHIKill(IntA, AValNo))
560 for (LiveRange::Segment &ASeg : IntA.segments) {
561 if (ASeg.valno != AValNo) continue;
562 LiveInterval::iterator BI =
563 std::upper_bound(IntB.begin(), IntB.end(), ASeg.start);
564 if (BI != IntB.begin())
566 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
567 if (BI->valno == BValNo)
569 if (BI->start <= ASeg.start && BI->end > ASeg.start)
571 if (BI->start > ASeg.start && BI->start < ASeg.end)
578 /// Copy segements with value number @p SrcValNo from liverange @p Src to live
579 /// range @Dst and use value number @p DstValNo there.
580 static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo,
581 const LiveRange &Src, const VNInfo *SrcValNo)
583 for (const LiveRange::Segment &S : Src.segments) {
584 if (S.valno != SrcValNo)
586 Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo));
590 /// We found a non-trivially-coalescable copy with
591 /// IntA being the source and IntB being the dest, thus this defines a value
592 /// number in IntB. If the source value number (in IntA) is defined by a
593 /// commutable instruction and its other operand is coalesced to the copy dest
594 /// register, see if we can transform the copy into a noop by commuting the
595 /// definition. For example,
597 /// A3 = op A2 B0<kill>
599 /// B1 = A3 <- this copy
601 /// = op A3 <- more uses
605 /// B2 = op B0 A2<kill>
607 /// B1 = B2 <- now an identify copy
609 /// = op B2 <- more uses
611 /// This returns true if an interval was modified.
613 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
614 MachineInstr *CopyMI) {
615 assert (!CP.isPhys());
617 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
620 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
622 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
624 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
625 // the example above.
626 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
627 if (!BValNo || BValNo->def != CopyIdx)
630 // AValNo is the value number in A that defines the copy, A3 in the example.
631 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
632 assert(AValNo && "COPY source not live");
633 if (AValNo->isPHIDef() || AValNo->isUnused())
635 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
638 if (!DefMI->isCommutable())
640 // If DefMI is a two-address instruction then commuting it will change the
641 // destination register.
642 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
643 assert(DefIdx != -1);
645 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
647 unsigned Op1, Op2, NewDstIdx;
648 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
652 else if (Op2 == UseOpIdx)
657 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
658 unsigned NewReg = NewDstMO.getReg();
659 if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
662 // Make sure there are no other definitions of IntB that would reach the
663 // uses which the new definition can reach.
664 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
667 // If some of the uses of IntA.reg is already coalesced away, return false.
668 // It's not possible to determine whether it's safe to perform the coalescing.
669 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
670 MachineInstr *UseMI = MO.getParent();
671 unsigned OpNo = &MO - &UseMI->getOperand(0);
672 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
673 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
674 if (US == IntA.end() || US->valno != AValNo)
676 // If this use is tied to a def, we can't rewrite the register.
677 if (UseMI->isRegTiedToDefOperand(OpNo))
681 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
684 // At this point we have decided that it is legal to do this
685 // transformation. Start by commuting the instruction.
686 MachineBasicBlock *MBB = DefMI->getParent();
687 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
690 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
691 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
692 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
694 if (NewMI != DefMI) {
695 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
696 MachineBasicBlock::iterator Pos = DefMI;
697 MBB->insert(Pos, NewMI);
700 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
701 NewMI->getOperand(OpIdx).setIsKill();
703 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
712 // Update uses of IntA of the specific Val# with IntB.
713 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
714 UE = MRI->use_end(); UI != UE;) {
715 MachineOperand &UseMO = *UI;
716 MachineInstr *UseMI = UseMO.getParent();
718 if (UseMI->isDebugValue()) {
719 // FIXME These don't have an instruction index. Not clear we have enough
720 // info to decide whether to do this replacement or not. For now do it.
721 UseMO.setReg(NewReg);
724 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
725 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
726 if (US == IntA.end() || US->valno != AValNo)
728 // Kill flags are no longer accurate. They are recomputed after RA.
729 UseMO.setIsKill(false);
730 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
731 UseMO.substPhysReg(NewReg, *TRI);
733 UseMO.setReg(NewReg);
736 if (!UseMI->isCopy())
738 if (UseMI->getOperand(0).getReg() != IntB.reg ||
739 UseMI->getOperand(0).getSubReg())
742 // This copy will become a noop. If it's defining a new val#, merge it into
744 SlotIndex DefIdx = UseIdx.getRegSlot();
745 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
748 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
749 assert(DVNI->def == DefIdx);
750 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
751 for (LiveInterval::SubRange &S : IntB.subranges()) {
752 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
755 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
756 S.MergeValueNumberInto(SubBValNo, SubDVNI);
759 ErasedInstrs.insert(UseMI);
760 LIS->RemoveMachineInstrFromMaps(UseMI);
761 UseMI->eraseFromParent();
764 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
766 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
767 if (IntB.hasSubRanges()) {
768 if (!IntA.hasSubRanges()) {
769 unsigned Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
770 IntA.createSubRangeFrom(Allocator, Mask, IntA);
772 SlotIndex AIdx = CopyIdx.getRegSlot(true);
773 for (LiveInterval::SubRange &SA : IntA.subranges()) {
774 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
775 if (ASubValNo == nullptr) {
776 DEBUG(dbgs() << "No A Range at " << AIdx << " with mask "
777 << format("%04X", SA.LaneMask) << "\n");
781 unsigned AMask = SA.LaneMask;
782 for (LiveInterval::SubRange &SB : IntB.subranges()) {
783 unsigned BMask = SB.LaneMask;
784 unsigned Common = BMask & AMask;
788 DEBUG(dbgs() << format("\t\tCopy+Merge %04X into %04X\n", BMask, Common));
789 unsigned BRest = BMask & ~AMask;
790 LiveInterval::SubRange *CommonRange;
793 DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", BRest));
794 // Duplicate SubRange for newly merged common stuff.
795 CommonRange = IntB.createSubRangeFrom(Allocator, Common, SB);
797 // We van reuse the L SubRange.
798 SB.LaneMask = Common;
801 LiveRange RangeCopy(SB, Allocator);
803 VNInfo *BSubValNo = CommonRange->getVNInfoAt(CopyIdx);
804 assert(BSubValNo->def == CopyIdx);
805 BSubValNo->def = ASubValNo->def;
806 addSegmentsWithValNo(*CommonRange, BSubValNo, SA, ASubValNo);
810 DEBUG(dbgs() << format("\t\tNew Lane %04X\n", AMask));
811 LiveRange *NewRange = IntB.createSubRange(Allocator, AMask);
812 VNInfo *BSubValNo = NewRange->getNextValue(CopyIdx, Allocator);
813 addSegmentsWithValNo(*NewRange, BSubValNo, SA, ASubValNo);
815 SA.removeValNo(ASubValNo);
817 } else if (IntA.hasSubRanges()) {
818 SlotIndex AIdx = CopyIdx.getRegSlot(true);
819 for (LiveInterval::SubRange &SA : IntA.subranges()) {
820 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
821 if (ASubValNo == nullptr) {
822 DEBUG(dbgs() << "No A Range at " << AIdx << " with mask "
823 << format("%04X", SA.LaneMask) << "\n");
826 SA.removeValNo(ASubValNo);
830 BValNo->def = AValNo->def;
831 addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
832 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
834 IntA.removeValNo(AValNo);
835 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
840 /// If the source of a copy is defined by a trivial
841 /// computation, replace the copy by rematerialize the definition.
842 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP,
843 MachineInstr *CopyMI,
846 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
847 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
848 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
849 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
850 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
853 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
854 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
855 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
856 assert(ValNo && "CopyMI input register not live");
857 if (ValNo->isPHIDef() || ValNo->isUnused())
859 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
862 if (DefMI->isCopyLike()) {
866 if (!TII->isAsCheapAsAMove(DefMI))
868 if (!TII->isTriviallyReMaterializable(DefMI, AA))
870 bool SawStore = false;
871 if (!DefMI->isSafeToMove(TII, AA, SawStore))
873 const MCInstrDesc &MCID = DefMI->getDesc();
874 if (MCID.getNumDefs() != 1)
876 // Only support subregister destinations when the def is read-undef.
877 MachineOperand &DstOperand = CopyMI->getOperand(0);
878 unsigned CopyDstReg = DstOperand.getReg();
879 if (DstOperand.getSubReg() && !DstOperand.isUndef())
882 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
883 // the register substantially (beyond both source and dest size). This is bad
884 // for performance since it can cascade through a function, introducing many
885 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
886 // around after a few subreg copies).
887 if (SrcIdx && DstIdx)
890 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
891 if (!DefMI->isImplicitDef()) {
892 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
893 unsigned NewDstReg = DstReg;
895 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
896 DefMI->getOperand(0).getSubReg());
898 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
900 // Finally, make sure that the physical subregister that will be
901 // constructed later is permitted for the instruction.
902 if (!DefRC->contains(NewDstReg))
905 // Theoretically, some stack frame reference could exist. Just make sure
906 // it hasn't actually happened.
907 assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
908 "Only expect to deal with virtual or physical registers");
912 MachineBasicBlock *MBB = CopyMI->getParent();
913 MachineBasicBlock::iterator MII =
914 std::next(MachineBasicBlock::iterator(CopyMI));
915 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
916 MachineInstr *NewMI = std::prev(MII);
918 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
919 CopyMI->eraseFromParent();
920 ErasedInstrs.insert(CopyMI);
922 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
923 // We need to remember these so we can add intervals once we insert
924 // NewMI into SlotIndexes.
925 SmallVector<unsigned, 4> NewMIImplDefs;
926 for (unsigned i = NewMI->getDesc().getNumOperands(),
927 e = NewMI->getNumOperands(); i != e; ++i) {
928 MachineOperand &MO = NewMI->getOperand(i);
930 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
931 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
932 NewMIImplDefs.push_back(MO.getReg());
936 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
937 const TargetRegisterClass *NewRC = CP.getNewRC();
938 unsigned NewIdx = NewMI->getOperand(0).getSubReg();
941 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
943 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
945 assert(NewRC && "subreg chosen for remat incompatible with instruction");
946 MRI->setRegClass(DstReg, NewRC);
948 updateRegDefsUses(DstReg, DstReg, DstIdx);
949 NewMI->getOperand(0).setSubReg(NewIdx);
950 } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
951 // The New instruction may be defining a sub-register of what's actually
952 // been asked for. If so it must implicitly define the whole thing.
953 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
954 "Only expect virtual or physical registers in remat");
955 NewMI->getOperand(0).setIsDead(true);
956 NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
960 // Record small dead def live-ranges for all the subregisters
961 // of the destination register.
962 // Otherwise, variables that live through may miss some
963 // interferences, thus creating invalid allocation.
965 // vreg1 = somedef ; vreg1 GR8
966 // vreg2 = remat ; vreg2 GR32
967 // CL = COPY vreg2.sub_8bit
968 // = somedef vreg1 ; vreg1 GR8
970 // vreg1 = somedef ; vreg1 GR8
971 // ECX<def, dead> = remat ; CL<imp-def>
972 // = somedef vreg1 ; vreg1 GR8
973 // vreg1 will see the inteferences with CL but not with CH since
974 // no live-ranges would have been created for ECX.
976 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
977 for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI);
978 Units.isValid(); ++Units)
979 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
980 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
983 if (NewMI->getOperand(0).getSubReg())
984 NewMI->getOperand(0).setIsUndef();
986 // CopyMI may have implicit operands, transfer them over to the newly
987 // rematerialized instruction. And update implicit def interval valnos.
988 for (unsigned i = CopyMI->getDesc().getNumOperands(),
989 e = CopyMI->getNumOperands(); i != e; ++i) {
990 MachineOperand &MO = CopyMI->getOperand(i);
992 assert(MO.isImplicit() && "No explicit operands after implict operands.");
993 // Discard VReg implicit defs.
994 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
995 NewMI->addOperand(MO);
1000 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1001 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
1002 unsigned Reg = NewMIImplDefs[i];
1003 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1004 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1005 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1008 DEBUG(dbgs() << "Remat: " << *NewMI);
1011 // The source interval can become smaller because we removed a use.
1012 LIS->shrinkToUses(&SrcInt, &DeadDefs);
1013 if (!DeadDefs.empty()) {
1014 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1015 // to describe DstReg instead.
1016 for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
1017 MachineInstr *UseMI = UseMO.getParent();
1018 if (UseMI->isDebugValue()) {
1019 UseMO.setReg(DstReg);
1020 DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1023 eliminateDeadDefs();
1029 static void removeUndefValue(LiveRange &LR, SlotIndex At)
1031 VNInfo *VNInfo = LR.getVNInfoAt(At);
1032 assert(VNInfo != nullptr && SlotIndex::isSameInstr(VNInfo->def, At));
1033 LR.removeValNo(VNInfo);
1036 /// ProcessImpicitDefs may leave some copies of <undef>
1037 /// values, it only removes local variables. When we have a copy like:
1039 /// %vreg1 = COPY %vreg2<undef>
1041 /// We delete the copy and remove the corresponding value number from %vreg1.
1042 /// Any uses of that value number are marked as <undef>.
1043 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1044 // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1045 // CoalescerPair may have a new register class with adjusted subreg indices
1047 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1048 isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1050 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
1051 const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1052 // CopyMI is undef iff SrcReg is not live before the instruction.
1053 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1054 unsigned SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1055 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1056 if ((SR.LaneMask & SrcMask) == 0)
1061 } else if (SrcLI.liveAt(Idx))
1064 DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1066 // Remove any DstReg segments starting at the instruction.
1067 LiveInterval &DstLI = LIS->getInterval(DstReg);
1068 unsigned DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1069 SlotIndex RegIndex = Idx.getRegSlot();
1070 for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1071 if ((SR.LaneMask & DstMask) == 0)
1073 removeUndefValue(SR, RegIndex);
1075 DstLI.removeEmptySubRanges();
1077 // Remove value or merge with previous one in case of a subregister def.
1078 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1079 VNInfo *VNInfo = DstLI.getVNInfoAt(RegIndex);
1080 DstLI.MergeValueNumberInto(VNInfo, PrevVNI);
1082 removeUndefValue(DstLI, RegIndex);
1085 // Mark uses as undef.
1086 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1087 if (MO.isDef() /*|| MO.isUndef()*/)
1089 const MachineInstr &MI = *MO.getParent();
1090 SlotIndex UseIdx = LIS->getInstructionIndex(&MI);
1091 unsigned UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1093 if (UseMask != ~0u && DstLI.hasSubRanges()) {
1095 for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1096 if ((SR.LaneMask & UseMask) == 0)
1098 if (SR.liveAt(UseIdx)) {
1104 isLive = DstLI.liveAt(UseIdx);
1107 MO.setIsUndef(true);
1108 DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1113 /// Replace all defs and uses of SrcReg to DstReg and update the subregister
1114 /// number if it is not zero. If DstReg is a physical register and the existing
1115 /// subregister number of the def / use being updated is not zero, make sure to
1116 /// set it to the correct physical subregister.
1117 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
1120 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1121 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1123 SmallPtrSet<MachineInstr*, 8> Visited;
1124 for (MachineRegisterInfo::reg_instr_iterator
1125 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1127 MachineInstr *UseMI = &*(I++);
1129 // Each instruction can only be rewritten once because sub-register
1130 // composition is not always idempotent. When SrcReg != DstReg, rewriting
1131 // the UseMI operands removes them from the SrcReg use-def chain, but when
1132 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1133 // operands mentioning the virtual register.
1134 if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1137 SmallVector<unsigned,8> Ops;
1139 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1141 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1142 // because SrcReg is a sub-register.
1143 if (DstInt && !Reads && SubIdx)
1144 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
1146 // Replace SrcReg with DstReg in all UseMI operands.
1147 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1148 MachineOperand &MO = UseMI->getOperand(Ops[i]);
1150 // Adjust <undef> flags in case of sub-register joins. We don't want to
1151 // turn a full def into a read-modify-write sub-register def and vice
1153 if (SubIdx && MO.isDef())
1154 MO.setIsUndef(!Reads);
1156 // A subreg use of a partially undef (super) register may be a complete
1157 // undef use now and then has to be marked that way.
1158 if (SubIdx != 0 && MO.isUse() && MRI->tracksSubRegLiveness()) {
1159 if (!DstInt->hasSubRanges()) {
1160 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1161 unsigned Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
1162 DstInt->createSubRangeFrom(Allocator, Mask, *DstInt);
1164 unsigned Mask = TRI->getSubRegIndexLaneMask(SubIdx);
1165 bool IsUndef = true;
1166 SlotIndex MIIdx = UseMI->isDebugValue()
1167 ? LIS->getSlotIndexes()->getIndexBefore(UseMI)
1168 : LIS->getInstructionIndex(UseMI);
1169 SlotIndex UseIdx = MIIdx.getRegSlot(true);
1170 for (LiveInterval::SubRange &S : DstInt->subranges()) {
1171 if ((S.LaneMask & Mask) == 0)
1173 if (S.liveAt(UseIdx)) {
1179 MO.setIsUndef(true);
1180 // We found out some subregister use is actually reading an undefined
1181 // value. In some cases the whole vreg has become undefined at this
1182 // point so we have to potentially shrink the main range if the
1183 // use was ending a live segment there.
1184 LiveQueryResult Q = DstInt->Query(MIIdx);
1185 if (Q.valueOut() == nullptr)
1186 ShrinkMainRange = true;
1191 MO.substPhysReg(DstReg, *TRI);
1193 MO.substVirtReg(DstReg, SubIdx, *TRI);
1197 dbgs() << "\t\tupdated: ";
1198 if (!UseMI->isDebugValue())
1199 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
1205 /// Return true if a copy involving a physreg should be joined.
1206 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1207 /// Always join simple intervals that are defined by a single copy from a
1208 /// reserved register. This doesn't increase register pressure, so it is
1209 /// always beneficial.
1210 if (!MRI->isReserved(CP.getDstReg())) {
1211 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1215 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1216 if (CP.isFlipped() && JoinVInt.containsOneValue())
1219 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
1223 /// Attempt to join intervals corresponding to SrcReg/DstReg,
1224 /// which are the src/dst of the copy instruction CopyMI. This returns true
1225 /// if the copy was successfully coalesced away. If it is not currently
1226 /// possible to coalesce this interval, but it may be possible if other
1227 /// things get coalesced, then it returns true by reference in 'Again'.
1228 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1231 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1233 CoalescerPair CP(*TRI);
1234 if (!CP.setRegisters(CopyMI)) {
1235 DEBUG(dbgs() << "\tNot coalescable.\n");
1239 if (CP.getNewRC()) {
1240 auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1241 auto DstRC = MRI->getRegClass(CP.getDstReg());
1242 unsigned SrcIdx = CP.getSrcIdx();
1243 unsigned DstIdx = CP.getDstIdx();
1244 if (CP.isFlipped()) {
1245 std::swap(SrcIdx, DstIdx);
1246 std::swap(SrcRC, DstRC);
1248 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1250 DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
1255 // Dead code elimination. This really should be handled by MachineDCE, but
1256 // sometimes dead copies slip through, and we can't generate invalid live
1258 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1259 DEBUG(dbgs() << "\tCopy is dead.\n");
1260 DeadDefs.push_back(CopyMI);
1261 eliminateDeadDefs();
1265 // Eliminate undefs.
1266 if (!CP.isPhys() && eliminateUndefCopy(CopyMI)) {
1267 LIS->RemoveMachineInstrFromMaps(CopyMI);
1268 CopyMI->eraseFromParent();
1269 return false; // Not coalescable.
1272 // Coalesced copies are normally removed immediately, but transformations
1273 // like removeCopyByCommutingDef() can inadvertently create identity copies.
1274 // When that happens, just join the values and remove the copy.
1275 if (CP.getSrcReg() == CP.getDstReg()) {
1276 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1277 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1278 const SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
1279 LiveQueryResult LRQ = LI.Query(CopyIdx);
1280 if (VNInfo *DefVNI = LRQ.valueDefined()) {
1281 VNInfo *ReadVNI = LRQ.valueIn();
1282 assert(ReadVNI && "No value before copy and no <undef> flag.");
1283 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1284 LI.MergeValueNumberInto(DefVNI, ReadVNI);
1286 // Process subregister liveranges.
1287 for (LiveInterval::SubRange &S : LI.subranges()) {
1288 LiveQueryResult SLRQ = S.Query(CopyIdx);
1289 if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
1290 VNInfo *SReadVNI = SLRQ.valueIn();
1291 S.MergeValueNumberInto(SDefVNI, SReadVNI);
1294 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
1296 LIS->RemoveMachineInstrFromMaps(CopyMI);
1297 CopyMI->eraseFromParent();
1301 // Enforce policies.
1303 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1304 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1306 if (!canJoinPhys(CP)) {
1307 // Before giving up coalescing, if definition of source is defined by
1308 // trivial computation, try rematerializing it.
1310 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1313 Again = true; // May be possible to coalesce later.
1317 // When possible, let DstReg be the larger interval.
1318 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1319 LIS->getInterval(CP.getDstReg()).size())
1323 dbgs() << "\tConsidering merging to "
1324 << TRI->getRegClassName(CP.getNewRC()) << " with ";
1325 if (CP.getDstIdx() && CP.getSrcIdx())
1326 dbgs() << PrintReg(CP.getDstReg()) << " in "
1327 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1328 << PrintReg(CP.getSrcReg()) << " in "
1329 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1331 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1332 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1337 ShrinkMainRange = false;
1339 // Okay, attempt to join these two intervals. On failure, this returns false.
1340 // Otherwise, if one of the intervals being joined is a physreg, this method
1341 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1342 // been modified, so we can use this information below to update aliases.
1343 if (!joinIntervals(CP)) {
1344 // Coalescing failed.
1346 // If definition of source is defined by trivial computation, try
1347 // rematerializing it.
1349 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1352 // If we can eliminate the copy without merging the live segments, do so
1354 if (!CP.isPartial() && !CP.isPhys()) {
1355 if (adjustCopiesBackFrom(CP, CopyMI) ||
1356 removeCopyByCommutingDef(CP, CopyMI)) {
1357 LIS->RemoveMachineInstrFromMaps(CopyMI);
1358 CopyMI->eraseFromParent();
1359 DEBUG(dbgs() << "\tTrivial!\n");
1364 // Otherwise, we are unable to join the intervals.
1365 DEBUG(dbgs() << "\tInterference!\n");
1366 Again = true; // May be possible to coalesce later.
1370 // Coalescing to a virtual register that is of a sub-register class of the
1371 // other. Make sure the resulting register is set to the right register class.
1372 if (CP.isCrossClass()) {
1374 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1377 // Removing sub-register copies can ease the register class constraints.
1378 // Make sure we attempt to inflate the register class of DstReg.
1379 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1380 InflateRegs.push_back(CP.getDstReg());
1382 // CopyMI has been erased by joinIntervals at this point. Remove it from
1383 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1384 // to the work list. This keeps ErasedInstrs from growing needlessly.
1385 ErasedInstrs.erase(CopyMI);
1387 // Rewrite all SrcReg operands to DstReg.
1388 // Also update DstReg operands to include DstIdx if it is set.
1390 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1391 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1393 // Shrink subregister ranges if necessary.
1394 if (ShrinkMask != 0) {
1395 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1396 for (LiveInterval::SubRange &S : LI.subranges()) {
1397 if ((S.LaneMask & ShrinkMask) == 0)
1399 DEBUG(dbgs() << "Shrink LaneUses (Lane "
1400 << format("%04X", S.LaneMask) << ")\n");
1401 LIS->shrinkToUses(S, LI.reg);
1404 if (ShrinkMainRange) {
1405 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1406 LIS->shrinkToUses(&LI);
1409 // SrcReg is guaranteed to be the register whose live interval that is
1411 LIS->removeInterval(CP.getSrcReg());
1413 // Update regalloc hint.
1414 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1417 dbgs() << "\tSuccess: " << PrintReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
1418 << " -> " << PrintReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
1419 dbgs() << "\tResult = ";
1421 dbgs() << PrintReg(CP.getDstReg(), TRI);
1423 dbgs() << LIS->getInterval(CP.getDstReg());
1431 /// Attempt joining with a reserved physreg.
1432 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1433 assert(CP.isPhys() && "Must be a physreg copy");
1434 assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
1435 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1436 DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1438 assert(CP.isFlipped() && RHS.containsOneValue() &&
1439 "Invalid join with reserved register");
1441 // Optimization for reserved registers like ESP. We can only merge with a
1442 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1443 // The live range of the reserved register will look like a set of dead defs
1444 // - we don't properly track the live range of reserved registers.
1446 // Deny any overlapping intervals. This depends on all the reserved
1447 // register live ranges to look like dead defs.
1448 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1449 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1450 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1454 // Skip any value computations, we are not adding new values to the
1455 // reserved register. Also skip merging the live ranges, the reserved
1456 // register live range doesn't need to be accurate as long as all the
1459 // Delete the identity copy.
1460 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1461 LIS->RemoveMachineInstrFromMaps(CopyMI);
1462 CopyMI->eraseFromParent();
1464 // We don't track kills for reserved registers.
1465 MRI->clearKillFlags(CP.getSrcReg());
1470 //===----------------------------------------------------------------------===//
1471 // Interference checking and interval joining
1472 //===----------------------------------------------------------------------===//
1474 // In the easiest case, the two live ranges being joined are disjoint, and
1475 // there is no interference to consider. It is quite common, though, to have
1476 // overlapping live ranges, and we need to check if the interference can be
1479 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1480 // This means that two SSA values overlap if and only if the def of one value
1481 // is contained in the live range of the other value. As a special case, the
1482 // overlapping values can be defined at the same index.
1484 // The interference from an overlapping def can be resolved in these cases:
1486 // 1. Coalescable copies. The value is defined by a copy that would become an
1487 // identity copy after joining SrcReg and DstReg. The copy instruction will
1488 // be removed, and the value will be merged with the source value.
1490 // There can be several copies back and forth, causing many values to be
1491 // merged into one. We compute a list of ultimate values in the joined live
1492 // range as well as a mappings from the old value numbers.
1494 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1495 // predecessors have a live out value. It doesn't cause real interference,
1496 // and can be merged into the value it overlaps. Like a coalescable copy, it
1497 // can be erased after joining.
1499 // 3. Copy of external value. The overlapping def may be a copy of a value that
1500 // is already in the other register. This is like a coalescable copy, but
1501 // the live range of the source register must be trimmed after erasing the
1502 // copy instruction:
1505 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1507 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1508 // defining one lane at a time:
1510 // %dst:ssub0<def,read-undef> = FOO
1512 // %dst:ssub1<def> = COPY %src
1514 // The live range of %src overlaps the %dst value defined by FOO, but
1515 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1516 // which was undef anyway.
1518 // The value mapping is more complicated in this case. The final live range
1519 // will have different value numbers for both FOO and BAR, but there is no
1520 // simple mapping from old to new values. It may even be necessary to add
1523 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1524 // is live, but never read. This can happen because we don't compute
1525 // individual live ranges per lane.
1529 // %dst:ssub1<def> = COPY %src
1531 // This kind of interference is only resolved locally. If the clobbered
1532 // lane value escapes the block, the join is aborted.
1535 /// Track information about values in a single virtual register about to be
1536 /// joined. Objects of this class are always created in pairs - one for each
1537 /// side of the CoalescerPair (or one for each lane of a side of the coalescer
1540 /// Live range we work on.
1542 /// (Main) register we work on.
1545 /// When coalescing a subregister range this is the LaneMask in Reg.
1546 unsigned SubRegMask;
1547 /// This is true when joining sub register ranges, false when joining main
1549 const bool SubRangeJoin;
1550 /// Whether the current LiveInterval tracks subregister liveness.
1551 const bool TrackSubRegLiveness;
1553 // Location of this register in the final joined register.
1554 // Either CP.DstIdx or CP.SrcIdx.
1555 const unsigned SubIdx;
1557 // Values that will be present in the final live range.
1558 SmallVectorImpl<VNInfo*> &NewVNInfo;
1560 const CoalescerPair &CP;
1562 SlotIndexes *Indexes;
1563 const TargetRegisterInfo *TRI;
1565 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1566 // This is suitable for passing to LiveInterval::join().
1567 SmallVector<int, 8> Assignments;
1569 // Conflict resolution for overlapping values.
1570 enum ConflictResolution {
1571 // No overlap, simply keep this value.
1574 // Merge this value into OtherVNI and erase the defining instruction.
1575 // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1579 // Merge this value into OtherVNI but keep the defining instruction.
1580 // This is for the special case where OtherVNI is defined by the same
1584 // Keep this value, and have it replace OtherVNI where possible. This
1585 // complicates value mapping since OtherVNI maps to two different values
1586 // before and after this def.
1587 // Used when clobbering undefined or dead lanes.
1590 // Unresolved conflict. Visit later when all values have been mapped.
1593 // Unresolvable conflict. Abort the join.
1597 // Per-value info for LI. The lane bit masks are all relative to the final
1598 // joined register, so they can be compared directly between SrcReg and
1601 ConflictResolution Resolution;
1603 // Lanes written by this def, 0 for unanalyzed values.
1604 unsigned WriteLanes;
1606 // Lanes with defined values in this register. Other lanes are undef and
1608 unsigned ValidLanes;
1610 // Value in LI being redefined by this def.
1613 // Value in the other live range that overlaps this def, if any.
1616 // Is this value an IMPLICIT_DEF that can be erased?
1618 // IMPLICIT_DEF values should only exist at the end of a basic block that
1619 // is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1620 // safely erased if they are overlapping a live value in the other live
1623 // Weird control flow graphs and incomplete PHI handling in
1624 // ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1625 // longer live ranges. Such IMPLICIT_DEF values should be treated like
1627 bool ErasableImplicitDef;
1629 // True when the live range of this value will be pruned because of an
1630 // overlapping CR_Replace value in the other live range.
1633 // True once Pruned above has been computed.
1634 bool PrunedComputed;
1636 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1637 RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false),
1638 Pruned(false), PrunedComputed(false) {}
1640 bool isAnalyzed() const { return WriteLanes != 0; }
1643 // One entry per value number in LI.
1644 SmallVector<Val, 8> Vals;
1646 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
1647 VNInfo *stripCopies(VNInfo *VNI, unsigned LaneMask, unsigned &Reg) const;
1648 bool valuesIdentical(VNInfo *Val0, VNInfo *Val1, const JoinVals &Other) const;
1649 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1650 void computeAssignment(unsigned ValNo, JoinVals &Other);
1651 bool taintExtent(unsigned, unsigned, JoinVals&,
1652 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1653 bool usesLanes(const MachineInstr *MI, unsigned, unsigned, unsigned) const;
1654 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1657 JoinVals(LiveRange &LR, unsigned Reg, unsigned subIdx,
1658 SmallVectorImpl<VNInfo*> &newVNInfo,
1659 const CoalescerPair &cp, LiveIntervals *lis,
1660 const TargetRegisterInfo *tri, unsigned SubRegMask,
1661 bool SubRangeJoin, bool TrackSubRegLiveness)
1662 : LR(LR), Reg(Reg), SubRegMask(SubRegMask), SubRangeJoin(SubRangeJoin),
1663 TrackSubRegLiveness(TrackSubRegLiveness), SubIdx(subIdx),
1664 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
1665 TRI(tri), Assignments(LR.getNumValNums(), -1),
1666 Vals(LR.getNumValNums())
1669 /// Analyze defs in LR and compute a value mapping in NewVNInfo.
1670 /// Returns false if any conflicts were impossible to resolve.
1671 bool mapValues(JoinVals &Other);
1673 /// Try to resolve conflicts that require all values to be mapped.
1674 /// Returns false if any conflicts were impossible to resolve.
1675 bool resolveConflicts(JoinVals &Other);
1677 /// Prune the live range of values in Other.LR where they would conflict with
1678 /// CR_Replace values in LR. Collect end points for restoring the live range
1680 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
1683 // Removes subranges starting at copies that get removed. This sometimes
1684 // happens when undefined subranges are copied around. These ranges contain
1685 // no usefull information and can be removed.
1686 void pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask);
1688 /// Erase any machine instructions that have been coalesced away.
1689 /// Add erased instructions to ErasedInstrs.
1690 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1691 /// the erased instrs.
1692 void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
1693 SmallVectorImpl<unsigned> &ShrinkRegs);
1695 /// Get the value assignments suitable for passing to LiveInterval::join.
1696 const int *getAssignments() const { return Assignments.data(); }
1698 } // end anonymous namespace
1700 /// Compute the bitmask of lanes actually written by DefMI.
1701 /// Set Redef if there are any partial register definitions that depend on the
1702 /// previous value of the register.
1703 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
1706 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1707 if (!MO->isReg() || MO->getReg() != Reg || !MO->isDef())
1709 L |= TRI->getSubRegIndexLaneMask(
1710 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1717 /// Find the ultimate value that VNI was copied from.
1718 VNInfo *JoinVals::stripCopies(VNInfo *VNI, unsigned LaneMask, unsigned &Reg)
1720 while (!VNI->isPHIDef()) {
1721 SlotIndex Def = VNI->def;
1722 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1723 assert(MI && "No defining instruction");
1724 if (!MI->isFullCopy())
1726 unsigned SrcReg = MI->getOperand(1).getReg();
1727 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1730 const LiveInterval &LI = LIS->getInterval(SrcReg);
1732 // No subrange involved.
1733 if (LaneMask == 0 || !LI.hasSubRanges()) {
1734 LiveQueryResult LRQ = LI.Query(Def);
1735 ValueIn = LRQ.valueIn();
1737 // Query subranges. Pick the first matching one.
1739 for (const LiveInterval::SubRange &S : LI.subranges()) {
1740 if ((S.LaneMask & LaneMask) == 0)
1742 LiveQueryResult LRQ = S.Query(Def);
1743 ValueIn = LRQ.valueIn();
1747 if (ValueIn == nullptr)
1755 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
1756 const JoinVals &Other) const {
1757 unsigned Reg0 = Reg;
1758 VNInfo *Stripped0 = stripCopies(Value0, SubRegMask, Reg0);
1759 unsigned Reg1 = Other.Reg;
1760 VNInfo *Stripped1 = stripCopies(Value1, Other.SubRegMask, Reg1);
1761 if (Stripped0 == Stripped1)
1764 // Special case: when merging subranges one of the ranges is actually a copy,
1765 // so we can't simply compare VNInfos but have to resort to comparing
1766 // position and register of the Def.
1767 return Stripped0->def == Stripped1->def && Reg0 == Reg1;
1770 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1771 /// Return a conflict resolution when possible, but leave the hard cases as
1773 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1774 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1775 /// The recursion always goes upwards in the dominator tree, making loops
1777 JoinVals::ConflictResolution
1778 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1779 Val &V = Vals[ValNo];
1780 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1781 VNInfo *VNI = LR.getValNumInfo(ValNo);
1782 if (VNI->isUnused()) {
1787 // Get the instruction defining this value, compute the lanes written.
1788 const MachineInstr *DefMI = nullptr;
1789 if (VNI->isPHIDef()) {
1790 // Conservatively assume that all lanes in a PHI are valid.
1791 unsigned Lanes = SubRangeJoin ? 1 : TRI->getSubRegIndexLaneMask(SubIdx);
1792 V.ValidLanes = V.WriteLanes = Lanes;
1794 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1795 assert(DefMI != nullptr);
1797 // We don't care about the lanes when joining subregister ranges.
1798 V.ValidLanes = V.WriteLanes = 1;
1801 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1803 // If this is a read-modify-write instruction, there may be more valid
1804 // lanes than the ones written by this instruction.
1805 // This only covers partial redef operands. DefMI may have normal use
1806 // operands reading the register. They don't contribute valid lanes.
1808 // This adds ssub1 to the set of valid lanes in %src:
1810 // %src:ssub1<def> = FOO
1812 // This leaves only ssub1 valid, making any other lanes undef:
1814 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1816 // The <read-undef> flag on the def operand means that old lane values are
1819 V.RedefVNI = LR.Query(VNI->def).valueIn();
1820 assert((TrackSubRegLiveness || V.RedefVNI) &&
1821 "Instruction is reading nonexistent value");
1822 if (V.RedefVNI != nullptr) {
1823 computeAssignment(V.RedefVNI->id, Other);
1824 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1828 // An IMPLICIT_DEF writes undef values.
1829 if (DefMI->isImplicitDef()) {
1830 // We normally expect IMPLICIT_DEF values to be live only until the end
1831 // of their block. If the value is really live longer and gets pruned in
1832 // another block, this flag is cleared again.
1833 V.ErasableImplicitDef = true;
1834 V.ValidLanes &= ~V.WriteLanes;
1839 // Find the value in Other that overlaps VNI->def, if any.
1840 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
1842 // It is possible that both values are defined by the same instruction, or
1843 // the values are PHIs defined in the same block. When that happens, the two
1844 // values should be merged into one, but not into any preceding value.
1845 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1846 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1847 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1849 // One value stays, the other is merged. Keep the earlier one, or the first
1851 if (OtherVNI->def < VNI->def)
1852 Other.computeAssignment(OtherVNI->id, *this);
1853 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1854 // This is an early-clobber def overlapping a live-in value in the other
1855 // register. Not mergeable.
1856 V.OtherVNI = OtherLRQ.valueIn();
1857 return CR_Impossible;
1859 V.OtherVNI = OtherVNI;
1860 Val &OtherV = Other.Vals[OtherVNI->id];
1861 // Keep this value, check for conflicts when analyzing OtherVNI.
1862 if (!OtherV.isAnalyzed())
1864 // Both sides have been analyzed now.
1865 // Allow overlapping PHI values. Any real interference would show up in a
1866 // predecessor, the PHI itself can't introduce any conflicts.
1867 if (VNI->isPHIDef())
1869 if (V.ValidLanes & OtherV.ValidLanes)
1870 // Overlapping lanes can't be resolved.
1871 return CR_Impossible;
1876 // No simultaneous def. Is Other live at the def?
1877 V.OtherVNI = OtherLRQ.valueIn();
1879 // No overlap, no conflict.
1882 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1884 // We have overlapping values, or possibly a kill of Other.
1885 // Recursively compute assignments up the dominator tree.
1886 Other.computeAssignment(V.OtherVNI->id, *this);
1887 Val &OtherV = Other.Vals[V.OtherVNI->id];
1889 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
1890 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
1891 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
1894 // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
1895 // to erase the IMPLICIT_DEF instruction.
1896 if (OtherV.ErasableImplicitDef && DefMI &&
1897 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
1898 DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
1899 << " extends into BB#" << DefMI->getParent()->getNumber()
1900 << ", keeping it.\n");
1901 OtherV.ErasableImplicitDef = false;
1904 // Allow overlapping PHI values. Any real interference would show up in a
1905 // predecessor, the PHI itself can't introduce any conflicts.
1906 if (VNI->isPHIDef())
1909 // Check for simple erasable conflicts.
1910 if (DefMI->isImplicitDef())
1913 // Include the non-conflict where DefMI is a coalescable copy that kills
1914 // OtherVNI. We still want the copy erased and value numbers merged.
1915 if (CP.isCoalescable(DefMI)) {
1916 // Some of the lanes copied from OtherVNI may be undef, making them undef
1918 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1922 // This may not be a real conflict if DefMI simply kills Other and defines
1924 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1927 // Handle the case where VNI and OtherVNI can be proven to be identical:
1929 // %other = COPY %ext
1930 // %this = COPY %ext <-- Erase this copy
1932 if (DefMI->isFullCopy() && !CP.isPartial()
1933 && valuesIdentical(VNI, V.OtherVNI, Other))
1936 // If the lanes written by this instruction were all undef in OtherVNI, it is
1937 // still safe to join the live ranges. This can't be done with a simple value
1938 // mapping, though - OtherVNI will map to multiple values:
1940 // 1 %dst:ssub0 = FOO <-- OtherVNI
1941 // 2 %src = BAR <-- VNI
1942 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
1944 // 5 QUUX %src<kill>
1946 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1947 // handles this complex value mapping.
1948 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1951 // If the other live range is killed by DefMI and the live ranges are still
1952 // overlapping, it must be because we're looking at an early clobber def:
1954 // %dst<def,early-clobber> = ASM %src<kill>
1956 // In this case, it is illegal to merge the two live ranges since the early
1957 // clobber def would clobber %src before it was read.
1958 if (OtherLRQ.isKill()) {
1959 // This case where the def doesn't overlap the kill is handled above.
1960 assert(VNI->def.isEarlyClobber() &&
1961 "Only early clobber defs can overlap a kill");
1962 return CR_Impossible;
1965 // VNI is clobbering live lanes in OtherVNI, but there is still the
1966 // possibility that no instructions actually read the clobbered lanes.
1967 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1968 // Otherwise Other.RI wouldn't be live here.
1969 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1970 return CR_Impossible;
1972 // We need to verify that no instructions are reading the clobbered lanes. To
1973 // save compile time, we'll only check that locally. Don't allow the tainted
1974 // value to escape the basic block.
1975 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1976 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1977 return CR_Impossible;
1979 // There are still some things that could go wrong besides clobbered lanes
1980 // being read, for example OtherVNI may be only partially redefined in MBB,
1981 // and some clobbered lanes could escape the block. Save this analysis for
1982 // resolveConflicts() when all values have been mapped. We need to know
1983 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1984 // that now - the recursive analyzeValue() calls must go upwards in the
1986 return CR_Unresolved;
1989 /// Compute the value assignment for ValNo in RI.
1990 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1992 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1993 Val &V = Vals[ValNo];
1994 if (V.isAnalyzed()) {
1995 // Recursion should always move up the dominator tree, so ValNo is not
1996 // supposed to reappear before it has been assigned.
1997 assert(Assignments[ValNo] != -1 && "Bad recursion?");
2000 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2003 // Merge this ValNo into OtherVNI.
2004 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
2005 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
2006 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2007 DEBUG(dbgs() << "\t\tmerge " << PrintReg(Reg) << ':' << ValNo << '@'
2008 << LR.getValNumInfo(ValNo)->def << " into "
2009 << PrintReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
2010 << V.OtherVNI->def << " --> @"
2011 << NewVNInfo[Assignments[ValNo]]->def << '\n');
2014 case CR_Unresolved: {
2015 // The other value is going to be pruned if this join is successful.
2016 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
2017 Val &OtherV = Other.Vals[V.OtherVNI->id];
2018 // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
2020 if ((OtherV.WriteLanes & ~V.ValidLanes) != 0 && TrackSubRegLiveness)
2021 OtherV.ErasableImplicitDef = false;
2022 OtherV.Pruned = true;
2026 // This value number needs to go in the final joined live range.
2027 Assignments[ValNo] = NewVNInfo.size();
2028 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
2033 bool JoinVals::mapValues(JoinVals &Other) {
2034 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2035 computeAssignment(i, Other);
2036 if (Vals[i].Resolution == CR_Impossible) {
2037 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(Reg) << ':' << i
2038 << '@' << LR.getValNumInfo(i)->def << '\n');
2045 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
2046 /// the extent of the tainted lanes in the block.
2048 /// Multiple values in Other.LR can be affected since partial redefinitions can
2049 /// preserve previously tainted lanes.
2051 /// 1 %dst = VLOAD <-- Define all lanes in %dst
2052 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
2053 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
2054 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
2056 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
2057 /// entry to TaintedVals.
2059 /// Returns false if the tainted lanes extend beyond the basic block.
2061 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
2062 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
2063 VNInfo *VNI = LR.getValNumInfo(ValNo);
2064 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2065 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2067 // Scan Other.LR from VNI.def to MBBEnd.
2068 LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
2069 assert(OtherI != Other.LR.end() && "No conflict?");
2071 // OtherI is pointing to a tainted value. Abort the join if the tainted
2072 // lanes escape the block.
2073 SlotIndex End = OtherI->end;
2074 if (End >= MBBEnd) {
2075 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.Reg) << ':'
2076 << OtherI->valno->id << '@' << OtherI->start << '\n');
2079 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.Reg) << ':'
2080 << OtherI->valno->id << '@' << OtherI->start
2081 << " to " << End << '\n');
2082 // A dead def is not a problem.
2085 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2087 // Check for another def in the MBB.
2088 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2091 // Lanes written by the new def are no longer tainted.
2092 const Val &OV = Other.Vals[OtherI->valno->id];
2093 TaintedLanes &= ~OV.WriteLanes;
2096 } while (TaintedLanes);
2100 /// Return true if MI uses any of the given Lanes from Reg.
2101 /// This does not include partial redefinitions of Reg.
2102 bool JoinVals::usesLanes(const MachineInstr *MI, unsigned Reg, unsigned SubIdx,
2103 unsigned Lanes) const {
2104 if (MI->isDebugValue())
2106 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
2107 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
2109 if (!MO->readsReg())
2111 if (Lanes & TRI->getSubRegIndexLaneMask(
2112 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
2118 bool JoinVals::resolveConflicts(JoinVals &Other) {
2119 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2121 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
2122 if (V.Resolution != CR_Unresolved)
2124 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(Reg) << ':' << i
2125 << '@' << LR.getValNumInfo(i)->def << '\n');
2130 assert(V.OtherVNI && "Inconsistent conflict resolution.");
2131 VNInfo *VNI = LR.getValNumInfo(i);
2132 const Val &OtherV = Other.Vals[V.OtherVNI->id];
2134 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
2135 // join, those lanes will be tainted with a wrong value. Get the extent of
2136 // the tainted lanes.
2137 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2138 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
2139 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2140 // Tainted lanes would extend beyond the basic block.
2143 assert(!TaintExtent.empty() && "There should be at least one conflict.");
2145 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
2146 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2147 MachineBasicBlock::iterator MI = MBB->begin();
2148 if (!VNI->isPHIDef()) {
2149 MI = Indexes->getInstructionFromIndex(VNI->def);
2150 // No need to check the instruction defining VNI for reads.
2153 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
2154 "Interference ends on VNI->def. Should have been handled earlier");
2155 MachineInstr *LastMI =
2156 Indexes->getInstructionFromIndex(TaintExtent.front().first);
2157 assert(LastMI && "Range must end at a proper instruction");
2158 unsigned TaintNum = 0;
2160 assert(MI != MBB->end() && "Bad LastMI");
2161 if (usesLanes(MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2162 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
2165 // LastMI is the last instruction to use the current value.
2166 if (&*MI == LastMI) {
2167 if (++TaintNum == TaintExtent.size())
2169 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
2170 assert(LastMI && "Range must end at a proper instruction");
2171 TaintedLanes = TaintExtent[TaintNum].second;
2176 // The tainted lanes are unused.
2177 V.Resolution = CR_Replace;
2183 // Determine if ValNo is a copy of a value number in LR or Other.LR that will
2187 // %src = COPY %dst <-- This value to be pruned.
2188 // %dst = COPY %src <-- This value is a copy of a pruned value.
2190 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
2191 Val &V = Vals[ValNo];
2192 if (V.Pruned || V.PrunedComputed)
2195 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2198 // Follow copies up the dominator tree and check if any intermediate value
2200 V.PrunedComputed = true;
2201 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
2205 void JoinVals::pruneValues(JoinVals &Other,
2206 SmallVectorImpl<SlotIndex> &EndPoints,
2207 bool changeInstrs) {
2208 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2209 SlotIndex Def = LR.getValNumInfo(i)->def;
2210 switch (Vals[i].Resolution) {
2214 // This value takes precedence over the value in Other.LR.
2215 LIS->pruneValue(Other.LR, Def, &EndPoints);
2216 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
2217 // instructions are only inserted to provide a live-out value for PHI
2218 // predecessors, so the instruction should simply go away once its value
2219 // has been replaced.
2220 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2221 bool EraseImpDef = OtherV.ErasableImplicitDef &&
2222 OtherV.Resolution == CR_Keep;
2223 if (!Def.isBlock()) {
2225 // Remove <def,read-undef> flags. This def is now a partial redef.
2226 // Also remove <def,dead> flags since the joined live range will
2227 // continue past this instruction.
2228 for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
2229 MO.isValid(); ++MO) {
2230 if (MO->isReg() && MO->isDef() && MO->getReg() == Reg) {
2231 MO->setIsUndef(EraseImpDef);
2232 MO->setIsDead(false);
2236 // This value will reach instructions below, but we need to make sure
2237 // the live range also reaches the instruction at Def.
2239 EndPoints.push_back(Def);
2241 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.Reg) << " at " << Def
2242 << ": " << Other.LR << '\n');
2247 if (isPrunedValue(i, Other)) {
2248 // This value is ultimately a copy of a pruned value in LR or Other.LR.
2249 // We can no longer trust the value mapping computed by
2250 // computeAssignment(), the value that was originally copied could have
2252 LIS->pruneValue(LR, Def, &EndPoints);
2253 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(Reg) << " at "
2254 << Def << ": " << LR << '\n');
2259 llvm_unreachable("Unresolved conflicts");
2264 void JoinVals::pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask)
2266 // Look for values being erased.
2267 bool DidPrune = false;
2268 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2269 if (Vals[i].Resolution != CR_Erase)
2272 // Check subranges at the point where the copy will be removed.
2273 SlotIndex Def = LR.getValNumInfo(i)->def;
2274 for (LiveInterval::SubRange &S : LI.subranges()) {
2275 LiveQueryResult Q = S.Query(Def);
2277 // If a subrange starts at the copy then an undefined value has been
2278 // copied and we must remove that subrange value as well.
2279 VNInfo *ValueOut = Q.valueOutOrDead();
2280 if (ValueOut != nullptr && Q.valueIn() == nullptr) {
2281 DEBUG(dbgs() << "\t\tPrune sublane " << format("%04X", S.LaneMask)
2282 << " at " << Def << "\n");
2283 LIS->pruneValue(S, Def, nullptr);
2285 // Mark value number as unused.
2286 ValueOut->markUnused();
2289 // If a subrange ends at the copy, then a value was copied but only
2290 // partially used later. Shrink the subregister range apropriately.
2291 if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
2292 DEBUG(dbgs() << "\t\tDead uses at sublane "
2293 << format("%04X", S.LaneMask) << " at " << Def << "\n");
2294 ShrinkMask |= S.LaneMask;
2299 LI.removeEmptySubRanges();
2302 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2303 SmallVectorImpl<unsigned> &ShrinkRegs) {
2304 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2305 // Get the def location before markUnused() below invalidates it.
2306 SlotIndex Def = LR.getValNumInfo(i)->def;
2307 switch (Vals[i].Resolution) {
2309 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
2310 // longer. The IMPLICIT_DEF instructions are only inserted by
2311 // PHIElimination to guarantee that all PHI predecessors have a value.
2312 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
2314 // Remove value number i from LR. Note that this VNInfo is still present
2315 // in NewVNInfo, so it will appear as an unused value number in the final
2317 LR.getValNumInfo(i)->markUnused();
2318 LR.removeValNo(LR.getValNumInfo(i));
2319 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n');
2323 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2324 assert(MI && "No instruction to erase");
2326 unsigned Reg = MI->getOperand(1).getReg();
2327 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
2328 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
2329 ShrinkRegs.push_back(Reg);
2331 ErasedInstrs.insert(MI);
2332 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
2333 LIS->RemoveMachineInstrFromMaps(MI);
2334 MI->eraseFromParent();
2343 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, unsigned LMask,
2344 LiveRange &RRange, unsigned RMask,
2345 const CoalescerPair &CP) {
2346 SmallVector<VNInfo*, 16> NewVNInfo;
2347 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(),
2348 NewVNInfo, CP, LIS, TRI, LMask, true, true);
2349 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(),
2350 NewVNInfo, CP, LIS, TRI, RMask, true, true);
2352 /// Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
2353 /// Conflicts should already be resolved so the mapping/resolution should
2355 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2356 llvm_unreachable("Can't join subrange although main ranges are compatible");
2357 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2358 llvm_unreachable("Can't join subrange although main ranges are compatible");
2360 // The merging algorithm in LiveInterval::join() can't handle conflicting
2361 // value mappings, so we need to remove any live ranges that overlap a
2362 // CR_Replace resolution. Collect a set of end points that can be used to
2363 // restore the live range after joining.
2364 SmallVector<SlotIndex, 8> EndPoints;
2365 LHSVals.pruneValues(RHSVals, EndPoints, false);
2366 RHSVals.pruneValues(LHSVals, EndPoints, false);
2371 // Join RRange into LHS.
2372 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
2375 DEBUG(dbgs() << "\t\tjoined lanes: " << LRange << "\n");
2376 if (EndPoints.empty())
2379 // Recompute the parts of the live range we had to remove because of
2380 // CR_Replace conflicts.
2381 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2382 << " points: " << LRange << '\n');
2383 LIS->extendToIndices(LRange, EndPoints);
2386 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
2387 const LiveRange &ToMerge,
2388 unsigned DstLaneMask,
2389 unsigned PrevLaneMask,
2390 CoalescerPair &CP) {
2391 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2392 for (LiveInterval::SubRange &R : LI.subranges()) {
2393 unsigned RMask = R.LaneMask;
2394 // LaneMask of subregisters common to subrange R and ToMerge.
2395 unsigned Common = RMask & DstLaneMask;
2396 // There is nothing to do without common subregs.
2400 DEBUG(dbgs() << format("\t\tCopy+Merge %04X into %04X\n", RMask, Common));
2401 // LaneMask of subregisters contained in the R range but not in ToMerge,
2402 // they have to split into their own subrange.
2403 unsigned LRest = RMask & ~DstLaneMask;
2404 LiveInterval::SubRange *CommonRange;
2407 DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", LRest));
2408 // Duplicate SubRange for newly merged common stuff.
2409 CommonRange = LI.createSubRangeFrom(Allocator, Common, R);
2411 // Reuse the existing range.
2412 R.LaneMask = Common;
2415 LiveRange RangeCopy(ToMerge, Allocator);
2416 joinSubRegRanges(*CommonRange, CommonRange->LaneMask, RangeCopy,
2418 DstLaneMask &= ~RMask;
2421 if (DstLaneMask != 0) {
2422 DEBUG(dbgs() << format("\t\tNew Lane %04X\n", DstLaneMask));
2423 LI.createSubRangeFrom(Allocator, DstLaneMask, ToMerge);
2427 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
2428 SmallVector<VNInfo*, 16> NewVNInfo;
2429 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
2430 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
2431 bool TrackSubRegLiveness = MRI->tracksSubRegLiveness();
2432 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI,
2433 0, false, TrackSubRegLiveness);
2434 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), NewVNInfo, CP, LIS, TRI,
2435 0, false, TrackSubRegLiveness);
2437 DEBUG(dbgs() << "\t\tRHS = " << RHS
2438 << "\n\t\tLHS = " << LHS
2441 // First compute NewVNInfo and the simple value mappings.
2442 // Detect impossible conflicts early.
2443 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2446 // Some conflicts can only be resolved after all values have been mapped.
2447 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2450 // All clear, the live ranges can be merged.
2451 if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
2452 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2453 unsigned DstIdx = CP.getDstIdx();
2454 if (!LHS.hasSubRanges()) {
2455 unsigned Mask = CP.getNewRC()->getLaneMask();
2456 unsigned DstMask = TRI->composeSubRegIndexLaneMask(DstIdx, Mask);
2457 // LHS must support subregs or we wouldn't be in this codepath.
2458 assert(DstMask != 0);
2459 LHS.createSubRangeFrom(Allocator, DstMask, LHS);
2460 DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
2461 << ' ' << LHS << '\n');
2462 } else if (DstIdx != 0) {
2463 // Transform LHS lanemasks to new register class if necessary.
2464 for (LiveInterval::SubRange &R : LHS.subranges()) {
2465 unsigned DstMask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
2466 R.LaneMask = DstMask;
2468 DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
2469 << ' ' << LHS << '\n');
2472 unsigned SrcIdx = CP.getSrcIdx();
2473 if (!RHS.hasSubRanges()) {
2474 unsigned Mask = SrcIdx != 0
2475 ? TRI->getSubRegIndexLaneMask(SrcIdx)
2476 : MRI->getMaxLaneMaskForVReg(LHS.reg);
2478 DEBUG(dbgs() << "\t\tRHS Mask: "
2479 << format("%04X", Mask) << "\n");
2480 mergeSubRangeInto(LHS, RHS, Mask, 0, CP);
2482 // Pair up subranges and merge.
2483 for (LiveInterval::SubRange &R : RHS.subranges()) {
2484 unsigned RMask = R.LaneMask;
2486 // Transform LaneMask of RHS subranges to the ones on LHS.
2487 RMask = TRI->composeSubRegIndexLaneMask(SrcIdx, RMask);
2488 DEBUG(dbgs() << "\t\tTransform RHS Mask "
2489 << format("%04X", R.LaneMask) << " to subreg "
2490 << TRI->getSubRegIndexName(SrcIdx)
2491 << " => " << format("%04X", RMask) << "\n");
2494 mergeSubRangeInto(LHS, R, RMask, R.LaneMask, CP);
2498 DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
2500 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
2501 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
2504 // The merging algorithm in LiveInterval::join() can't handle conflicting
2505 // value mappings, so we need to remove any live ranges that overlap a
2506 // CR_Replace resolution. Collect a set of end points that can be used to
2507 // restore the live range after joining.
2508 SmallVector<SlotIndex, 8> EndPoints;
2509 LHSVals.pruneValues(RHSVals, EndPoints, true);
2510 RHSVals.pruneValues(LHSVals, EndPoints, true);
2512 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
2513 // registers to require trimming.
2514 SmallVector<unsigned, 8> ShrinkRegs;
2515 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2516 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2517 while (!ShrinkRegs.empty())
2518 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
2520 // Join RHS into LHS.
2521 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
2523 // Kill flags are going to be wrong if the live ranges were overlapping.
2524 // Eventually, we should simply clear all kill flags when computing live
2525 // ranges. They are reinserted after register allocation.
2526 MRI->clearKillFlags(LHS.reg);
2527 MRI->clearKillFlags(RHS.reg);
2529 if (!EndPoints.empty()) {
2530 // Recompute the parts of the live range we had to remove because of
2531 // CR_Replace conflicts.
2532 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2533 << " points: " << LHS << '\n');
2534 LIS->extendToIndices((LiveRange&)LHS, EndPoints);
2540 /// Attempt to join these two intervals. On failure, this returns false.
2541 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
2542 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
2546 // Information concerning MBB coalescing priority.
2547 struct MBBPriorityInfo {
2548 MachineBasicBlock *MBB;
2552 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
2553 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
2557 // C-style comparator that sorts first based on the loop depth of the basic
2558 // block (the unsigned), and then on the MBB number.
2560 // EnableGlobalCopies assumes that the primary sort key is loop depth.
2561 static int compareMBBPriority(const MBBPriorityInfo *LHS,
2562 const MBBPriorityInfo *RHS) {
2563 // Deeper loops first
2564 if (LHS->Depth != RHS->Depth)
2565 return LHS->Depth > RHS->Depth ? -1 : 1;
2567 // Try to unsplit critical edges next.
2568 if (LHS->IsSplit != RHS->IsSplit)
2569 return LHS->IsSplit ? -1 : 1;
2571 // Prefer blocks that are more connected in the CFG. This takes care of
2572 // the most difficult copies first while intervals are short.
2573 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
2574 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
2576 return cl > cr ? -1 : 1;
2578 // As a last resort, sort by block number.
2579 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
2582 /// \returns true if the given copy uses or defines a local live range.
2583 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
2584 if (!Copy->isCopy())
2587 if (Copy->getOperand(1).isUndef())
2590 unsigned SrcReg = Copy->getOperand(1).getReg();
2591 unsigned DstReg = Copy->getOperand(0).getReg();
2592 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
2593 || TargetRegisterInfo::isPhysicalRegister(DstReg))
2596 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
2597 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
2600 // Try joining WorkList copies starting from index From.
2601 // Null out any successful joins.
2602 bool RegisterCoalescer::
2603 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2604 bool Progress = false;
2605 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2608 // Skip instruction pointers that have already been erased, for example by
2609 // dead code elimination.
2610 if (ErasedInstrs.erase(CurrList[i])) {
2611 CurrList[i] = nullptr;
2615 bool Success = joinCopy(CurrList[i], Again);
2616 Progress |= Success;
2617 if (Success || !Again)
2618 CurrList[i] = nullptr;
2624 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2625 DEBUG(dbgs() << MBB->getName() << ":\n");
2627 // Collect all copy-like instructions in MBB. Don't start coalescing anything
2628 // yet, it might invalidate the iterator.
2629 const unsigned PrevSize = WorkList.size();
2630 if (JoinGlobalCopies) {
2631 // Coalesce copies bottom-up to coalesce local defs before local uses. They
2632 // are not inherently easier to resolve, but slightly preferable until we
2633 // have local live range splitting. In particular this is required by
2634 // cmp+jmp macro fusion.
2635 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2637 if (!MII->isCopyLike())
2639 if (isLocalCopy(&(*MII), LIS))
2640 LocalWorkList.push_back(&(*MII));
2642 WorkList.push_back(&(*MII));
2646 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2648 if (MII->isCopyLike())
2649 WorkList.push_back(MII);
2651 // Try coalescing the collected copies immediately, and remove the nulls.
2652 // This prevents the WorkList from getting too large since most copies are
2653 // joinable on the first attempt.
2654 MutableArrayRef<MachineInstr*>
2655 CurrList(WorkList.begin() + PrevSize, WorkList.end());
2656 if (copyCoalesceWorkList(CurrList))
2657 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2658 (MachineInstr*)nullptr), WorkList.end());
2661 void RegisterCoalescer::coalesceLocals() {
2662 copyCoalesceWorkList(LocalWorkList);
2663 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2664 if (LocalWorkList[j])
2665 WorkList.push_back(LocalWorkList[j]);
2667 LocalWorkList.clear();
2670 void RegisterCoalescer::joinAllIntervals() {
2671 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2672 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2674 std::vector<MBBPriorityInfo> MBBs;
2675 MBBs.reserve(MF->size());
2676 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2677 MachineBasicBlock *MBB = I;
2678 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2679 JoinSplitEdges && isSplitEdge(MBB)));
2681 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
2683 // Coalesce intervals in MBB priority order.
2684 unsigned CurrDepth = UINT_MAX;
2685 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2686 // Try coalescing the collected local copies for deeper loops.
2687 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
2689 CurrDepth = MBBs[i].Depth;
2691 copyCoalesceInMBB(MBBs[i].MBB);
2695 // Joining intervals can allow other intervals to be joined. Iteratively join
2696 // until we make no progress.
2697 while (copyCoalesceWorkList(WorkList))
2701 void RegisterCoalescer::releaseMemory() {
2702 ErasedInstrs.clear();
2705 InflateRegs.clear();
2708 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2710 MRI = &fn.getRegInfo();
2711 TM = &fn.getTarget();
2712 TRI = TM->getSubtargetImpl()->getRegisterInfo();
2713 TII = TM->getSubtargetImpl()->getInstrInfo();
2714 LIS = &getAnalysis<LiveIntervals>();
2715 AA = &getAnalysis<AliasAnalysis>();
2716 Loops = &getAnalysis<MachineLoopInfo>();
2718 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
2719 if (EnableGlobalCopies == cl::BOU_UNSET)
2720 JoinGlobalCopies = ST.useMachineScheduler();
2722 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2724 // The MachineScheduler does not currently require JoinSplitEdges. This will
2725 // either be enabled unconditionally or replaced by a more general live range
2726 // splitting optimization.
2727 JoinSplitEdges = EnableJoinSplits;
2729 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2730 << "********** Function: " << MF->getName() << '\n');
2732 if (VerifyCoalescing)
2733 MF->verify(this, "Before register coalescing");
2735 RegClassInfo.runOnMachineFunction(fn);
2737 // Join (coalesce) intervals if requested.
2741 // After deleting a lot of copies, register classes may be less constrained.
2742 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2744 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2745 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2747 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2748 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2749 unsigned Reg = InflateRegs[i];
2750 if (MRI->reg_nodbg_empty(Reg))
2752 if (MRI->recomputeRegClass(Reg, *TM)) {
2753 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2754 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
2755 LiveInterval &LI = LIS->getInterval(Reg);
2756 unsigned MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2758 // If the inflated register class does not support subregisters anymore
2759 // remove the subranges.
2760 LI.clearSubRanges();
2762 // If subranges are still supported, then the same subregs should still
2765 for (LiveInterval::SubRange &S : LI.subranges()) {
2766 assert ((S.LaneMask & ~MaxMask) == 0);
2775 if (VerifyCoalescing)
2776 MF->verify(this, "After register coalescing");
2780 /// Implement the dump method.
2781 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {