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/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
44 #define DEBUG_TYPE "regalloc"
46 STATISTIC(numJoins , "Number of interval joins performed");
47 STATISTIC(numCrossRCs , "Number of cross class joins performed");
48 STATISTIC(numCommutes , "Number of instruction commuting performed");
49 STATISTIC(numExtends , "Number of copies extended");
50 STATISTIC(NumReMats , "Number of instructions re-materialized");
51 STATISTIC(NumInflated , "Number of register classes inflated");
52 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
53 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
56 EnableJoining("join-liveintervals",
57 cl::desc("Coalesce copies (default=true)"),
60 static cl::opt<bool> UseTerminalRule("terminal-rule",
61 cl::desc("Apply the terminal rule"),
62 cl::init(false), cl::Hidden);
64 /// Temporary flag to test critical edge unsplitting.
66 EnableJoinSplits("join-splitedges",
67 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
69 /// Temporary flag to test global copy optimization.
70 static cl::opt<cl::boolOrDefault>
71 EnableGlobalCopies("join-globalcopies",
72 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
73 cl::init(cl::BOU_UNSET), cl::Hidden);
76 VerifyCoalescing("verify-coalescing",
77 cl::desc("Verify machine instrs before and after register coalescing"),
81 class RegisterCoalescer : public MachineFunctionPass,
82 private LiveRangeEdit::Delegate {
84 MachineRegisterInfo* MRI;
85 const TargetMachine* TM;
86 const TargetRegisterInfo* TRI;
87 const TargetInstrInfo* TII;
89 const MachineLoopInfo* Loops;
91 RegisterClassInfo RegClassInfo;
93 /// A LaneMask to remember on which subregister live ranges we need to call
94 /// shrinkToUses() later.
95 LaneBitmask ShrinkMask;
97 /// True if the main range of the currently coalesced intervals should be
98 /// checked for smaller live intervals.
101 /// \brief True if the coalescer should aggressively coalesce global copies
102 /// in favor of keeping local copies.
103 bool JoinGlobalCopies;
105 /// \brief True if the coalescer should aggressively coalesce fall-thru
106 /// blocks exclusively containing copies.
109 /// Copy instructions yet to be coalesced.
110 SmallVector<MachineInstr*, 8> WorkList;
111 SmallVector<MachineInstr*, 8> LocalWorkList;
113 /// Set of instruction pointers that have been erased, and
114 /// that may be present in WorkList.
115 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
117 /// Dead instructions that are about to be deleted.
118 SmallVector<MachineInstr*, 8> DeadDefs;
120 /// Virtual registers to be considered for register class inflation.
121 SmallVector<unsigned, 8> InflateRegs;
123 /// Recursively eliminate dead defs in DeadDefs.
124 void eliminateDeadDefs();
126 /// LiveRangeEdit callback for eliminateDeadDefs().
127 void LRE_WillEraseInstruction(MachineInstr *MI) override;
129 /// Coalesce the LocalWorkList.
130 void coalesceLocals();
132 /// Join compatible live intervals
133 void joinAllIntervals();
135 /// Coalesce copies in the specified MBB, putting
136 /// copies that cannot yet be coalesced into WorkList.
137 void copyCoalesceInMBB(MachineBasicBlock *MBB);
139 /// Tries to coalesce all copies in CurrList. Returns true if any progress
141 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
143 /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
144 /// src/dst of the copy instruction CopyMI. This returns true if the copy
145 /// was successfully coalesced away. If it is not currently possible to
146 /// coalesce this interval, but it may be possible if other things get
147 /// coalesced, then it returns true by reference in 'Again'.
148 bool joinCopy(MachineInstr *TheCopy, bool &Again);
150 /// Attempt to join these two intervals. On failure, this
151 /// returns false. The output "SrcInt" will not have been modified, so we
152 /// can use this information below to update aliases.
153 bool joinIntervals(CoalescerPair &CP);
155 /// Attempt joining two virtual registers. Return true on success.
156 bool joinVirtRegs(CoalescerPair &CP);
158 /// Attempt joining with a reserved physreg.
159 bool joinReservedPhysReg(CoalescerPair &CP);
161 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
162 /// Subranges in @p LI which only partially interfere with the desired
163 /// LaneMask are split as necessary. @p LaneMask are the lanes that
164 /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
165 /// lanemasks already adjusted to the coalesced register.
166 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
167 LaneBitmask LaneMask, CoalescerPair &CP);
169 /// Join the liveranges of two subregisters. Joins @p RRange into
170 /// @p LRange, @p RRange may be invalid afterwards.
171 void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
172 LaneBitmask LaneMask, const CoalescerPair &CP);
174 /// We found a non-trivially-coalescable copy. If the source value number is
175 /// defined by a copy from the destination reg see if we can merge these two
176 /// destination reg valno# into a single value number, eliminating a copy.
177 /// This returns true if an interval was modified.
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 /// This returns true if an interval was modified.
190 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
192 /// If the source of a copy is defined by a
193 /// trivial computation, replace the copy by rematerialize the definition.
194 bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI,
197 /// Return true if a copy involving a physreg should be joined.
198 bool canJoinPhys(const CoalescerPair &CP);
200 /// Replace all defs and uses of SrcReg to DstReg and update the subregister
201 /// number if it is not zero. If DstReg is a physical register and the
202 /// existing subregister number of the def / use being updated is not zero,
203 /// make sure to set it to the correct physical subregister.
204 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
206 /// Handle copies of undef values.
207 /// Returns true if @p CopyMI was a copy of an undef value and eliminated.
208 bool eliminateUndefCopy(MachineInstr *CopyMI);
210 /// Check whether or not we should apply the terminal rule on the
211 /// destination (Dst) of \p Copy.
212 /// When the terminal rule applies, Copy is not profitable to
214 /// Dst is terminal if it has exactly one affinity (Dst, Src) and
215 /// at least one interference (Dst, Dst2). If Dst is terminal, the
216 /// terminal rule consists in checking that at least one of
217 /// interfering node, say Dst2, has an affinity of equal or greater
219 /// In that case, Dst2 and Dst will not be able to be both coalesced
220 /// with Src. Since Dst2 exposes more coalescing opportunities than
221 /// Dst, we can drop \p Copy.
222 bool applyTerminalRule(const MachineInstr &Copy) const;
224 /// Wrapper method for \see LiveIntervals::shrinkToUses.
225 /// This method does the proper fixing of the live-ranges when the afore
226 /// mentioned method returns true.
227 void shrinkToUses(LiveInterval *LI,
228 SmallVectorImpl<MachineInstr * > *Dead = nullptr) {
229 if (LIS->shrinkToUses(LI, Dead)) {
230 /// Check whether or not \p LI is composed by multiple connected
231 /// components and if that is the case, fix that.
232 SmallVector<LiveInterval*, 8> SplitLIs;
233 LIS->splitSeparateComponents(*LI, SplitLIs);
238 static char ID; ///< Class identification, replacement for typeinfo
239 RegisterCoalescer() : MachineFunctionPass(ID) {
240 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
243 void getAnalysisUsage(AnalysisUsage &AU) const override;
245 void releaseMemory() override;
247 /// This is the pass entry point.
248 bool runOnMachineFunction(MachineFunction&) override;
250 /// Implement the dump method.
251 void print(raw_ostream &O, const Module* = nullptr) const override;
253 } // end anonymous namespace
255 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
257 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
258 "Simple Register Coalescing", false, false)
259 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
260 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
261 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
262 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
263 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
264 "Simple Register Coalescing", false, false)
266 char RegisterCoalescer::ID = 0;
268 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
269 unsigned &Src, unsigned &Dst,
270 unsigned &SrcSub, unsigned &DstSub) {
272 Dst = MI->getOperand(0).getReg();
273 DstSub = MI->getOperand(0).getSubReg();
274 Src = MI->getOperand(1).getReg();
275 SrcSub = MI->getOperand(1).getSubReg();
276 } else if (MI->isSubregToReg()) {
277 Dst = MI->getOperand(0).getReg();
278 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
279 MI->getOperand(3).getImm());
280 Src = MI->getOperand(2).getReg();
281 SrcSub = MI->getOperand(2).getSubReg();
287 /// Return true if this block should be vacated by the coalescer to eliminate
288 /// branches. The important cases to handle in the coalescer are critical edges
289 /// split during phi elimination which contain only copies. Simple blocks that
290 /// contain non-branches should also be vacated, but this can be handled by an
291 /// earlier pass similar to early if-conversion.
292 static bool isSplitEdge(const MachineBasicBlock *MBB) {
293 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
296 for (const auto &MI : *MBB) {
297 if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
303 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
307 Flipped = CrossClass = false;
309 unsigned Src, Dst, SrcSub, DstSub;
310 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
312 Partial = SrcSub || DstSub;
314 // If one register is a physreg, it must be Dst.
315 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
316 if (TargetRegisterInfo::isPhysicalRegister(Dst))
319 std::swap(SrcSub, DstSub);
323 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
325 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
326 // Eliminate DstSub on a physreg.
328 Dst = TRI.getSubReg(Dst, DstSub);
329 if (!Dst) return false;
333 // Eliminate SrcSub by picking a corresponding Dst superregister.
335 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
336 if (!Dst) return false;
337 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
341 // Both registers are virtual.
342 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
343 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
345 // Both registers have subreg indices.
346 if (SrcSub && DstSub) {
347 // Copies between different sub-registers are never coalescable.
348 if (Src == Dst && SrcSub != DstSub)
351 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
356 // SrcReg will be merged with a sub-register of DstReg.
358 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
360 // DstReg will be merged with a sub-register of SrcReg.
362 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
364 // This is a straight copy without sub-registers.
365 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
368 // The combined constraint may be impossible to satisfy.
372 // Prefer SrcReg to be a sub-register of DstReg.
373 // FIXME: Coalescer should support subregs symmetrically.
374 if (DstIdx && !SrcIdx) {
376 std::swap(SrcIdx, DstIdx);
380 CrossClass = NewRC != DstRC || NewRC != SrcRC;
382 // Check our invariants
383 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
384 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
385 "Cannot have a physical SubIdx");
391 bool CoalescerPair::flip() {
392 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
394 std::swap(SrcReg, DstReg);
395 std::swap(SrcIdx, DstIdx);
400 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
403 unsigned Src, Dst, SrcSub, DstSub;
404 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
407 // Find the virtual register that is SrcReg.
410 std::swap(SrcSub, DstSub);
411 } else if (Src != SrcReg) {
415 // Now check that Dst matches DstReg.
416 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
417 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
419 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
420 // DstSub could be set for a physreg from INSERT_SUBREG.
422 Dst = TRI.getSubReg(Dst, DstSub);
425 return DstReg == Dst;
426 // This is a partial register copy. Check that the parts match.
427 return TRI.getSubReg(DstReg, SrcSub) == Dst;
429 // DstReg is virtual.
432 // Registers match, do the subregisters line up?
433 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
434 TRI.composeSubRegIndices(DstIdx, DstSub);
438 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
439 AU.setPreservesCFG();
440 AU.addRequired<AAResultsWrapperPass>();
441 AU.addRequired<LiveIntervals>();
442 AU.addPreserved<LiveIntervals>();
443 AU.addPreserved<SlotIndexes>();
444 AU.addRequired<MachineLoopInfo>();
445 AU.addPreserved<MachineLoopInfo>();
446 AU.addPreservedID(MachineDominatorsID);
447 MachineFunctionPass::getAnalysisUsage(AU);
450 void RegisterCoalescer::eliminateDeadDefs() {
451 SmallVector<unsigned, 8> NewRegs;
452 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
453 nullptr, this).eliminateDeadDefs(DeadDefs);
456 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
457 // MI may be in WorkList. Make sure we don't visit it.
458 ErasedInstrs.insert(MI);
461 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
462 MachineInstr *CopyMI) {
463 assert(!CP.isPartial() && "This doesn't work for partial copies.");
464 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
467 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
469 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
470 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
472 // We have a non-trivially-coalescable copy with IntA being the source and
473 // IntB being the dest, thus this defines a value number in IntB. If the
474 // source value number (in IntA) is defined by a copy from B, see if we can
475 // merge these two pieces of B into a single value number, eliminating a copy.
480 // B1 = A3 <- this copy
482 // In this case, B0 can be extended to where the B1 copy lives, allowing the
483 // B1 value number to be replaced with B0 (which simplifies the B
486 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
487 // the example above.
488 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
489 if (BS == IntB.end()) return false;
490 VNInfo *BValNo = BS->valno;
492 // Get the location that B is defined at. Two options: either this value has
493 // an unknown definition point or it is defined at CopyIdx. If unknown, we
495 if (BValNo->def != CopyIdx) return false;
497 // AValNo is the value number in A that defines the copy, A3 in the example.
498 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
499 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
500 // The live segment might not exist after fun with physreg coalescing.
501 if (AS == IntA.end()) return false;
502 VNInfo *AValNo = AS->valno;
504 // If AValNo is defined as a copy from IntB, we can potentially process this.
505 // Get the instruction that defines this value number.
506 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
507 // Don't allow any partial copies, even if isCoalescable() allows them.
508 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
511 // Get the Segment in IntB that this value number starts with.
512 LiveInterval::iterator ValS =
513 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
514 if (ValS == IntB.end())
517 // Make sure that the end of the live segment is inside the same block as
519 MachineInstr *ValSEndInst =
520 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
521 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
524 // Okay, we now know that ValS ends in the same block that the CopyMI
525 // live-range starts. If there are no intervening live segments between them
526 // in IntB, we can merge them.
527 if (ValS+1 != BS) return false;
529 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
531 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
532 // We are about to delete CopyMI, so need to remove it as the 'instruction
533 // that defines this value #'. Update the valnum with the new defining
535 BValNo->def = FillerStart;
537 // Okay, we can merge them. We need to insert a new liverange:
538 // [ValS.end, BS.begin) of either value number, then we merge the
539 // two value numbers.
540 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
542 // Okay, merge "B1" into the same value number as "B0".
543 if (BValNo != ValS->valno)
544 IntB.MergeValueNumberInto(BValNo, ValS->valno);
546 // Do the same for the subregister segments.
547 for (LiveInterval::SubRange &S : IntB.subranges()) {
548 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
549 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
550 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
551 if (SubBValNo != SubValSNo)
552 S.MergeValueNumberInto(SubBValNo, SubValSNo);
555 DEBUG(dbgs() << " result = " << IntB << '\n');
557 // If the source instruction was killing the source register before the
558 // merge, unset the isKill marker given the live range has been extended.
559 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
561 ValSEndInst->getOperand(UIdx).setIsKill(false);
564 // Rewrite the copy. If the copy instruction was killing the destination
565 // register before the merge, find the last use and trim the live range. That
566 // will also add the isKill marker.
567 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
568 if (AS->end == CopyIdx)
575 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
579 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
581 if (LIS->hasPHIKill(IntA, AValNo))
584 for (LiveRange::Segment &ASeg : IntA.segments) {
585 if (ASeg.valno != AValNo) continue;
586 LiveInterval::iterator BI =
587 std::upper_bound(IntB.begin(), IntB.end(), ASeg.start);
588 if (BI != IntB.begin())
590 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
591 if (BI->valno == BValNo)
593 if (BI->start <= ASeg.start && BI->end > ASeg.start)
595 if (BI->start > ASeg.start && BI->start < ASeg.end)
602 /// Copy segements with value number @p SrcValNo from liverange @p Src to live
603 /// range @Dst and use value number @p DstValNo there.
604 static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo,
605 const LiveRange &Src, const VNInfo *SrcValNo)
607 for (const LiveRange::Segment &S : Src.segments) {
608 if (S.valno != SrcValNo)
610 Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo));
614 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
615 MachineInstr *CopyMI) {
616 assert(!CP.isPhys());
619 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
621 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
623 // We found a non-trivially-coalescable copy with IntA being the source and
624 // IntB being the dest, thus this defines a value number in IntB. If the
625 // source value number (in IntA) is defined by a commutable instruction and
626 // its other operand is coalesced to the copy dest register, see if we can
627 // transform the copy into a noop by commuting the definition. For example,
629 // A3 = op A2 B0<kill>
631 // B1 = A3 <- this copy
633 // = op A3 <- more uses
637 // B2 = op B0 A2<kill>
639 // B1 = B2 <- now an identity copy
641 // = op B2 <- more uses
643 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
644 // the example above.
645 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
646 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
647 assert(BValNo != nullptr && BValNo->def == CopyIdx);
649 // AValNo is the value number in A that defines the copy, A3 in the example.
650 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
651 assert(AValNo && !AValNo->isUnused() && "COPY source not live");
652 if (AValNo->isPHIDef())
654 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
657 if (!DefMI->isCommutable())
659 // If DefMI is a two-address instruction then commuting it will change the
660 // destination register.
661 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
662 assert(DefIdx != -1);
664 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
667 // FIXME: The code below tries to commute 'UseOpIdx' operand with some other
668 // commutable operand which is expressed by 'CommuteAnyOperandIndex'value
669 // passed to the method. That _other_ operand is chosen by
670 // the findCommutedOpIndices() method.
672 // That is obviously an area for improvement in case of instructions having
673 // more than 2 operands. For example, if some instruction has 3 commutable
674 // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
675 // op#2<->op#3) of commute transformation should be considered/tried here.
676 unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
677 if (!TII->findCommutedOpIndices(DefMI, UseOpIdx, NewDstIdx))
680 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
681 unsigned NewReg = NewDstMO.getReg();
682 if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
685 // Make sure there are no other definitions of IntB that would reach the
686 // uses which the new definition can reach.
687 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
690 // If some of the uses of IntA.reg is already coalesced away, return false.
691 // It's not possible to determine whether it's safe to perform the coalescing.
692 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
693 MachineInstr *UseMI = MO.getParent();
694 unsigned OpNo = &MO - &UseMI->getOperand(0);
695 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
696 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
697 if (US == IntA.end() || US->valno != AValNo)
699 // If this use is tied to a def, we can't rewrite the register.
700 if (UseMI->isRegTiedToDefOperand(OpNo))
704 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
707 // At this point we have decided that it is legal to do this
708 // transformation. Start by commuting the instruction.
709 MachineBasicBlock *MBB = DefMI->getParent();
710 MachineInstr *NewMI =
711 TII->commuteInstruction(DefMI, false, UseOpIdx, NewDstIdx);
714 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
715 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
716 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
718 if (NewMI != DefMI) {
719 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
720 MachineBasicBlock::iterator Pos = DefMI;
721 MBB->insert(Pos, NewMI);
725 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
734 // Update uses of IntA of the specific Val# with IntB.
735 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
737 UI != UE; /* ++UI is below because of possible MI removal */) {
738 MachineOperand &UseMO = *UI;
742 MachineInstr *UseMI = UseMO.getParent();
743 if (UseMI->isDebugValue()) {
744 // FIXME These don't have an instruction index. Not clear we have enough
745 // info to decide whether to do this replacement or not. For now do it.
746 UseMO.setReg(NewReg);
749 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
750 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
751 assert(US != IntA.end() && "Use must be live");
752 if (US->valno != AValNo)
754 // Kill flags are no longer accurate. They are recomputed after RA.
755 UseMO.setIsKill(false);
756 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
757 UseMO.substPhysReg(NewReg, *TRI);
759 UseMO.setReg(NewReg);
762 if (!UseMI->isCopy())
764 if (UseMI->getOperand(0).getReg() != IntB.reg ||
765 UseMI->getOperand(0).getSubReg())
768 // This copy will become a noop. If it's defining a new val#, merge it into
770 SlotIndex DefIdx = UseIdx.getRegSlot();
771 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
774 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
775 assert(DVNI->def == DefIdx);
776 BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
777 for (LiveInterval::SubRange &S : IntB.subranges()) {
778 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
781 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
782 assert(SubBValNo->def == CopyIdx);
783 S.MergeValueNumberInto(SubDVNI, SubBValNo);
786 ErasedInstrs.insert(UseMI);
787 LIS->RemoveMachineInstrFromMaps(UseMI);
788 UseMI->eraseFromParent();
791 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
793 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
794 if (IntB.hasSubRanges()) {
795 if (!IntA.hasSubRanges()) {
796 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
797 IntA.createSubRangeFrom(Allocator, Mask, IntA);
799 SlotIndex AIdx = CopyIdx.getRegSlot(true);
800 for (LiveInterval::SubRange &SA : IntA.subranges()) {
801 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
802 assert(ASubValNo != nullptr);
804 LaneBitmask AMask = SA.LaneMask;
805 for (LiveInterval::SubRange &SB : IntB.subranges()) {
806 LaneBitmask BMask = SB.LaneMask;
807 LaneBitmask Common = BMask & AMask;
811 DEBUG( dbgs() << "\t\tCopy_Merge " << PrintLaneMask(BMask)
812 << " into " << PrintLaneMask(Common) << '\n');
813 LaneBitmask BRest = BMask & ~AMask;
814 LiveInterval::SubRange *CommonRange;
817 DEBUG(dbgs() << "\t\tReduce Lane to " << PrintLaneMask(BRest)
819 // Duplicate SubRange for newly merged common stuff.
820 CommonRange = IntB.createSubRangeFrom(Allocator, Common, SB);
822 // We van reuse the L SubRange.
823 SB.LaneMask = Common;
826 LiveRange RangeCopy(SB, Allocator);
828 VNInfo *BSubValNo = CommonRange->getVNInfoAt(CopyIdx);
829 assert(BSubValNo->def == CopyIdx);
830 BSubValNo->def = ASubValNo->def;
831 addSegmentsWithValNo(*CommonRange, BSubValNo, SA, ASubValNo);
835 DEBUG(dbgs() << "\t\tNew Lane " << PrintLaneMask(AMask) << '\n');
836 LiveRange *NewRange = IntB.createSubRange(Allocator, AMask);
837 VNInfo *BSubValNo = NewRange->getNextValue(CopyIdx, Allocator);
838 addSegmentsWithValNo(*NewRange, BSubValNo, SA, ASubValNo);
843 BValNo->def = AValNo->def;
844 addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
845 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
847 LIS->removeVRegDefAt(IntA, AValNo->def);
849 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
854 /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
855 /// defining a subregister.
856 static bool definesFullReg(const MachineInstr &MI, unsigned Reg) {
857 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) &&
858 "This code cannot handle physreg aliasing");
859 for (const MachineOperand &Op : MI.operands()) {
860 if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
862 // Return true if we define the full register or don't care about the value
863 // inside other subregisters.
864 if (Op.getSubReg() == 0 || Op.isUndef())
870 bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP,
871 MachineInstr *CopyMI,
874 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
875 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
876 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
877 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
878 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
881 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
882 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
883 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
884 assert(ValNo && "CopyMI input register not live");
885 if (ValNo->isPHIDef() || ValNo->isUnused())
887 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
890 if (DefMI->isCopyLike()) {
894 if (!TII->isAsCheapAsAMove(DefMI))
896 if (!TII->isTriviallyReMaterializable(DefMI, AA))
898 if (!definesFullReg(*DefMI, SrcReg))
900 bool SawStore = false;
901 if (!DefMI->isSafeToMove(AA, SawStore))
903 const MCInstrDesc &MCID = DefMI->getDesc();
904 if (MCID.getNumDefs() != 1)
906 // Only support subregister destinations when the def is read-undef.
907 MachineOperand &DstOperand = CopyMI->getOperand(0);
908 unsigned CopyDstReg = DstOperand.getReg();
909 if (DstOperand.getSubReg() && !DstOperand.isUndef())
912 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
913 // the register substantially (beyond both source and dest size). This is bad
914 // for performance since it can cascade through a function, introducing many
915 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
916 // around after a few subreg copies).
917 if (SrcIdx && DstIdx)
920 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
921 if (!DefMI->isImplicitDef()) {
922 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
923 unsigned NewDstReg = DstReg;
925 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
926 DefMI->getOperand(0).getSubReg());
928 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
930 // Finally, make sure that the physical subregister that will be
931 // constructed later is permitted for the instruction.
932 if (!DefRC->contains(NewDstReg))
935 // Theoretically, some stack frame reference could exist. Just make sure
936 // it hasn't actually happened.
937 assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
938 "Only expect to deal with virtual or physical registers");
942 MachineBasicBlock *MBB = CopyMI->getParent();
943 MachineBasicBlock::iterator MII =
944 std::next(MachineBasicBlock::iterator(CopyMI));
945 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
946 MachineInstr *NewMI = std::prev(MII);
948 // In a situation like the following:
949 // %vreg0:subreg = instr ; DefMI, subreg = DstIdx
950 // %vreg1 = copy %vreg0:subreg ; CopyMI, SrcIdx = 0
951 // instead of widening %vreg1 to the register class of %vreg0 simply do:
953 const TargetRegisterClass *NewRC = CP.getNewRC();
955 MachineOperand &DefMO = NewMI->getOperand(0);
956 if (DefMO.getSubReg() == DstIdx) {
957 assert(SrcIdx == 0 && CP.isFlipped()
958 && "Shouldn't have SrcIdx+DstIdx at this point");
959 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
960 const TargetRegisterClass *CommonRC =
961 TRI->getCommonSubClass(DefRC, DstRC);
962 if (CommonRC != nullptr) {
970 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
971 CopyMI->eraseFromParent();
972 ErasedInstrs.insert(CopyMI);
974 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
975 // We need to remember these so we can add intervals once we insert
976 // NewMI into SlotIndexes.
977 SmallVector<unsigned, 4> NewMIImplDefs;
978 for (unsigned i = NewMI->getDesc().getNumOperands(),
979 e = NewMI->getNumOperands(); i != e; ++i) {
980 MachineOperand &MO = NewMI->getOperand(i);
981 if (MO.isReg() && MO.isDef()) {
982 assert(MO.isImplicit() && MO.isDead() &&
983 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
984 NewMIImplDefs.push_back(MO.getReg());
988 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
989 unsigned NewIdx = NewMI->getOperand(0).getSubReg();
991 if (DefRC != nullptr) {
993 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
995 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
996 assert(NewRC && "subreg chosen for remat incompatible with instruction");
998 MRI->setRegClass(DstReg, NewRC);
1000 updateRegDefsUses(DstReg, DstReg, DstIdx);
1001 NewMI->getOperand(0).setSubReg(NewIdx);
1002 } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
1003 // The New instruction may be defining a sub-register of what's actually
1004 // been asked for. If so it must implicitly define the whole thing.
1005 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
1006 "Only expect virtual or physical registers in remat");
1007 NewMI->getOperand(0).setIsDead(true);
1008 NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
1012 // Record small dead def live-ranges for all the subregisters
1013 // of the destination register.
1014 // Otherwise, variables that live through may miss some
1015 // interferences, thus creating invalid allocation.
1017 // vreg1 = somedef ; vreg1 GR8
1018 // vreg2 = remat ; vreg2 GR32
1019 // CL = COPY vreg2.sub_8bit
1020 // = somedef vreg1 ; vreg1 GR8
1022 // vreg1 = somedef ; vreg1 GR8
1023 // ECX<def, dead> = remat ; CL<imp-def>
1024 // = somedef vreg1 ; vreg1 GR8
1025 // vreg1 will see the inteferences with CL but not with CH since
1026 // no live-ranges would have been created for ECX.
1028 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1029 for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI);
1030 Units.isValid(); ++Units)
1031 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1032 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1035 if (NewMI->getOperand(0).getSubReg())
1036 NewMI->getOperand(0).setIsUndef();
1038 // CopyMI may have implicit operands, transfer them over to the newly
1039 // rematerialized instruction. And update implicit def interval valnos.
1040 for (unsigned i = CopyMI->getDesc().getNumOperands(),
1041 e = CopyMI->getNumOperands(); i != e; ++i) {
1042 MachineOperand &MO = CopyMI->getOperand(i);
1044 assert(MO.isImplicit() && "No explicit operands after implict operands.");
1045 // Discard VReg implicit defs.
1046 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
1047 NewMI->addOperand(MO);
1052 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1053 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
1054 unsigned Reg = NewMIImplDefs[i];
1055 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1056 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1057 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1060 DEBUG(dbgs() << "Remat: " << *NewMI);
1063 // The source interval can become smaller because we removed a use.
1064 shrinkToUses(&SrcInt, &DeadDefs);
1065 if (!DeadDefs.empty()) {
1066 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1067 // to describe DstReg instead.
1068 for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
1069 MachineInstr *UseMI = UseMO.getParent();
1070 if (UseMI->isDebugValue()) {
1071 UseMO.setReg(DstReg);
1072 DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1075 eliminateDeadDefs();
1081 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1082 // ProcessImpicitDefs may leave some copies of <undef> values, it only removes
1083 // local variables. When we have a copy like:
1085 // %vreg1 = COPY %vreg2<undef>
1087 // We delete the copy and remove the corresponding value number from %vreg1.
1088 // Any uses of that value number are marked as <undef>.
1090 // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1091 // CoalescerPair may have a new register class with adjusted subreg indices
1093 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1094 isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1096 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
1097 const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1098 // CopyMI is undef iff SrcReg is not live before the instruction.
1099 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1100 LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1101 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1102 if ((SR.LaneMask & SrcMask) == 0)
1107 } else if (SrcLI.liveAt(Idx))
1110 DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1112 // Remove any DstReg segments starting at the instruction.
1113 LiveInterval &DstLI = LIS->getInterval(DstReg);
1114 SlotIndex RegIndex = Idx.getRegSlot();
1115 // Remove value or merge with previous one in case of a subregister def.
1116 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1117 VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
1118 DstLI.MergeValueNumberInto(VNI, PrevVNI);
1120 // The affected subregister segments can be removed.
1121 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1122 for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1123 if ((SR.LaneMask & DstMask) == 0)
1126 VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1127 assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
1128 SR.removeValNo(SVNI);
1130 DstLI.removeEmptySubRanges();
1132 LIS->removeVRegDefAt(DstLI, RegIndex);
1134 // Mark uses as undef.
1135 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1136 if (MO.isDef() /*|| MO.isUndef()*/)
1138 const MachineInstr &MI = *MO.getParent();
1139 SlotIndex UseIdx = LIS->getInstructionIndex(&MI);
1140 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1142 if (UseMask != ~0u && DstLI.hasSubRanges()) {
1144 for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1145 if ((SR.LaneMask & UseMask) == 0)
1147 if (SR.liveAt(UseIdx)) {
1153 isLive = DstLI.liveAt(UseIdx);
1156 MO.setIsUndef(true);
1157 DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1162 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
1165 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1166 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1168 SmallPtrSet<MachineInstr*, 8> Visited;
1169 for (MachineRegisterInfo::reg_instr_iterator
1170 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1172 MachineInstr *UseMI = &*(I++);
1174 // Each instruction can only be rewritten once because sub-register
1175 // composition is not always idempotent. When SrcReg != DstReg, rewriting
1176 // the UseMI operands removes them from the SrcReg use-def chain, but when
1177 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1178 // operands mentioning the virtual register.
1179 if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1182 SmallVector<unsigned,8> Ops;
1184 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1186 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1187 // because SrcReg is a sub-register.
1188 if (DstInt && !Reads && SubIdx)
1189 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
1191 // Replace SrcReg with DstReg in all UseMI operands.
1192 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1193 MachineOperand &MO = UseMI->getOperand(Ops[i]);
1195 // Adjust <undef> flags in case of sub-register joins. We don't want to
1196 // turn a full def into a read-modify-write sub-register def and vice
1198 if (SubIdx && MO.isDef())
1199 MO.setIsUndef(!Reads);
1201 // A subreg use of a partially undef (super) register may be a complete
1202 // undef use now and then has to be marked that way.
1203 if (SubIdx != 0 && MO.isUse() && MRI->shouldTrackSubRegLiveness(DstReg)) {
1204 if (!DstInt->hasSubRanges()) {
1205 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1206 LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
1207 DstInt->createSubRangeFrom(Allocator, Mask, *DstInt);
1209 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubIdx);
1210 bool IsUndef = true;
1211 SlotIndex MIIdx = UseMI->isDebugValue()
1212 ? LIS->getSlotIndexes()->getIndexBefore(UseMI)
1213 : LIS->getInstructionIndex(UseMI);
1214 SlotIndex UseIdx = MIIdx.getRegSlot(true);
1215 for (LiveInterval::SubRange &S : DstInt->subranges()) {
1216 if ((S.LaneMask & Mask) == 0)
1218 if (S.liveAt(UseIdx)) {
1224 MO.setIsUndef(true);
1225 // We found out some subregister use is actually reading an undefined
1226 // value. In some cases the whole vreg has become undefined at this
1227 // point so we have to potentially shrink the main range if the
1228 // use was ending a live segment there.
1229 LiveQueryResult Q = DstInt->Query(MIIdx);
1230 if (Q.valueOut() == nullptr)
1231 ShrinkMainRange = true;
1236 MO.substPhysReg(DstReg, *TRI);
1238 MO.substVirtReg(DstReg, SubIdx, *TRI);
1242 dbgs() << "\t\tupdated: ";
1243 if (!UseMI->isDebugValue())
1244 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
1250 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1251 // Always join simple intervals that are defined by a single copy from a
1252 // reserved register. This doesn't increase register pressure, so it is
1253 // always beneficial.
1254 if (!MRI->isReserved(CP.getDstReg())) {
1255 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1259 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1260 if (JoinVInt.containsOneValue())
1263 DEBUG(dbgs() << "\tCannot join complex intervals into reserved register.\n");
1267 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1270 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1272 CoalescerPair CP(*TRI);
1273 if (!CP.setRegisters(CopyMI)) {
1274 DEBUG(dbgs() << "\tNot coalescable.\n");
1278 if (CP.getNewRC()) {
1279 auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1280 auto DstRC = MRI->getRegClass(CP.getDstReg());
1281 unsigned SrcIdx = CP.getSrcIdx();
1282 unsigned DstIdx = CP.getDstIdx();
1283 if (CP.isFlipped()) {
1284 std::swap(SrcIdx, DstIdx);
1285 std::swap(SrcRC, DstRC);
1287 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1289 DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
1294 // Dead code elimination. This really should be handled by MachineDCE, but
1295 // sometimes dead copies slip through, and we can't generate invalid live
1297 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1298 DEBUG(dbgs() << "\tCopy is dead.\n");
1299 DeadDefs.push_back(CopyMI);
1300 eliminateDeadDefs();
1304 // Eliminate undefs.
1305 if (!CP.isPhys() && eliminateUndefCopy(CopyMI)) {
1306 LIS->RemoveMachineInstrFromMaps(CopyMI);
1307 CopyMI->eraseFromParent();
1308 return false; // Not coalescable.
1311 // Coalesced copies are normally removed immediately, but transformations
1312 // like removeCopyByCommutingDef() can inadvertently create identity copies.
1313 // When that happens, just join the values and remove the copy.
1314 if (CP.getSrcReg() == CP.getDstReg()) {
1315 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1316 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1317 const SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
1318 LiveQueryResult LRQ = LI.Query(CopyIdx);
1319 if (VNInfo *DefVNI = LRQ.valueDefined()) {
1320 VNInfo *ReadVNI = LRQ.valueIn();
1321 assert(ReadVNI && "No value before copy and no <undef> flag.");
1322 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1323 LI.MergeValueNumberInto(DefVNI, ReadVNI);
1325 // Process subregister liveranges.
1326 for (LiveInterval::SubRange &S : LI.subranges()) {
1327 LiveQueryResult SLRQ = S.Query(CopyIdx);
1328 if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
1329 VNInfo *SReadVNI = SLRQ.valueIn();
1330 S.MergeValueNumberInto(SDefVNI, SReadVNI);
1333 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
1335 LIS->RemoveMachineInstrFromMaps(CopyMI);
1336 CopyMI->eraseFromParent();
1340 // Enforce policies.
1342 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1343 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1345 if (!canJoinPhys(CP)) {
1346 // Before giving up coalescing, if definition of source is defined by
1347 // trivial computation, try rematerializing it.
1349 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1352 Again = true; // May be possible to coalesce later.
1356 // When possible, let DstReg be the larger interval.
1357 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1358 LIS->getInterval(CP.getDstReg()).size())
1362 dbgs() << "\tConsidering merging to "
1363 << TRI->getRegClassName(CP.getNewRC()) << " with ";
1364 if (CP.getDstIdx() && CP.getSrcIdx())
1365 dbgs() << PrintReg(CP.getDstReg()) << " in "
1366 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1367 << PrintReg(CP.getSrcReg()) << " in "
1368 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1370 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1371 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1376 ShrinkMainRange = false;
1378 // Okay, attempt to join these two intervals. On failure, this returns false.
1379 // Otherwise, if one of the intervals being joined is a physreg, this method
1380 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1381 // been modified, so we can use this information below to update aliases.
1382 if (!joinIntervals(CP)) {
1383 // Coalescing failed.
1385 // If definition of source is defined by trivial computation, try
1386 // rematerializing it.
1388 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1391 // If we can eliminate the copy without merging the live segments, do so
1393 if (!CP.isPartial() && !CP.isPhys()) {
1394 if (adjustCopiesBackFrom(CP, CopyMI) ||
1395 removeCopyByCommutingDef(CP, CopyMI)) {
1396 LIS->RemoveMachineInstrFromMaps(CopyMI);
1397 CopyMI->eraseFromParent();
1398 DEBUG(dbgs() << "\tTrivial!\n");
1403 // Otherwise, we are unable to join the intervals.
1404 DEBUG(dbgs() << "\tInterference!\n");
1405 Again = true; // May be possible to coalesce later.
1409 // Coalescing to a virtual register that is of a sub-register class of the
1410 // other. Make sure the resulting register is set to the right register class.
1411 if (CP.isCrossClass()) {
1413 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1416 // Removing sub-register copies can ease the register class constraints.
1417 // Make sure we attempt to inflate the register class of DstReg.
1418 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1419 InflateRegs.push_back(CP.getDstReg());
1421 // CopyMI has been erased by joinIntervals at this point. Remove it from
1422 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1423 // to the work list. This keeps ErasedInstrs from growing needlessly.
1424 ErasedInstrs.erase(CopyMI);
1426 // Rewrite all SrcReg operands to DstReg.
1427 // Also update DstReg operands to include DstIdx if it is set.
1429 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1430 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1432 // Shrink subregister ranges if necessary.
1433 if (ShrinkMask != 0) {
1434 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1435 for (LiveInterval::SubRange &S : LI.subranges()) {
1436 if ((S.LaneMask & ShrinkMask) == 0)
1438 DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)
1440 LIS->shrinkToUses(S, LI.reg);
1442 LI.removeEmptySubRanges();
1444 if (ShrinkMainRange) {
1445 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1449 // SrcReg is guaranteed to be the register whose live interval that is
1451 LIS->removeInterval(CP.getSrcReg());
1453 // Update regalloc hint.
1454 TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1457 dbgs() << "\tSuccess: " << PrintReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
1458 << " -> " << PrintReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
1459 dbgs() << "\tResult = ";
1461 dbgs() << PrintReg(CP.getDstReg(), TRI);
1463 dbgs() << LIS->getInterval(CP.getDstReg());
1471 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1472 unsigned DstReg = CP.getDstReg();
1473 assert(CP.isPhys() && "Must be a physreg copy");
1474 assert(MRI->isReserved(DstReg) && "Not a reserved register");
1475 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1476 DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1478 assert(RHS.containsOneValue() && "Invalid join with reserved register");
1480 // Optimization for reserved registers like ESP. We can only merge with a
1481 // reserved physreg if RHS has a single value that is a copy of DstReg.
1482 // The live range of the reserved register will look like a set of dead defs
1483 // - we don't properly track the live range of reserved registers.
1485 // Deny any overlapping intervals. This depends on all the reserved
1486 // register live ranges to look like dead defs.
1487 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI)
1488 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1489 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1493 // Skip any value computations, we are not adding new values to the
1494 // reserved register. Also skip merging the live ranges, the reserved
1495 // register live range doesn't need to be accurate as long as all the
1498 // Delete the identity copy.
1499 MachineInstr *CopyMI;
1500 if (CP.isFlipped()) {
1501 CopyMI = MRI->getVRegDef(RHS.reg);
1503 if (!MRI->hasOneNonDBGUse(RHS.reg)) {
1504 DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
1508 MachineInstr *DestMI = MRI->getVRegDef(RHS.reg);
1509 CopyMI = &*MRI->use_instr_nodbg_begin(RHS.reg);
1510 const SlotIndex CopyRegIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
1511 const SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
1513 // We checked above that there are no interfering defs of the physical
1514 // register. However, for this case, where we intent to move up the def of
1515 // the physical register, we also need to check for interfering uses.
1516 SlotIndexes *Indexes = LIS->getSlotIndexes();
1517 for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
1518 SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
1519 MachineInstr *MI = LIS->getInstructionFromIndex(SI);
1520 if (MI->readsRegister(DstReg, TRI)) {
1521 DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
1525 // We must also check for clobbers caused by regmasks.
1526 for (const auto &MO : MI->operands()) {
1527 if (MO.isRegMask() && MO.clobbersPhysReg(DstReg)) {
1528 DEBUG(dbgs() << "\t\tInterference (regmask clobber): " << *MI);
1534 // We're going to remove the copy which defines a physical reserved
1535 // register, so remove its valno, etc.
1536 DEBUG(dbgs() << "\t\tRemoving phys reg def of " << DstReg << " at "
1537 << CopyRegIdx << "\n");
1539 LIS->removePhysRegDefAt(DstReg, CopyRegIdx);
1540 // Create a new dead def at the new def location.
1541 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
1542 LiveRange &LR = LIS->getRegUnit(*UI);
1543 LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
1547 LIS->RemoveMachineInstrFromMaps(CopyMI);
1548 CopyMI->eraseFromParent();
1550 // We don't track kills for reserved registers.
1551 MRI->clearKillFlags(CP.getSrcReg());
1556 //===----------------------------------------------------------------------===//
1557 // Interference checking and interval joining
1558 //===----------------------------------------------------------------------===//
1560 // In the easiest case, the two live ranges being joined are disjoint, and
1561 // there is no interference to consider. It is quite common, though, to have
1562 // overlapping live ranges, and we need to check if the interference can be
1565 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1566 // This means that two SSA values overlap if and only if the def of one value
1567 // is contained in the live range of the other value. As a special case, the
1568 // overlapping values can be defined at the same index.
1570 // The interference from an overlapping def can be resolved in these cases:
1572 // 1. Coalescable copies. The value is defined by a copy that would become an
1573 // identity copy after joining SrcReg and DstReg. The copy instruction will
1574 // be removed, and the value will be merged with the source value.
1576 // There can be several copies back and forth, causing many values to be
1577 // merged into one. We compute a list of ultimate values in the joined live
1578 // range as well as a mappings from the old value numbers.
1580 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1581 // predecessors have a live out value. It doesn't cause real interference,
1582 // and can be merged into the value it overlaps. Like a coalescable copy, it
1583 // can be erased after joining.
1585 // 3. Copy of external value. The overlapping def may be a copy of a value that
1586 // is already in the other register. This is like a coalescable copy, but
1587 // the live range of the source register must be trimmed after erasing the
1588 // copy instruction:
1591 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1593 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1594 // defining one lane at a time:
1596 // %dst:ssub0<def,read-undef> = FOO
1598 // %dst:ssub1<def> = COPY %src
1600 // The live range of %src overlaps the %dst value defined by FOO, but
1601 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1602 // which was undef anyway.
1604 // The value mapping is more complicated in this case. The final live range
1605 // will have different value numbers for both FOO and BAR, but there is no
1606 // simple mapping from old to new values. It may even be necessary to add
1609 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1610 // is live, but never read. This can happen because we don't compute
1611 // individual live ranges per lane.
1615 // %dst:ssub1<def> = COPY %src
1617 // This kind of interference is only resolved locally. If the clobbered
1618 // lane value escapes the block, the join is aborted.
1621 /// Track information about values in a single virtual register about to be
1622 /// joined. Objects of this class are always created in pairs - one for each
1623 /// side of the CoalescerPair (or one for each lane of a side of the coalescer
1626 /// Live range we work on.
1628 /// (Main) register we work on.
1631 /// Reg (and therefore the values in this liverange) will end up as
1632 /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
1634 const unsigned SubIdx;
1635 /// The LaneMask that this liverange will occupy the coalesced register. May
1636 /// be smaller than the lanemask produced by SubIdx when merging subranges.
1637 const LaneBitmask LaneMask;
1639 /// This is true when joining sub register ranges, false when joining main
1641 const bool SubRangeJoin;
1642 /// Whether the current LiveInterval tracks subregister liveness.
1643 const bool TrackSubRegLiveness;
1645 /// Values that will be present in the final live range.
1646 SmallVectorImpl<VNInfo*> &NewVNInfo;
1648 const CoalescerPair &CP;
1650 SlotIndexes *Indexes;
1651 const TargetRegisterInfo *TRI;
1653 /// Value number assignments. Maps value numbers in LI to entries in
1654 /// NewVNInfo. This is suitable for passing to LiveInterval::join().
1655 SmallVector<int, 8> Assignments;
1657 /// Conflict resolution for overlapping values.
1658 enum ConflictResolution {
1659 /// No overlap, simply keep this value.
1662 /// Merge this value into OtherVNI and erase the defining instruction.
1663 /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
1667 /// Merge this value into OtherVNI but keep the defining instruction.
1668 /// This is for the special case where OtherVNI is defined by the same
1672 /// Keep this value, and have it replace OtherVNI where possible. This
1673 /// complicates value mapping since OtherVNI maps to two different values
1674 /// before and after this def.
1675 /// Used when clobbering undefined or dead lanes.
1678 /// Unresolved conflict. Visit later when all values have been mapped.
1681 /// Unresolvable conflict. Abort the join.
1685 /// Per-value info for LI. The lane bit masks are all relative to the final
1686 /// joined register, so they can be compared directly between SrcReg and
1689 ConflictResolution Resolution;
1691 /// Lanes written by this def, 0 for unanalyzed values.
1692 LaneBitmask WriteLanes;
1694 /// Lanes with defined values in this register. Other lanes are undef and
1695 /// safe to clobber.
1696 LaneBitmask ValidLanes;
1698 /// Value in LI being redefined by this def.
1701 /// Value in the other live range that overlaps this def, if any.
1704 /// Is this value an IMPLICIT_DEF that can be erased?
1706 /// IMPLICIT_DEF values should only exist at the end of a basic block that
1707 /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1708 /// safely erased if they are overlapping a live value in the other live
1711 /// Weird control flow graphs and incomplete PHI handling in
1712 /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1713 /// longer live ranges. Such IMPLICIT_DEF values should be treated like
1715 bool ErasableImplicitDef;
1717 /// True when the live range of this value will be pruned because of an
1718 /// overlapping CR_Replace value in the other live range.
1721 /// True once Pruned above has been computed.
1722 bool PrunedComputed;
1724 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1725 RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false),
1726 Pruned(false), PrunedComputed(false) {}
1728 bool isAnalyzed() const { return WriteLanes != 0; }
1731 /// One entry per value number in LI.
1732 SmallVector<Val, 8> Vals;
1734 /// Compute the bitmask of lanes actually written by DefMI.
1735 /// Set Redef if there are any partial register definitions that depend on the
1736 /// previous value of the register.
1737 LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
1739 /// Find the ultimate value that VNI was copied from.
1740 std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const;
1742 bool valuesIdentical(VNInfo *Val0, VNInfo *Val1, const JoinVals &Other) const;
1744 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1745 /// Return a conflict resolution when possible, but leave the hard cases as
1747 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1748 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1749 /// The recursion always goes upwards in the dominator tree, making loops
1751 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1753 /// Compute the value assignment for ValNo in RI.
1754 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1756 void computeAssignment(unsigned ValNo, JoinVals &Other);
1758 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
1759 /// the extent of the tainted lanes in the block.
1761 /// Multiple values in Other.LR can be affected since partial redefinitions
1762 /// can preserve previously tainted lanes.
1764 /// 1 %dst = VLOAD <-- Define all lanes in %dst
1765 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
1766 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
1767 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1769 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1770 /// entry to TaintedVals.
1772 /// Returns false if the tainted lanes extend beyond the basic block.
1773 bool taintExtent(unsigned, LaneBitmask, JoinVals&,
1774 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask> >&);
1776 /// Return true if MI uses any of the given Lanes from Reg.
1777 /// This does not include partial redefinitions of Reg.
1778 bool usesLanes(const MachineInstr *MI, unsigned, unsigned, LaneBitmask) const;
1780 /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
1783 /// %dst = COPY %src
1784 /// %src = COPY %dst <-- This value to be pruned.
1785 /// %dst = COPY %src <-- This value is a copy of a pruned value.
1786 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1789 JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, LaneBitmask LaneMask,
1790 SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp,
1791 LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
1792 bool TrackSubRegLiveness)
1793 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
1794 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
1795 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
1796 TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums())
1799 /// Analyze defs in LR and compute a value mapping in NewVNInfo.
1800 /// Returns false if any conflicts were impossible to resolve.
1801 bool mapValues(JoinVals &Other);
1803 /// Try to resolve conflicts that require all values to be mapped.
1804 /// Returns false if any conflicts were impossible to resolve.
1805 bool resolveConflicts(JoinVals &Other);
1807 /// Prune the live range of values in Other.LR where they would conflict with
1808 /// CR_Replace values in LR. Collect end points for restoring the live range
1810 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
1813 /// Removes subranges starting at copies that get removed. This sometimes
1814 /// happens when undefined subranges are copied around. These ranges contain
1815 /// no useful information and can be removed.
1816 void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask);
1818 /// Erase any machine instructions that have been coalesced away.
1819 /// Add erased instructions to ErasedInstrs.
1820 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1821 /// the erased instrs.
1822 void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
1823 SmallVectorImpl<unsigned> &ShrinkRegs);
1825 /// Remove liverange defs at places where implicit defs will be removed.
1826 void removeImplicitDefs();
1828 /// Get the value assignments suitable for passing to LiveInterval::join.
1829 const int *getAssignments() const { return Assignments.data(); }
1831 } // end anonymous namespace
1833 LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
1836 for (const MachineOperand &MO : DefMI->operands()) {
1837 if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef())
1839 L |= TRI->getSubRegIndexLaneMask(
1840 TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
1847 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
1848 const VNInfo *VNI) const {
1849 unsigned Reg = this->Reg;
1851 while (!VNI->isPHIDef()) {
1852 SlotIndex Def = VNI->def;
1853 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1854 assert(MI && "No defining instruction");
1855 if (!MI->isFullCopy())
1856 return std::make_pair(VNI, Reg);
1857 unsigned SrcReg = MI->getOperand(1).getReg();
1858 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1859 return std::make_pair(VNI, Reg);
1861 const LiveInterval &LI = LIS->getInterval(SrcReg);
1862 const VNInfo *ValueIn;
1863 // No subrange involved.
1864 if (!SubRangeJoin || !LI.hasSubRanges()) {
1865 LiveQueryResult LRQ = LI.Query(Def);
1866 ValueIn = LRQ.valueIn();
1868 // Query subranges. Pick the first matching one.
1870 for (const LiveInterval::SubRange &S : LI.subranges()) {
1871 // Transform lanemask to a mask in the joined live interval.
1872 LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
1873 if ((SMask & LaneMask) == 0)
1875 LiveQueryResult LRQ = S.Query(Def);
1876 ValueIn = LRQ.valueIn();
1880 if (ValueIn == nullptr)
1885 return std::make_pair(VNI, Reg);
1888 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
1889 const JoinVals &Other) const {
1890 const VNInfo *Orig0;
1892 std::tie(Orig0, Reg0) = followCopyChain(Value0);
1893 if (Orig0 == Value1)
1896 const VNInfo *Orig1;
1898 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
1900 // The values are equal if they are defined at the same place and use the
1901 // same register. Note that we cannot compare VNInfos directly as some of
1902 // them might be from a copy created in mergeSubRangeInto() while the other
1903 // is from the original LiveInterval.
1904 return Orig0->def == Orig1->def && Reg0 == Reg1;
1907 JoinVals::ConflictResolution
1908 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1909 Val &V = Vals[ValNo];
1910 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1911 VNInfo *VNI = LR.getValNumInfo(ValNo);
1912 if (VNI->isUnused()) {
1917 // Get the instruction defining this value, compute the lanes written.
1918 const MachineInstr *DefMI = nullptr;
1919 if (VNI->isPHIDef()) {
1920 // Conservatively assume that all lanes in a PHI are valid.
1921 LaneBitmask Lanes = SubRangeJoin ? 1 : TRI->getSubRegIndexLaneMask(SubIdx);
1922 V.ValidLanes = V.WriteLanes = Lanes;
1924 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1925 assert(DefMI != nullptr);
1927 // We don't care about the lanes when joining subregister ranges.
1928 V.WriteLanes = V.ValidLanes = 1;
1929 if (DefMI->isImplicitDef()) {
1931 V.ErasableImplicitDef = true;
1935 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1937 // If this is a read-modify-write instruction, there may be more valid
1938 // lanes than the ones written by this instruction.
1939 // This only covers partial redef operands. DefMI may have normal use
1940 // operands reading the register. They don't contribute valid lanes.
1942 // This adds ssub1 to the set of valid lanes in %src:
1944 // %src:ssub1<def> = FOO
1946 // This leaves only ssub1 valid, making any other lanes undef:
1948 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1950 // The <read-undef> flag on the def operand means that old lane values are
1953 V.RedefVNI = LR.Query(VNI->def).valueIn();
1954 assert((TrackSubRegLiveness || V.RedefVNI) &&
1955 "Instruction is reading nonexistent value");
1956 if (V.RedefVNI != nullptr) {
1957 computeAssignment(V.RedefVNI->id, Other);
1958 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1962 // An IMPLICIT_DEF writes undef values.
1963 if (DefMI->isImplicitDef()) {
1964 // We normally expect IMPLICIT_DEF values to be live only until the end
1965 // of their block. If the value is really live longer and gets pruned in
1966 // another block, this flag is cleared again.
1967 V.ErasableImplicitDef = true;
1968 V.ValidLanes &= ~V.WriteLanes;
1973 // Find the value in Other that overlaps VNI->def, if any.
1974 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
1976 // It is possible that both values are defined by the same instruction, or
1977 // the values are PHIs defined in the same block. When that happens, the two
1978 // values should be merged into one, but not into any preceding value.
1979 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1980 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1981 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1983 // One value stays, the other is merged. Keep the earlier one, or the first
1985 if (OtherVNI->def < VNI->def)
1986 Other.computeAssignment(OtherVNI->id, *this);
1987 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1988 // This is an early-clobber def overlapping a live-in value in the other
1989 // register. Not mergeable.
1990 V.OtherVNI = OtherLRQ.valueIn();
1991 return CR_Impossible;
1993 V.OtherVNI = OtherVNI;
1994 Val &OtherV = Other.Vals[OtherVNI->id];
1995 // Keep this value, check for conflicts when analyzing OtherVNI.
1996 if (!OtherV.isAnalyzed())
1998 // Both sides have been analyzed now.
1999 // Allow overlapping PHI values. Any real interference would show up in a
2000 // predecessor, the PHI itself can't introduce any conflicts.
2001 if (VNI->isPHIDef())
2003 if (V.ValidLanes & OtherV.ValidLanes)
2004 // Overlapping lanes can't be resolved.
2005 return CR_Impossible;
2010 // No simultaneous def. Is Other live at the def?
2011 V.OtherVNI = OtherLRQ.valueIn();
2013 // No overlap, no conflict.
2016 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
2018 // We have overlapping values, or possibly a kill of Other.
2019 // Recursively compute assignments up the dominator tree.
2020 Other.computeAssignment(V.OtherVNI->id, *this);
2021 Val &OtherV = Other.Vals[V.OtherVNI->id];
2023 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
2024 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
2025 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
2028 // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
2029 // to erase the IMPLICIT_DEF instruction.
2030 if (OtherV.ErasableImplicitDef && DefMI &&
2031 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
2032 DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
2033 << " extends into BB#" << DefMI->getParent()->getNumber()
2034 << ", keeping it.\n");
2035 OtherV.ErasableImplicitDef = false;
2038 // Allow overlapping PHI values. Any real interference would show up in a
2039 // predecessor, the PHI itself can't introduce any conflicts.
2040 if (VNI->isPHIDef())
2043 // Check for simple erasable conflicts.
2044 if (DefMI->isImplicitDef()) {
2045 // We need the def for the subregister if there is nothing else live at the
2046 // subrange at this point.
2047 if (TrackSubRegLiveness
2048 && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)) == 0)
2053 // Include the non-conflict where DefMI is a coalescable copy that kills
2054 // OtherVNI. We still want the copy erased and value numbers merged.
2055 if (CP.isCoalescable(DefMI)) {
2056 // Some of the lanes copied from OtherVNI may be undef, making them undef
2058 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
2062 // This may not be a real conflict if DefMI simply kills Other and defines
2064 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
2067 // Handle the case where VNI and OtherVNI can be proven to be identical:
2069 // %other = COPY %ext
2070 // %this = COPY %ext <-- Erase this copy
2072 if (DefMI->isFullCopy() && !CP.isPartial()
2073 && valuesIdentical(VNI, V.OtherVNI, Other))
2076 // If the lanes written by this instruction were all undef in OtherVNI, it is
2077 // still safe to join the live ranges. This can't be done with a simple value
2078 // mapping, though - OtherVNI will map to multiple values:
2080 // 1 %dst:ssub0 = FOO <-- OtherVNI
2081 // 2 %src = BAR <-- VNI
2082 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
2084 // 5 QUUX %src<kill>
2086 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
2087 // handles this complex value mapping.
2088 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
2091 // If the other live range is killed by DefMI and the live ranges are still
2092 // overlapping, it must be because we're looking at an early clobber def:
2094 // %dst<def,early-clobber> = ASM %src<kill>
2096 // In this case, it is illegal to merge the two live ranges since the early
2097 // clobber def would clobber %src before it was read.
2098 if (OtherLRQ.isKill()) {
2099 // This case where the def doesn't overlap the kill is handled above.
2100 assert(VNI->def.isEarlyClobber() &&
2101 "Only early clobber defs can overlap a kill");
2102 return CR_Impossible;
2105 // VNI is clobbering live lanes in OtherVNI, but there is still the
2106 // possibility that no instructions actually read the clobbered lanes.
2107 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
2108 // Otherwise Other.RI wouldn't be live here.
2109 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
2110 return CR_Impossible;
2112 // We need to verify that no instructions are reading the clobbered lanes. To
2113 // save compile time, we'll only check that locally. Don't allow the tainted
2114 // value to escape the basic block.
2115 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2116 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
2117 return CR_Impossible;
2119 // There are still some things that could go wrong besides clobbered lanes
2120 // being read, for example OtherVNI may be only partially redefined in MBB,
2121 // and some clobbered lanes could escape the block. Save this analysis for
2122 // resolveConflicts() when all values have been mapped. We need to know
2123 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
2124 // that now - the recursive analyzeValue() calls must go upwards in the
2126 return CR_Unresolved;
2129 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
2130 Val &V = Vals[ValNo];
2131 if (V.isAnalyzed()) {
2132 // Recursion should always move up the dominator tree, so ValNo is not
2133 // supposed to reappear before it has been assigned.
2134 assert(Assignments[ValNo] != -1 && "Bad recursion?");
2137 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2140 // Merge this ValNo into OtherVNI.
2141 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
2142 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
2143 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2144 DEBUG(dbgs() << "\t\tmerge " << PrintReg(Reg) << ':' << ValNo << '@'
2145 << LR.getValNumInfo(ValNo)->def << " into "
2146 << PrintReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
2147 << V.OtherVNI->def << " --> @"
2148 << NewVNInfo[Assignments[ValNo]]->def << '\n');
2151 case CR_Unresolved: {
2152 // The other value is going to be pruned if this join is successful.
2153 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
2154 Val &OtherV = Other.Vals[V.OtherVNI->id];
2155 // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
2157 if ((OtherV.WriteLanes & ~V.ValidLanes) != 0 && TrackSubRegLiveness)
2158 OtherV.ErasableImplicitDef = false;
2159 OtherV.Pruned = true;
2163 // This value number needs to go in the final joined live range.
2164 Assignments[ValNo] = NewVNInfo.size();
2165 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
2170 bool JoinVals::mapValues(JoinVals &Other) {
2171 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2172 computeAssignment(i, Other);
2173 if (Vals[i].Resolution == CR_Impossible) {
2174 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(Reg) << ':' << i
2175 << '@' << LR.getValNumInfo(i)->def << '\n');
2183 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
2184 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask> > &TaintExtent) {
2185 VNInfo *VNI = LR.getValNumInfo(ValNo);
2186 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2187 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2189 // Scan Other.LR from VNI.def to MBBEnd.
2190 LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
2191 assert(OtherI != Other.LR.end() && "No conflict?");
2193 // OtherI is pointing to a tainted value. Abort the join if the tainted
2194 // lanes escape the block.
2195 SlotIndex End = OtherI->end;
2196 if (End >= MBBEnd) {
2197 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.Reg) << ':'
2198 << OtherI->valno->id << '@' << OtherI->start << '\n');
2201 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.Reg) << ':'
2202 << OtherI->valno->id << '@' << OtherI->start
2203 << " to " << End << '\n');
2204 // A dead def is not a problem.
2207 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2209 // Check for another def in the MBB.
2210 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2213 // Lanes written by the new def are no longer tainted.
2214 const Val &OV = Other.Vals[OtherI->valno->id];
2215 TaintedLanes &= ~OV.WriteLanes;
2218 } while (TaintedLanes);
2222 bool JoinVals::usesLanes(const MachineInstr *MI, unsigned Reg, unsigned SubIdx,
2223 LaneBitmask Lanes) const {
2224 if (MI->isDebugValue())
2226 for (const MachineOperand &MO : MI->operands()) {
2227 if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg)
2231 if (Lanes & TRI->getSubRegIndexLaneMask(
2232 TRI->composeSubRegIndices(SubIdx, MO.getSubReg())))
2238 bool JoinVals::resolveConflicts(JoinVals &Other) {
2239 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2241 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
2242 if (V.Resolution != CR_Unresolved)
2244 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(Reg) << ':' << i
2245 << '@' << LR.getValNumInfo(i)->def << '\n');
2250 assert(V.OtherVNI && "Inconsistent conflict resolution.");
2251 VNInfo *VNI = LR.getValNumInfo(i);
2252 const Val &OtherV = Other.Vals[V.OtherVNI->id];
2254 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
2255 // join, those lanes will be tainted with a wrong value. Get the extent of
2256 // the tainted lanes.
2257 LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2258 SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent;
2259 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2260 // Tainted lanes would extend beyond the basic block.
2263 assert(!TaintExtent.empty() && "There should be at least one conflict.");
2265 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
2266 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2267 MachineBasicBlock::iterator MI = MBB->begin();
2268 if (!VNI->isPHIDef()) {
2269 MI = Indexes->getInstructionFromIndex(VNI->def);
2270 // No need to check the instruction defining VNI for reads.
2273 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
2274 "Interference ends on VNI->def. Should have been handled earlier");
2275 MachineInstr *LastMI =
2276 Indexes->getInstructionFromIndex(TaintExtent.front().first);
2277 assert(LastMI && "Range must end at a proper instruction");
2278 unsigned TaintNum = 0;
2280 assert(MI != MBB->end() && "Bad LastMI");
2281 if (usesLanes(MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2282 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
2285 // LastMI is the last instruction to use the current value.
2286 if (&*MI == LastMI) {
2287 if (++TaintNum == TaintExtent.size())
2289 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
2290 assert(LastMI && "Range must end at a proper instruction");
2291 TaintedLanes = TaintExtent[TaintNum].second;
2296 // The tainted lanes are unused.
2297 V.Resolution = CR_Replace;
2303 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
2304 Val &V = Vals[ValNo];
2305 if (V.Pruned || V.PrunedComputed)
2308 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2311 // Follow copies up the dominator tree and check if any intermediate value
2313 V.PrunedComputed = true;
2314 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
2318 void JoinVals::pruneValues(JoinVals &Other,
2319 SmallVectorImpl<SlotIndex> &EndPoints,
2320 bool changeInstrs) {
2321 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2322 SlotIndex Def = LR.getValNumInfo(i)->def;
2323 switch (Vals[i].Resolution) {
2327 // This value takes precedence over the value in Other.LR.
2328 LIS->pruneValue(Other.LR, Def, &EndPoints);
2329 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
2330 // instructions are only inserted to provide a live-out value for PHI
2331 // predecessors, so the instruction should simply go away once its value
2332 // has been replaced.
2333 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2334 bool EraseImpDef = OtherV.ErasableImplicitDef &&
2335 OtherV.Resolution == CR_Keep;
2336 if (!Def.isBlock()) {
2338 // Remove <def,read-undef> flags. This def is now a partial redef.
2339 // Also remove <def,dead> flags since the joined live range will
2340 // continue past this instruction.
2341 for (MachineOperand &MO :
2342 Indexes->getInstructionFromIndex(Def)->operands()) {
2343 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
2344 MO.setIsUndef(EraseImpDef);
2345 MO.setIsDead(false);
2349 // This value will reach instructions below, but we need to make sure
2350 // the live range also reaches the instruction at Def.
2352 EndPoints.push_back(Def);
2354 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.Reg) << " at " << Def
2355 << ": " << Other.LR << '\n');
2360 if (isPrunedValue(i, Other)) {
2361 // This value is ultimately a copy of a pruned value in LR or Other.LR.
2362 // We can no longer trust the value mapping computed by
2363 // computeAssignment(), the value that was originally copied could have
2365 LIS->pruneValue(LR, Def, &EndPoints);
2366 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(Reg) << " at "
2367 << Def << ": " << LR << '\n');
2372 llvm_unreachable("Unresolved conflicts");
2377 void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask)
2379 // Look for values being erased.
2380 bool DidPrune = false;
2381 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2382 if (Vals[i].Resolution != CR_Erase)
2385 // Check subranges at the point where the copy will be removed.
2386 SlotIndex Def = LR.getValNumInfo(i)->def;
2387 for (LiveInterval::SubRange &S : LI.subranges()) {
2388 LiveQueryResult Q = S.Query(Def);
2390 // If a subrange starts at the copy then an undefined value has been
2391 // copied and we must remove that subrange value as well.
2392 VNInfo *ValueOut = Q.valueOutOrDead();
2393 if (ValueOut != nullptr && Q.valueIn() == nullptr) {
2394 DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)
2395 << " at " << Def << "\n");
2396 LIS->pruneValue(S, Def, nullptr);
2398 // Mark value number as unused.
2399 ValueOut->markUnused();
2402 // If a subrange ends at the copy, then a value was copied but only
2403 // partially used later. Shrink the subregister range appropriately.
2404 if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
2405 DEBUG(dbgs() << "\t\tDead uses at sublane " << PrintLaneMask(S.LaneMask)
2406 << " at " << Def << "\n");
2407 ShrinkMask |= S.LaneMask;
2412 LI.removeEmptySubRanges();
2415 void JoinVals::removeImplicitDefs() {
2416 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2418 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
2421 VNInfo *VNI = LR.getValNumInfo(i);
2423 LR.removeValNo(VNI);
2427 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2428 SmallVectorImpl<unsigned> &ShrinkRegs) {
2429 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2430 // Get the def location before markUnused() below invalidates it.
2431 SlotIndex Def = LR.getValNumInfo(i)->def;
2432 switch (Vals[i].Resolution) {
2434 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
2435 // longer. The IMPLICIT_DEF instructions are only inserted by
2436 // PHIElimination to guarantee that all PHI predecessors have a value.
2437 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
2439 // Remove value number i from LR.
2440 VNInfo *VNI = LR.getValNumInfo(i);
2441 LR.removeValNo(VNI);
2442 // Note that this VNInfo is reused and still referenced in NewVNInfo,
2443 // make it appear like an unused value number.
2445 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n');
2450 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2451 assert(MI && "No instruction to erase");
2453 unsigned Reg = MI->getOperand(1).getReg();
2454 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
2455 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
2456 ShrinkRegs.push_back(Reg);
2458 ErasedInstrs.insert(MI);
2459 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
2460 LIS->RemoveMachineInstrFromMaps(MI);
2461 MI->eraseFromParent();
2470 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
2471 LaneBitmask LaneMask,
2472 const CoalescerPair &CP) {
2473 SmallVector<VNInfo*, 16> NewVNInfo;
2474 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
2475 NewVNInfo, CP, LIS, TRI, true, true);
2476 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
2477 NewVNInfo, CP, LIS, TRI, true, true);
2479 // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
2480 // We should be able to resolve all conflicts here as we could successfully do
2481 // it on the mainrange already. There is however a problem when multiple
2482 // ranges get mapped to the "overflow" lane mask bit which creates unexpected
2484 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
2485 // We already determined that it is legal to merge the intervals, so this
2486 // should never fail.
2487 llvm_unreachable("*** Couldn't join subrange!\n");
2489 if (!LHSVals.resolveConflicts(RHSVals) ||
2490 !RHSVals.resolveConflicts(LHSVals)) {
2491 // We already determined that it is legal to merge the intervals, so this
2492 // should never fail.
2493 llvm_unreachable("*** Couldn't join subrange!\n");
2496 // The merging algorithm in LiveInterval::join() can't handle conflicting
2497 // value mappings, so we need to remove any live ranges that overlap a
2498 // CR_Replace resolution. Collect a set of end points that can be used to
2499 // restore the live range after joining.
2500 SmallVector<SlotIndex, 8> EndPoints;
2501 LHSVals.pruneValues(RHSVals, EndPoints, false);
2502 RHSVals.pruneValues(LHSVals, EndPoints, false);
2504 LHSVals.removeImplicitDefs();
2505 RHSVals.removeImplicitDefs();
2510 // Join RRange into LHS.
2511 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
2514 DEBUG(dbgs() << "\t\tjoined lanes: " << LRange << "\n");
2515 if (EndPoints.empty())
2518 // Recompute the parts of the live range we had to remove because of
2519 // CR_Replace conflicts.
2520 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2521 << " points: " << LRange << '\n');
2522 LIS->extendToIndices(LRange, EndPoints);
2525 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
2526 const LiveRange &ToMerge,
2527 LaneBitmask LaneMask,
2528 CoalescerPair &CP) {
2529 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2530 for (LiveInterval::SubRange &R : LI.subranges()) {
2531 LaneBitmask RMask = R.LaneMask;
2532 // LaneMask of subregisters common to subrange R and ToMerge.
2533 LaneBitmask Common = RMask & LaneMask;
2534 // There is nothing to do without common subregs.
2538 DEBUG(dbgs() << "\t\tCopy+Merge " << PrintLaneMask(RMask) << " into "
2539 << PrintLaneMask(Common) << '\n');
2540 // LaneMask of subregisters contained in the R range but not in ToMerge,
2541 // they have to split into their own subrange.
2542 LaneBitmask LRest = RMask & ~LaneMask;
2543 LiveInterval::SubRange *CommonRange;
2546 DEBUG(dbgs() << "\t\tReduce Lane to " << PrintLaneMask(LRest) << '\n');
2547 // Duplicate SubRange for newly merged common stuff.
2548 CommonRange = LI.createSubRangeFrom(Allocator, Common, R);
2550 // Reuse the existing range.
2551 R.LaneMask = Common;
2554 LiveRange RangeCopy(ToMerge, Allocator);
2555 joinSubRegRanges(*CommonRange, RangeCopy, Common, CP);
2559 if (LaneMask != 0) {
2560 DEBUG(dbgs() << "\t\tNew Lane " << PrintLaneMask(LaneMask) << '\n');
2561 LI.createSubRangeFrom(Allocator, LaneMask, ToMerge);
2565 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
2566 SmallVector<VNInfo*, 16> NewVNInfo;
2567 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
2568 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
2569 bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
2570 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), 0, NewVNInfo, CP, LIS,
2571 TRI, false, TrackSubRegLiveness);
2572 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), 0, NewVNInfo, CP, LIS,
2573 TRI, false, TrackSubRegLiveness);
2575 DEBUG(dbgs() << "\t\tRHS = " << RHS
2576 << "\n\t\tLHS = " << LHS
2579 // First compute NewVNInfo and the simple value mappings.
2580 // Detect impossible conflicts early.
2581 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2584 // Some conflicts can only be resolved after all values have been mapped.
2585 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2588 // All clear, the live ranges can be merged.
2589 if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
2590 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2592 // Transform lanemasks from the LHS to masks in the coalesced register and
2593 // create initial subranges if necessary.
2594 unsigned DstIdx = CP.getDstIdx();
2595 if (!LHS.hasSubRanges()) {
2596 LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
2597 : TRI->getSubRegIndexLaneMask(DstIdx);
2598 // LHS must support subregs or we wouldn't be in this codepath.
2600 LHS.createSubRangeFrom(Allocator, Mask, LHS);
2601 } else if (DstIdx != 0) {
2602 // Transform LHS lanemasks to new register class if necessary.
2603 for (LiveInterval::SubRange &R : LHS.subranges()) {
2604 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
2608 DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
2609 << ' ' << LHS << '\n');
2611 // Determine lanemasks of RHS in the coalesced register and merge subranges.
2612 unsigned SrcIdx = CP.getSrcIdx();
2613 if (!RHS.hasSubRanges()) {
2614 LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
2615 : TRI->getSubRegIndexLaneMask(SrcIdx);
2616 mergeSubRangeInto(LHS, RHS, Mask, CP);
2618 // Pair up subranges and merge.
2619 for (LiveInterval::SubRange &R : RHS.subranges()) {
2620 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
2621 mergeSubRangeInto(LHS, R, Mask, CP);
2624 DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
2626 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
2627 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
2630 // The merging algorithm in LiveInterval::join() can't handle conflicting
2631 // value mappings, so we need to remove any live ranges that overlap a
2632 // CR_Replace resolution. Collect a set of end points that can be used to
2633 // restore the live range after joining.
2634 SmallVector<SlotIndex, 8> EndPoints;
2635 LHSVals.pruneValues(RHSVals, EndPoints, true);
2636 RHSVals.pruneValues(LHSVals, EndPoints, true);
2638 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
2639 // registers to require trimming.
2640 SmallVector<unsigned, 8> ShrinkRegs;
2641 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2642 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2643 while (!ShrinkRegs.empty())
2644 shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
2646 // Join RHS into LHS.
2647 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
2649 // Kill flags are going to be wrong if the live ranges were overlapping.
2650 // Eventually, we should simply clear all kill flags when computing live
2651 // ranges. They are reinserted after register allocation.
2652 MRI->clearKillFlags(LHS.reg);
2653 MRI->clearKillFlags(RHS.reg);
2655 if (!EndPoints.empty()) {
2656 // Recompute the parts of the live range we had to remove because of
2657 // CR_Replace conflicts.
2658 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2659 << " points: " << LHS << '\n');
2660 LIS->extendToIndices((LiveRange&)LHS, EndPoints);
2666 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
2667 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
2671 /// Information concerning MBB coalescing priority.
2672 struct MBBPriorityInfo {
2673 MachineBasicBlock *MBB;
2677 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
2678 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
2682 /// C-style comparator that sorts first based on the loop depth of the basic
2683 /// block (the unsigned), and then on the MBB number.
2685 /// EnableGlobalCopies assumes that the primary sort key is loop depth.
2686 static int compareMBBPriority(const MBBPriorityInfo *LHS,
2687 const MBBPriorityInfo *RHS) {
2688 // Deeper loops first
2689 if (LHS->Depth != RHS->Depth)
2690 return LHS->Depth > RHS->Depth ? -1 : 1;
2692 // Try to unsplit critical edges next.
2693 if (LHS->IsSplit != RHS->IsSplit)
2694 return LHS->IsSplit ? -1 : 1;
2696 // Prefer blocks that are more connected in the CFG. This takes care of
2697 // the most difficult copies first while intervals are short.
2698 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
2699 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
2701 return cl > cr ? -1 : 1;
2703 // As a last resort, sort by block number.
2704 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
2707 /// \returns true if the given copy uses or defines a local live range.
2708 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
2709 if (!Copy->isCopy())
2712 if (Copy->getOperand(1).isUndef())
2715 unsigned SrcReg = Copy->getOperand(1).getReg();
2716 unsigned DstReg = Copy->getOperand(0).getReg();
2717 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
2718 || TargetRegisterInfo::isPhysicalRegister(DstReg))
2721 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
2722 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
2725 bool RegisterCoalescer::
2726 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2727 bool Progress = false;
2728 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2731 // Skip instruction pointers that have already been erased, for example by
2732 // dead code elimination.
2733 if (ErasedInstrs.erase(CurrList[i])) {
2734 CurrList[i] = nullptr;
2738 bool Success = joinCopy(CurrList[i], Again);
2739 Progress |= Success;
2740 if (Success || !Again)
2741 CurrList[i] = nullptr;
2746 /// Check if DstReg is a terminal node.
2747 /// I.e., it does not have any affinity other than \p Copy.
2748 static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy,
2749 const MachineRegisterInfo *MRI) {
2750 assert(Copy.isCopyLike());
2751 // Check if the destination of this copy as any other affinity.
2752 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
2753 if (&MI != &Copy && MI.isCopyLike())
2758 bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
2759 assert(Copy.isCopyLike());
2760 if (!UseTerminalRule)
2762 unsigned DstReg, DstSubReg, SrcReg, SrcSubReg;
2763 isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg);
2764 // Check if the destination of this copy has any other affinity.
2765 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
2766 // If SrcReg is a physical register, the copy won't be coalesced.
2767 // Ignoring it may have other side effect (like missing
2768 // rematerialization). So keep it.
2769 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
2770 !isTerminalReg(DstReg, Copy, MRI))
2773 // DstReg is a terminal node. Check if it interferes with any other
2774 // copy involving SrcReg.
2775 const MachineBasicBlock *OrigBB = Copy.getParent();
2776 const LiveInterval &DstLI = LIS->getInterval(DstReg);
2777 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
2778 // Technically we should check if the weight of the new copy is
2779 // interesting compared to the other one and update the weight
2780 // of the copies accordingly. However, this would only work if
2781 // we would gather all the copies first then coalesce, whereas
2782 // right now we interleave both actions.
2783 // For now, just consider the copies that are in the same block.
2784 if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
2786 unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg;
2787 isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
2789 if (OtherReg == SrcReg)
2790 OtherReg = OtherSrcReg;
2791 // Check if OtherReg is a non-terminal.
2792 if (TargetRegisterInfo::isPhysicalRegister(OtherReg) ||
2793 isTerminalReg(OtherReg, MI, MRI))
2795 // Check that OtherReg interfere with DstReg.
2796 if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
2797 DEBUG(dbgs() << "Apply terminal rule for: " << PrintReg(DstReg) << '\n');
2805 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2806 DEBUG(dbgs() << MBB->getName() << ":\n");
2808 // Collect all copy-like instructions in MBB. Don't start coalescing anything
2809 // yet, it might invalidate the iterator.
2810 const unsigned PrevSize = WorkList.size();
2811 if (JoinGlobalCopies) {
2812 SmallVector<MachineInstr*, 2> LocalTerminals;
2813 SmallVector<MachineInstr*, 2> GlobalTerminals;
2814 // Coalesce copies bottom-up to coalesce local defs before local uses. They
2815 // are not inherently easier to resolve, but slightly preferable until we
2816 // have local live range splitting. In particular this is required by
2817 // cmp+jmp macro fusion.
2818 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2820 if (!MII->isCopyLike())
2822 bool ApplyTerminalRule = applyTerminalRule(*MII);
2823 if (isLocalCopy(&(*MII), LIS)) {
2824 if (ApplyTerminalRule)
2825 LocalTerminals.push_back(&(*MII));
2827 LocalWorkList.push_back(&(*MII));
2829 if (ApplyTerminalRule)
2830 GlobalTerminals.push_back(&(*MII));
2832 WorkList.push_back(&(*MII));
2835 // Append the copies evicted by the terminal rule at the end of the list.
2836 LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
2837 WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
2840 SmallVector<MachineInstr*, 2> Terminals;
2841 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2843 if (MII->isCopyLike()) {
2844 if (applyTerminalRule(*MII))
2845 Terminals.push_back(&(*MII));
2847 WorkList.push_back(MII);
2849 // Append the copies evicted by the terminal rule at the end of the list.
2850 WorkList.append(Terminals.begin(), Terminals.end());
2852 // Try coalescing the collected copies immediately, and remove the nulls.
2853 // This prevents the WorkList from getting too large since most copies are
2854 // joinable on the first attempt.
2855 MutableArrayRef<MachineInstr*>
2856 CurrList(WorkList.begin() + PrevSize, WorkList.end());
2857 if (copyCoalesceWorkList(CurrList))
2858 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2859 (MachineInstr*)nullptr), WorkList.end());
2862 void RegisterCoalescer::coalesceLocals() {
2863 copyCoalesceWorkList(LocalWorkList);
2864 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2865 if (LocalWorkList[j])
2866 WorkList.push_back(LocalWorkList[j]);
2868 LocalWorkList.clear();
2871 void RegisterCoalescer::joinAllIntervals() {
2872 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2873 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2875 std::vector<MBBPriorityInfo> MBBs;
2876 MBBs.reserve(MF->size());
2877 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2878 MachineBasicBlock *MBB = &*I;
2879 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2880 JoinSplitEdges && isSplitEdge(MBB)));
2882 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
2884 // Coalesce intervals in MBB priority order.
2885 unsigned CurrDepth = UINT_MAX;
2886 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2887 // Try coalescing the collected local copies for deeper loops.
2888 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
2890 CurrDepth = MBBs[i].Depth;
2892 copyCoalesceInMBB(MBBs[i].MBB);
2896 // Joining intervals can allow other intervals to be joined. Iteratively join
2897 // until we make no progress.
2898 while (copyCoalesceWorkList(WorkList))
2902 void RegisterCoalescer::releaseMemory() {
2903 ErasedInstrs.clear();
2906 InflateRegs.clear();
2909 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2911 MRI = &fn.getRegInfo();
2912 TM = &fn.getTarget();
2913 const TargetSubtargetInfo &STI = fn.getSubtarget();
2914 TRI = STI.getRegisterInfo();
2915 TII = STI.getInstrInfo();
2916 LIS = &getAnalysis<LiveIntervals>();
2917 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2918 Loops = &getAnalysis<MachineLoopInfo>();
2919 if (EnableGlobalCopies == cl::BOU_UNSET)
2920 JoinGlobalCopies = STI.enableJoinGlobalCopies();
2922 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2924 // The MachineScheduler does not currently require JoinSplitEdges. This will
2925 // either be enabled unconditionally or replaced by a more general live range
2926 // splitting optimization.
2927 JoinSplitEdges = EnableJoinSplits;
2929 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2930 << "********** Function: " << MF->getName() << '\n');
2932 if (VerifyCoalescing)
2933 MF->verify(this, "Before register coalescing");
2935 RegClassInfo.runOnMachineFunction(fn);
2937 // Join (coalesce) intervals if requested.
2941 // After deleting a lot of copies, register classes may be less constrained.
2942 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2944 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2945 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2947 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2948 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2949 unsigned Reg = InflateRegs[i];
2950 if (MRI->reg_nodbg_empty(Reg))
2952 if (MRI->recomputeRegClass(Reg)) {
2953 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2954 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
2957 LiveInterval &LI = LIS->getInterval(Reg);
2958 if (LI.hasSubRanges()) {
2959 // If the inflated register class does not support subregisters anymore
2960 // remove the subranges.
2961 if (!MRI->shouldTrackSubRegLiveness(Reg)) {
2962 LI.clearSubRanges();
2965 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2966 // If subranges are still supported, then the same subregs
2967 // should still be supported.
2968 for (LiveInterval::SubRange &S : LI.subranges()) {
2969 assert((S.LaneMask & ~MaxMask) == 0);
2978 if (VerifyCoalescing)
2979 MF->verify(this, "After register coalescing");
2983 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {