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/Format.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "regalloc"
47 STATISTIC(numJoins , "Number of interval joins performed");
48 STATISTIC(numCrossRCs , "Number of cross class joins performed");
49 STATISTIC(numCommutes , "Number of instruction commuting performed");
50 STATISTIC(numExtends , "Number of copies extended");
51 STATISTIC(NumReMats , "Number of instructions re-materialized");
52 STATISTIC(NumInflated , "Number of register classes inflated");
53 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
54 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
57 EnableJoining("join-liveintervals",
58 cl::desc("Coalesce copies (default=true)"),
61 /// Temporary flag to test critical edge unsplitting.
63 EnableJoinSplits("join-splitedges",
64 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
66 /// Temporary flag to test global copy optimization.
67 static cl::opt<cl::boolOrDefault>
68 EnableGlobalCopies("join-globalcopies",
69 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
70 cl::init(cl::BOU_UNSET), cl::Hidden);
73 VerifyCoalescing("verify-coalescing",
74 cl::desc("Verify machine instrs before and after register coalescing"),
78 class RegisterCoalescer : public MachineFunctionPass,
79 private LiveRangeEdit::Delegate {
81 MachineRegisterInfo* MRI;
82 const TargetMachine* TM;
83 const TargetRegisterInfo* TRI;
84 const TargetInstrInfo* TII;
86 const MachineLoopInfo* Loops;
88 RegisterClassInfo RegClassInfo;
90 /// A LaneMask to remember on which subregister live ranges we need to call
91 /// shrinkToUses() later.
94 /// True if the main range of the currently coalesced intervals should be
95 /// checked for smaller live intervals.
98 /// \brief True if the coalescer should aggressively coalesce global copies
99 /// in favor of keeping local copies.
100 bool JoinGlobalCopies;
102 /// \brief True if the coalescer should aggressively coalesce fall-thru
103 /// blocks exclusively containing copies.
106 /// Copy instructions yet to be coalesced.
107 SmallVector<MachineInstr*, 8> WorkList;
108 SmallVector<MachineInstr*, 8> LocalWorkList;
110 /// Set of instruction pointers that have been erased, and
111 /// that may be present in WorkList.
112 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
114 /// Dead instructions that are about to be deleted.
115 SmallVector<MachineInstr*, 8> DeadDefs;
117 /// Virtual registers to be considered for register class inflation.
118 SmallVector<unsigned, 8> InflateRegs;
120 /// Recursively eliminate dead defs in DeadDefs.
121 void eliminateDeadDefs();
123 /// LiveRangeEdit callback for eliminateDeadDefs().
124 void LRE_WillEraseInstruction(MachineInstr *MI) override;
126 /// Coalesce the LocalWorkList.
127 void coalesceLocals();
129 /// Join compatible live intervals
130 void joinAllIntervals();
132 /// Coalesce copies in the specified MBB, putting
133 /// copies that cannot yet be coalesced into WorkList.
134 void copyCoalesceInMBB(MachineBasicBlock *MBB);
136 /// Tries to coalesce all copies in CurrList. Returns true if any progress
138 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
140 /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
141 /// src/dst of the copy instruction CopyMI. This returns true if the copy
142 /// was successfully coalesced away. If it is not currently possible to
143 /// coalesce this interval, but it may be possible if other things get
144 /// coalesced, then it returns true by reference in 'Again'.
145 bool joinCopy(MachineInstr *TheCopy, bool &Again);
147 /// Attempt to join these two intervals. On failure, this
148 /// returns false. The output "SrcInt" will not have been modified, so we
149 /// can use this information below to update aliases.
150 bool joinIntervals(CoalescerPair &CP);
152 /// Attempt joining two virtual registers. Return true on success.
153 bool joinVirtRegs(CoalescerPair &CP);
155 /// Attempt joining with a reserved physreg.
156 bool joinReservedPhysReg(CoalescerPair &CP);
158 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
159 /// Subranges in @p LI which only partially interfere with the desired
160 /// LaneMask are split as necessary. @p LaneMask are the lanes that
161 /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
162 /// lanemasks already adjusted to the coalesced register.
163 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
164 unsigned LaneMask, CoalescerPair &CP);
166 /// Join the liveranges of two subregisters. Joins @p RRange into
167 /// @p LRange, @p RRange may be invalid afterwards.
168 void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
169 unsigned LaneMask, const CoalescerPair &CP);
171 /// We found a non-trivially-coalescable copy. If the source value number is
172 /// defined by a copy from the destination reg see if we can merge these two
173 /// destination reg valno# into a single value number, eliminating a copy.
174 /// This returns true if an interval was modified.
175 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
177 /// Return true if there are definitions of IntB
178 /// other than BValNo val# that can reach uses of AValno val# of IntA.
179 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
180 VNInfo *AValNo, VNInfo *BValNo);
182 /// We found a non-trivially-coalescable copy.
183 /// If the source value number is defined by a commutable instruction and
184 /// its other operand is coalesced to the copy dest register, see if we
185 /// can transform the copy into a noop by commuting the definition.
186 /// This returns true if an interval was modified.
187 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
189 /// If the source of a copy is defined by a
190 /// trivial computation, replace the copy by rematerialize the definition.
191 bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI,
194 /// Return true if a copy involving a physreg should be joined.
195 bool canJoinPhys(const CoalescerPair &CP);
197 /// Replace all defs and uses of SrcReg to DstReg and update the subregister
198 /// number if it is not zero. If DstReg is a physical register and the
199 /// existing subregister number of the def / use being updated is not zero,
200 /// make sure to set it to the correct physical subregister.
201 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
203 /// Handle copies of undef values.
204 /// Returns true if @p CopyMI was a copy of an undef value and eliminated.
205 bool eliminateUndefCopy(MachineInstr *CopyMI);
208 static char ID; ///< Class identification, replacement for typeinfo
209 RegisterCoalescer() : MachineFunctionPass(ID) {
210 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
213 void getAnalysisUsage(AnalysisUsage &AU) const override;
215 void releaseMemory() override;
217 /// This is the pass entry point.
218 bool runOnMachineFunction(MachineFunction&) override;
220 /// Implement the dump method.
221 void print(raw_ostream &O, const Module* = nullptr) const override;
223 } // end anonymous namespace
225 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
227 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
228 "Simple Register Coalescing", false, false)
229 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
230 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
231 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
232 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
233 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
234 "Simple Register Coalescing", false, false)
236 char RegisterCoalescer::ID = 0;
238 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
239 unsigned &Src, unsigned &Dst,
240 unsigned &SrcSub, unsigned &DstSub) {
242 Dst = MI->getOperand(0).getReg();
243 DstSub = MI->getOperand(0).getSubReg();
244 Src = MI->getOperand(1).getReg();
245 SrcSub = MI->getOperand(1).getSubReg();
246 } else if (MI->isSubregToReg()) {
247 Dst = MI->getOperand(0).getReg();
248 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
249 MI->getOperand(3).getImm());
250 Src = MI->getOperand(2).getReg();
251 SrcSub = MI->getOperand(2).getSubReg();
257 /// Return true if this block should be vacated by the coalescer to eliminate
258 /// branches. The important cases to handle in the coalescer are critical edges
259 /// split during phi elimination which contain only copies. Simple blocks that
260 /// contain non-branches should also be vacated, but this can be handled by an
261 /// earlier pass similar to early if-conversion.
262 static bool isSplitEdge(const MachineBasicBlock *MBB) {
263 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
266 for (const auto &MI : *MBB) {
267 if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
273 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
277 Flipped = CrossClass = false;
279 unsigned Src, Dst, SrcSub, DstSub;
280 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
282 Partial = SrcSub || DstSub;
284 // If one register is a physreg, it must be Dst.
285 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
286 if (TargetRegisterInfo::isPhysicalRegister(Dst))
289 std::swap(SrcSub, DstSub);
293 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
295 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
296 // Eliminate DstSub on a physreg.
298 Dst = TRI.getSubReg(Dst, DstSub);
299 if (!Dst) return false;
303 // Eliminate SrcSub by picking a corresponding Dst superregister.
305 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
306 if (!Dst) return false;
307 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
311 // Both registers are virtual.
312 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
313 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
315 // Both registers have subreg indices.
316 if (SrcSub && DstSub) {
317 // Copies between different sub-registers are never coalescable.
318 if (Src == Dst && SrcSub != DstSub)
321 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
326 // SrcReg will be merged with a sub-register of DstReg.
328 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
330 // DstReg will be merged with a sub-register of SrcReg.
332 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
334 // This is a straight copy without sub-registers.
335 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
338 // The combined constraint may be impossible to satisfy.
342 // Prefer SrcReg to be a sub-register of DstReg.
343 // FIXME: Coalescer should support subregs symmetrically.
344 if (DstIdx && !SrcIdx) {
346 std::swap(SrcIdx, DstIdx);
350 CrossClass = NewRC != DstRC || NewRC != SrcRC;
352 // Check our invariants
353 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
354 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
355 "Cannot have a physical SubIdx");
361 bool CoalescerPair::flip() {
362 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
364 std::swap(SrcReg, DstReg);
365 std::swap(SrcIdx, DstIdx);
370 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
373 unsigned Src, Dst, SrcSub, DstSub;
374 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
377 // Find the virtual register that is SrcReg.
380 std::swap(SrcSub, DstSub);
381 } else if (Src != SrcReg) {
385 // Now check that Dst matches DstReg.
386 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
387 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
389 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
390 // DstSub could be set for a physreg from INSERT_SUBREG.
392 Dst = TRI.getSubReg(Dst, DstSub);
395 return DstReg == Dst;
396 // This is a partial register copy. Check that the parts match.
397 return TRI.getSubReg(DstReg, SrcSub) == Dst;
399 // DstReg is virtual.
402 // Registers match, do the subregisters line up?
403 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
404 TRI.composeSubRegIndices(DstIdx, DstSub);
408 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
409 AU.setPreservesCFG();
410 AU.addRequired<AliasAnalysis>();
411 AU.addRequired<LiveIntervals>();
412 AU.addPreserved<LiveIntervals>();
413 AU.addPreserved<SlotIndexes>();
414 AU.addRequired<MachineLoopInfo>();
415 AU.addPreserved<MachineLoopInfo>();
416 AU.addPreservedID(MachineDominatorsID);
417 MachineFunctionPass::getAnalysisUsage(AU);
420 void RegisterCoalescer::eliminateDeadDefs() {
421 SmallVector<unsigned, 8> NewRegs;
422 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
423 nullptr, this).eliminateDeadDefs(DeadDefs);
426 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
427 // MI may be in WorkList. Make sure we don't visit it.
428 ErasedInstrs.insert(MI);
431 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
432 MachineInstr *CopyMI) {
433 assert(!CP.isPartial() && "This doesn't work for partial copies.");
434 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
437 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
439 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
440 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
442 // We have a non-trivially-coalescable copy with IntA being the source and
443 // IntB being the dest, thus this defines a value number in IntB. If the
444 // source value number (in IntA) is defined by a copy from B, see if we can
445 // merge these two pieces of B into a single value number, eliminating a copy.
450 // B1 = A3 <- this copy
452 // In this case, B0 can be extended to where the B1 copy lives, allowing the
453 // B1 value number to be replaced with B0 (which simplifies the B
456 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
457 // the example above.
458 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
459 if (BS == IntB.end()) return false;
460 VNInfo *BValNo = BS->valno;
462 // Get the location that B is defined at. Two options: either this value has
463 // an unknown definition point or it is defined at CopyIdx. If unknown, we
465 if (BValNo->def != CopyIdx) return false;
467 // AValNo is the value number in A that defines the copy, A3 in the example.
468 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
469 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
470 // The live segment might not exist after fun with physreg coalescing.
471 if (AS == IntA.end()) return false;
472 VNInfo *AValNo = AS->valno;
474 // If AValNo is defined as a copy from IntB, we can potentially process this.
475 // Get the instruction that defines this value number.
476 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
477 // Don't allow any partial copies, even if isCoalescable() allows them.
478 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
481 // Get the Segment in IntB that this value number starts with.
482 LiveInterval::iterator ValS =
483 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
484 if (ValS == IntB.end())
487 // Make sure that the end of the live segment is inside the same block as
489 MachineInstr *ValSEndInst =
490 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
491 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
494 // Okay, we now know that ValS ends in the same block that the CopyMI
495 // live-range starts. If there are no intervening live segments between them
496 // in IntB, we can merge them.
497 if (ValS+1 != BS) return false;
499 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
501 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
502 // We are about to delete CopyMI, so need to remove it as the 'instruction
503 // that defines this value #'. Update the valnum with the new defining
505 BValNo->def = FillerStart;
507 // Okay, we can merge them. We need to insert a new liverange:
508 // [ValS.end, BS.begin) of either value number, then we merge the
509 // two value numbers.
510 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
512 // Okay, merge "B1" into the same value number as "B0".
513 if (BValNo != ValS->valno)
514 IntB.MergeValueNumberInto(BValNo, ValS->valno);
516 // Do the same for the subregister segments.
517 for (LiveInterval::SubRange &S : IntB.subranges()) {
518 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
519 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
520 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
521 if (SubBValNo != SubValSNo)
522 S.MergeValueNumberInto(SubBValNo, SubValSNo);
525 DEBUG(dbgs() << " result = " << IntB << '\n');
527 // If the source instruction was killing the source register before the
528 // merge, unset the isKill marker given the live range has been extended.
529 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
531 ValSEndInst->getOperand(UIdx).setIsKill(false);
534 // Rewrite the copy. If the copy instruction was killing the destination
535 // register before the merge, find the last use and trim the live range. That
536 // will also add the isKill marker.
537 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
538 if (AS->end == CopyIdx)
539 LIS->shrinkToUses(&IntA);
545 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
549 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
551 if (LIS->hasPHIKill(IntA, AValNo))
554 for (LiveRange::Segment &ASeg : IntA.segments) {
555 if (ASeg.valno != AValNo) continue;
556 LiveInterval::iterator BI =
557 std::upper_bound(IntB.begin(), IntB.end(), ASeg.start);
558 if (BI != IntB.begin())
560 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
561 if (BI->valno == BValNo)
563 if (BI->start <= ASeg.start && BI->end > ASeg.start)
565 if (BI->start > ASeg.start && BI->start < ASeg.end)
572 /// Copy segements with value number @p SrcValNo from liverange @p Src to live
573 /// range @Dst and use value number @p DstValNo there.
574 static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo,
575 const LiveRange &Src, const VNInfo *SrcValNo)
577 for (const LiveRange::Segment &S : Src.segments) {
578 if (S.valno != SrcValNo)
580 Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo));
584 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
585 MachineInstr *CopyMI) {
586 assert(!CP.isPhys());
589 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
591 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
593 // We found a non-trivially-coalescable copy with IntA being the source and
594 // IntB being the dest, thus this defines a value number in IntB. If the
595 // source value number (in IntA) is defined by a commutable instruction and
596 // its other operand is coalesced to the copy dest register, see if we can
597 // transform the copy into a noop by commuting the definition. For example,
599 // A3 = op A2 B0<kill>
601 // B1 = A3 <- this copy
603 // = op A3 <- more uses
607 // B2 = op B0 A2<kill>
609 // B1 = B2 <- now an identity copy
611 // = op B2 <- more uses
613 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
614 // the example above.
615 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
616 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
617 assert(BValNo != nullptr && BValNo->def == CopyIdx);
619 // AValNo is the value number in A that defines the copy, A3 in the example.
620 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
621 assert(AValNo && !AValNo->isUnused() && "COPY source not live");
622 if (AValNo->isPHIDef())
624 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
627 if (!DefMI->isCommutable())
629 // If DefMI is a two-address instruction then commuting it will change the
630 // destination register.
631 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
632 assert(DefIdx != -1);
634 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
636 unsigned Op1, Op2, NewDstIdx;
637 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
641 else if (Op2 == UseOpIdx)
646 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
647 unsigned NewReg = NewDstMO.getReg();
648 if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
651 // Make sure there are no other definitions of IntB that would reach the
652 // uses which the new definition can reach.
653 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
656 // If some of the uses of IntA.reg is already coalesced away, return false.
657 // It's not possible to determine whether it's safe to perform the coalescing.
658 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
659 MachineInstr *UseMI = MO.getParent();
660 unsigned OpNo = &MO - &UseMI->getOperand(0);
661 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
662 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
663 if (US == IntA.end() || US->valno != AValNo)
665 // If this use is tied to a def, we can't rewrite the register.
666 if (UseMI->isRegTiedToDefOperand(OpNo))
670 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
673 // At this point we have decided that it is legal to do this
674 // transformation. Start by commuting the instruction.
675 MachineBasicBlock *MBB = DefMI->getParent();
676 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
679 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
680 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
681 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
683 if (NewMI != DefMI) {
684 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
685 MachineBasicBlock::iterator Pos = DefMI;
686 MBB->insert(Pos, NewMI);
690 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
699 // Update uses of IntA of the specific Val# with IntB.
700 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
702 UI != UE; /* ++UI is below because of possible MI removal */) {
703 MachineOperand &UseMO = *UI;
707 MachineInstr *UseMI = UseMO.getParent();
708 if (UseMI->isDebugValue()) {
709 // FIXME These don't have an instruction index. Not clear we have enough
710 // info to decide whether to do this replacement or not. For now do it.
711 UseMO.setReg(NewReg);
714 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
715 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
716 assert(US != IntA.end() && "Use must be live");
717 if (US->valno != AValNo)
719 // Kill flags are no longer accurate. They are recomputed after RA.
720 UseMO.setIsKill(false);
721 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
722 UseMO.substPhysReg(NewReg, *TRI);
724 UseMO.setReg(NewReg);
727 if (!UseMI->isCopy())
729 if (UseMI->getOperand(0).getReg() != IntB.reg ||
730 UseMI->getOperand(0).getSubReg())
733 // This copy will become a noop. If it's defining a new val#, merge it into
735 SlotIndex DefIdx = UseIdx.getRegSlot();
736 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
739 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
740 assert(DVNI->def == DefIdx);
741 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
742 for (LiveInterval::SubRange &S : IntB.subranges()) {
743 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
746 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
747 assert(SubBValNo->def == CopyIdx);
748 VNInfo *Merged = S.MergeValueNumberInto(SubBValNo, SubDVNI);
749 Merged->def = CopyIdx;
752 ErasedInstrs.insert(UseMI);
753 LIS->RemoveMachineInstrFromMaps(UseMI);
754 UseMI->eraseFromParent();
757 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
759 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
760 if (IntB.hasSubRanges()) {
761 if (!IntA.hasSubRanges()) {
762 unsigned Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
763 IntA.createSubRangeFrom(Allocator, Mask, IntA);
765 SlotIndex AIdx = CopyIdx.getRegSlot(true);
766 for (LiveInterval::SubRange &SA : IntA.subranges()) {
767 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
768 assert(ASubValNo != nullptr);
770 unsigned AMask = SA.LaneMask;
771 for (LiveInterval::SubRange &SB : IntB.subranges()) {
772 unsigned BMask = SB.LaneMask;
773 unsigned Common = BMask & AMask;
778 dbgs() << format("\t\tCopy+Merge %04X into %04X\n", BMask, Common));
779 unsigned BRest = BMask & ~AMask;
780 LiveInterval::SubRange *CommonRange;
783 DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", BRest));
784 // Duplicate SubRange for newly merged common stuff.
785 CommonRange = IntB.createSubRangeFrom(Allocator, Common, SB);
787 // We van reuse the L SubRange.
788 SB.LaneMask = Common;
791 LiveRange RangeCopy(SB, Allocator);
793 VNInfo *BSubValNo = CommonRange->getVNInfoAt(CopyIdx);
794 assert(BSubValNo->def == CopyIdx);
795 BSubValNo->def = ASubValNo->def;
796 addSegmentsWithValNo(*CommonRange, BSubValNo, SA, ASubValNo);
800 DEBUG(dbgs() << format("\t\tNew Lane %04X\n", AMask));
801 LiveRange *NewRange = IntB.createSubRange(Allocator, AMask);
802 VNInfo *BSubValNo = NewRange->getNextValue(CopyIdx, Allocator);
803 addSegmentsWithValNo(*NewRange, BSubValNo, SA, ASubValNo);
805 SA.removeValNo(ASubValNo);
809 BValNo->def = AValNo->def;
810 addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
811 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
813 IntA.removeValNo(AValNo);
814 // Remove valuenos in subranges (the A+B have subranges case has already been
816 if (!IntB.hasSubRanges()) {
817 SlotIndex AIdx = CopyIdx.getRegSlot(true);
818 for (LiveInterval::SubRange &SA : IntA.subranges()) {
819 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
820 assert(ASubValNo != nullptr);
821 SA.removeValNo(ASubValNo);
824 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
829 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP,
830 MachineInstr *CopyMI,
833 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
834 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
835 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
836 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
837 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
840 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
841 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
842 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
843 assert(ValNo && "CopyMI input register not live");
844 if (ValNo->isPHIDef() || ValNo->isUnused())
846 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
849 if (DefMI->isCopyLike()) {
853 if (!TII->isAsCheapAsAMove(DefMI))
855 if (!TII->isTriviallyReMaterializable(DefMI, AA))
857 bool SawStore = false;
858 if (!DefMI->isSafeToMove(TII, AA, SawStore))
860 const MCInstrDesc &MCID = DefMI->getDesc();
861 if (MCID.getNumDefs() != 1)
863 // Only support subregister destinations when the def is read-undef.
864 MachineOperand &DstOperand = CopyMI->getOperand(0);
865 unsigned CopyDstReg = DstOperand.getReg();
866 if (DstOperand.getSubReg() && !DstOperand.isUndef())
869 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
870 // the register substantially (beyond both source and dest size). This is bad
871 // for performance since it can cascade through a function, introducing many
872 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
873 // around after a few subreg copies).
874 if (SrcIdx && DstIdx)
877 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
878 if (!DefMI->isImplicitDef()) {
879 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
880 unsigned NewDstReg = DstReg;
882 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
883 DefMI->getOperand(0).getSubReg());
885 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
887 // Finally, make sure that the physical subregister that will be
888 // constructed later is permitted for the instruction.
889 if (!DefRC->contains(NewDstReg))
892 // Theoretically, some stack frame reference could exist. Just make sure
893 // it hasn't actually happened.
894 assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
895 "Only expect to deal with virtual or physical registers");
899 MachineBasicBlock *MBB = CopyMI->getParent();
900 MachineBasicBlock::iterator MII =
901 std::next(MachineBasicBlock::iterator(CopyMI));
902 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
903 MachineInstr *NewMI = std::prev(MII);
905 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
906 CopyMI->eraseFromParent();
907 ErasedInstrs.insert(CopyMI);
909 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
910 // We need to remember these so we can add intervals once we insert
911 // NewMI into SlotIndexes.
912 SmallVector<unsigned, 4> NewMIImplDefs;
913 for (unsigned i = NewMI->getDesc().getNumOperands(),
914 e = NewMI->getNumOperands(); i != e; ++i) {
915 MachineOperand &MO = NewMI->getOperand(i);
917 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
918 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
919 NewMIImplDefs.push_back(MO.getReg());
923 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
924 const TargetRegisterClass *NewRC = CP.getNewRC();
925 unsigned NewIdx = NewMI->getOperand(0).getSubReg();
928 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
930 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
932 assert(NewRC && "subreg chosen for remat incompatible with instruction");
933 MRI->setRegClass(DstReg, NewRC);
935 updateRegDefsUses(DstReg, DstReg, DstIdx);
936 NewMI->getOperand(0).setSubReg(NewIdx);
937 } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
938 // The New instruction may be defining a sub-register of what's actually
939 // been asked for. If so it must implicitly define the whole thing.
940 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
941 "Only expect virtual or physical registers in remat");
942 NewMI->getOperand(0).setIsDead(true);
943 NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
947 // Record small dead def live-ranges for all the subregisters
948 // of the destination register.
949 // Otherwise, variables that live through may miss some
950 // interferences, thus creating invalid allocation.
952 // vreg1 = somedef ; vreg1 GR8
953 // vreg2 = remat ; vreg2 GR32
954 // CL = COPY vreg2.sub_8bit
955 // = somedef vreg1 ; vreg1 GR8
957 // vreg1 = somedef ; vreg1 GR8
958 // ECX<def, dead> = remat ; CL<imp-def>
959 // = somedef vreg1 ; vreg1 GR8
960 // vreg1 will see the inteferences with CL but not with CH since
961 // no live-ranges would have been created for ECX.
963 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
964 for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI);
965 Units.isValid(); ++Units)
966 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
967 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
970 if (NewMI->getOperand(0).getSubReg())
971 NewMI->getOperand(0).setIsUndef();
973 // CopyMI may have implicit operands, transfer them over to the newly
974 // rematerialized instruction. And update implicit def interval valnos.
975 for (unsigned i = CopyMI->getDesc().getNumOperands(),
976 e = CopyMI->getNumOperands(); i != e; ++i) {
977 MachineOperand &MO = CopyMI->getOperand(i);
979 assert(MO.isImplicit() && "No explicit operands after implict operands.");
980 // Discard VReg implicit defs.
981 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
982 NewMI->addOperand(MO);
987 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
988 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
989 unsigned Reg = NewMIImplDefs[i];
990 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
991 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
992 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
995 DEBUG(dbgs() << "Remat: " << *NewMI);
998 // The source interval can become smaller because we removed a use.
999 LIS->shrinkToUses(&SrcInt, &DeadDefs);
1000 if (!DeadDefs.empty()) {
1001 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1002 // to describe DstReg instead.
1003 for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
1004 MachineInstr *UseMI = UseMO.getParent();
1005 if (UseMI->isDebugValue()) {
1006 UseMO.setReg(DstReg);
1007 DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1010 eliminateDeadDefs();
1016 static void removeUndefValue(LiveRange &LR, SlotIndex At)
1018 VNInfo *VNInfo = LR.getVNInfoAt(At);
1019 assert(VNInfo != nullptr && SlotIndex::isSameInstr(VNInfo->def, At));
1020 LR.removeValNo(VNInfo);
1023 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1024 // ProcessImpicitDefs may leave some copies of <undef> values, it only removes
1025 // local variables. When we have a copy like:
1027 // %vreg1 = COPY %vreg2<undef>
1029 // We delete the copy and remove the corresponding value number from %vreg1.
1030 // Any uses of that value number are marked as <undef>.
1032 // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1033 // CoalescerPair may have a new register class with adjusted subreg indices
1035 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1036 isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1038 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
1039 const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1040 // CopyMI is undef iff SrcReg is not live before the instruction.
1041 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1042 unsigned SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1043 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1044 if ((SR.LaneMask & SrcMask) == 0)
1049 } else if (SrcLI.liveAt(Idx))
1052 DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1054 // Remove any DstReg segments starting at the instruction.
1055 LiveInterval &DstLI = LIS->getInterval(DstReg);
1056 unsigned DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1057 SlotIndex RegIndex = Idx.getRegSlot();
1058 for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1059 if ((SR.LaneMask & DstMask) == 0)
1061 removeUndefValue(SR, RegIndex);
1063 DstLI.removeEmptySubRanges();
1065 // Remove value or merge with previous one in case of a subregister def.
1066 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1067 VNInfo *VNInfo = DstLI.getVNInfoAt(RegIndex);
1068 DstLI.MergeValueNumberInto(VNInfo, PrevVNI);
1070 removeUndefValue(DstLI, RegIndex);
1073 // Mark uses as undef.
1074 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1075 if (MO.isDef() /*|| MO.isUndef()*/)
1077 const MachineInstr &MI = *MO.getParent();
1078 SlotIndex UseIdx = LIS->getInstructionIndex(&MI);
1079 unsigned UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1081 if (UseMask != ~0u && DstLI.hasSubRanges()) {
1083 for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1084 if ((SR.LaneMask & UseMask) == 0)
1086 if (SR.liveAt(UseIdx)) {
1092 isLive = DstLI.liveAt(UseIdx);
1095 MO.setIsUndef(true);
1096 DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1101 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
1104 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1105 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1107 SmallPtrSet<MachineInstr*, 8> Visited;
1108 for (MachineRegisterInfo::reg_instr_iterator
1109 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1111 MachineInstr *UseMI = &*(I++);
1113 // Each instruction can only be rewritten once because sub-register
1114 // composition is not always idempotent. When SrcReg != DstReg, rewriting
1115 // the UseMI operands removes them from the SrcReg use-def chain, but when
1116 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1117 // operands mentioning the virtual register.
1118 if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1121 SmallVector<unsigned,8> Ops;
1123 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1125 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1126 // because SrcReg is a sub-register.
1127 if (DstInt && !Reads && SubIdx)
1128 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
1130 // Replace SrcReg with DstReg in all UseMI operands.
1131 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1132 MachineOperand &MO = UseMI->getOperand(Ops[i]);
1134 // Adjust <undef> flags in case of sub-register joins. We don't want to
1135 // turn a full def into a read-modify-write sub-register def and vice
1137 if (SubIdx && MO.isDef())
1138 MO.setIsUndef(!Reads);
1140 // A subreg use of a partially undef (super) register may be a complete
1141 // undef use now and then has to be marked that way.
1142 if (SubIdx != 0 && MO.isUse() && MRI->tracksSubRegLiveness()) {
1143 if (!DstInt->hasSubRanges()) {
1144 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1145 unsigned Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
1146 DstInt->createSubRangeFrom(Allocator, Mask, *DstInt);
1148 unsigned Mask = TRI->getSubRegIndexLaneMask(SubIdx);
1149 bool IsUndef = true;
1150 SlotIndex MIIdx = UseMI->isDebugValue()
1151 ? LIS->getSlotIndexes()->getIndexBefore(UseMI)
1152 : LIS->getInstructionIndex(UseMI);
1153 SlotIndex UseIdx = MIIdx.getRegSlot(true);
1154 for (LiveInterval::SubRange &S : DstInt->subranges()) {
1155 if ((S.LaneMask & Mask) == 0)
1157 if (S.liveAt(UseIdx)) {
1163 MO.setIsUndef(true);
1164 // We found out some subregister use is actually reading an undefined
1165 // value. In some cases the whole vreg has become undefined at this
1166 // point so we have to potentially shrink the main range if the
1167 // use was ending a live segment there.
1168 LiveQueryResult Q = DstInt->Query(MIIdx);
1169 if (Q.valueOut() == nullptr)
1170 ShrinkMainRange = true;
1175 MO.substPhysReg(DstReg, *TRI);
1177 MO.substVirtReg(DstReg, SubIdx, *TRI);
1181 dbgs() << "\t\tupdated: ";
1182 if (!UseMI->isDebugValue())
1183 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
1189 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1190 // Always join simple intervals that are defined by a single copy from a
1191 // reserved register. This doesn't increase register pressure, so it is
1192 // always beneficial.
1193 if (!MRI->isReserved(CP.getDstReg())) {
1194 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1198 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1199 if (JoinVInt.containsOneValue())
1202 DEBUG(dbgs() << "\tCannot join complex intervals into reserved register.\n");
1206 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1209 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1211 CoalescerPair CP(*TRI);
1212 if (!CP.setRegisters(CopyMI)) {
1213 DEBUG(dbgs() << "\tNot coalescable.\n");
1217 if (CP.getNewRC()) {
1218 auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1219 auto DstRC = MRI->getRegClass(CP.getDstReg());
1220 unsigned SrcIdx = CP.getSrcIdx();
1221 unsigned DstIdx = CP.getDstIdx();
1222 if (CP.isFlipped()) {
1223 std::swap(SrcIdx, DstIdx);
1224 std::swap(SrcRC, DstRC);
1226 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1228 DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
1233 // Dead code elimination. This really should be handled by MachineDCE, but
1234 // sometimes dead copies slip through, and we can't generate invalid live
1236 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1237 DEBUG(dbgs() << "\tCopy is dead.\n");
1238 DeadDefs.push_back(CopyMI);
1239 eliminateDeadDefs();
1243 // Eliminate undefs.
1244 if (!CP.isPhys() && eliminateUndefCopy(CopyMI)) {
1245 LIS->RemoveMachineInstrFromMaps(CopyMI);
1246 CopyMI->eraseFromParent();
1247 return false; // Not coalescable.
1250 // Coalesced copies are normally removed immediately, but transformations
1251 // like removeCopyByCommutingDef() can inadvertently create identity copies.
1252 // When that happens, just join the values and remove the copy.
1253 if (CP.getSrcReg() == CP.getDstReg()) {
1254 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1255 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1256 const SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
1257 LiveQueryResult LRQ = LI.Query(CopyIdx);
1258 if (VNInfo *DefVNI = LRQ.valueDefined()) {
1259 VNInfo *ReadVNI = LRQ.valueIn();
1260 assert(ReadVNI && "No value before copy and no <undef> flag.");
1261 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1262 LI.MergeValueNumberInto(DefVNI, ReadVNI);
1264 // Process subregister liveranges.
1265 for (LiveInterval::SubRange &S : LI.subranges()) {
1266 LiveQueryResult SLRQ = S.Query(CopyIdx);
1267 if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
1268 VNInfo *SReadVNI = SLRQ.valueIn();
1269 S.MergeValueNumberInto(SDefVNI, SReadVNI);
1272 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
1274 LIS->RemoveMachineInstrFromMaps(CopyMI);
1275 CopyMI->eraseFromParent();
1279 // Enforce policies.
1281 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1282 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1284 if (!canJoinPhys(CP)) {
1285 // Before giving up coalescing, if definition of source is defined by
1286 // trivial computation, try rematerializing it.
1288 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1291 Again = true; // May be possible to coalesce later.
1295 // When possible, let DstReg be the larger interval.
1296 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1297 LIS->getInterval(CP.getDstReg()).size())
1301 dbgs() << "\tConsidering merging to "
1302 << TRI->getRegClassName(CP.getNewRC()) << " with ";
1303 if (CP.getDstIdx() && CP.getSrcIdx())
1304 dbgs() << PrintReg(CP.getDstReg()) << " in "
1305 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1306 << PrintReg(CP.getSrcReg()) << " in "
1307 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1309 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1310 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1315 ShrinkMainRange = false;
1317 // Okay, attempt to join these two intervals. On failure, this returns false.
1318 // Otherwise, if one of the intervals being joined is a physreg, this method
1319 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1320 // been modified, so we can use this information below to update aliases.
1321 if (!joinIntervals(CP)) {
1322 // Coalescing failed.
1324 // If definition of source is defined by trivial computation, try
1325 // rematerializing it.
1327 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1330 // If we can eliminate the copy without merging the live segments, do so
1332 if (!CP.isPartial() && !CP.isPhys()) {
1333 if (adjustCopiesBackFrom(CP, CopyMI) ||
1334 removeCopyByCommutingDef(CP, CopyMI)) {
1335 LIS->RemoveMachineInstrFromMaps(CopyMI);
1336 CopyMI->eraseFromParent();
1337 DEBUG(dbgs() << "\tTrivial!\n");
1342 // Otherwise, we are unable to join the intervals.
1343 DEBUG(dbgs() << "\tInterference!\n");
1344 Again = true; // May be possible to coalesce later.
1348 // Coalescing to a virtual register that is of a sub-register class of the
1349 // other. Make sure the resulting register is set to the right register class.
1350 if (CP.isCrossClass()) {
1352 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1355 // Removing sub-register copies can ease the register class constraints.
1356 // Make sure we attempt to inflate the register class of DstReg.
1357 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1358 InflateRegs.push_back(CP.getDstReg());
1360 // CopyMI has been erased by joinIntervals at this point. Remove it from
1361 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1362 // to the work list. This keeps ErasedInstrs from growing needlessly.
1363 ErasedInstrs.erase(CopyMI);
1365 // Rewrite all SrcReg operands to DstReg.
1366 // Also update DstReg operands to include DstIdx if it is set.
1368 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1369 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1371 // Shrink subregister ranges if necessary.
1372 if (ShrinkMask != 0) {
1373 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1374 for (LiveInterval::SubRange &S : LI.subranges()) {
1375 if ((S.LaneMask & ShrinkMask) == 0)
1377 DEBUG(dbgs() << "Shrink LaneUses (Lane "
1378 << format("%04X", S.LaneMask) << ")\n");
1379 LIS->shrinkToUses(S, LI.reg);
1382 if (ShrinkMainRange) {
1383 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1384 LIS->shrinkToUses(&LI);
1387 // SrcReg is guaranteed to be the register whose live interval that is
1389 LIS->removeInterval(CP.getSrcReg());
1391 // Update regalloc hint.
1392 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1395 dbgs() << "\tSuccess: " << PrintReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
1396 << " -> " << PrintReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
1397 dbgs() << "\tResult = ";
1399 dbgs() << PrintReg(CP.getDstReg(), TRI);
1401 dbgs() << LIS->getInterval(CP.getDstReg());
1409 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1410 unsigned DstReg = CP.getDstReg();
1411 assert(CP.isPhys() && "Must be a physreg copy");
1412 assert(MRI->isReserved(DstReg) && "Not a reserved register");
1413 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1414 DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1416 assert(RHS.containsOneValue() && "Invalid join with reserved register");
1418 // Optimization for reserved registers like ESP. We can only merge with a
1419 // reserved physreg if RHS has a single value that is a copy of DstReg.
1420 // The live range of the reserved register will look like a set of dead defs
1421 // - we don't properly track the live range of reserved registers.
1423 // Deny any overlapping intervals. This depends on all the reserved
1424 // register live ranges to look like dead defs.
1425 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI)
1426 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1427 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1431 // Skip any value computations, we are not adding new values to the
1432 // reserved register. Also skip merging the live ranges, the reserved
1433 // register live range doesn't need to be accurate as long as all the
1436 // Delete the identity copy.
1437 MachineInstr *CopyMI;
1438 if (CP.isFlipped()) {
1439 CopyMI = MRI->getVRegDef(RHS.reg);
1441 if (!MRI->hasOneNonDBGUse(RHS.reg)) {
1442 DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
1446 MachineInstr *DestMI = MRI->getVRegDef(RHS.reg);
1447 CopyMI = &*MRI->use_instr_nodbg_begin(RHS.reg);
1448 const SlotIndex CopyRegIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
1449 const SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
1451 // We checked above that there are no interfering defs of the physical
1452 // register. However, for this case, where we intent to move up the def of
1453 // the physical register, we also need to check for interfering uses.
1454 SlotIndexes *Indexes = LIS->getSlotIndexes();
1455 for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
1456 SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
1457 MachineInstr *MI = LIS->getInstructionFromIndex(SI);
1458 if (MI->readsRegister(DstReg, TRI)) {
1459 DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
1464 // We're going to remove the copy which defines a physical reserved
1465 // register, so remove its valno, etc.
1466 DEBUG(dbgs() << "\t\tRemoving phys reg def of " << DstReg << " at "
1467 << CopyRegIdx << "\n");
1469 LIS->removePhysRegDefAt(DstReg, CopyRegIdx);
1470 // Create a new dead def at the new def location.
1471 for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
1472 LiveRange &LR = LIS->getRegUnit(*UI);
1473 LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
1477 LIS->RemoveMachineInstrFromMaps(CopyMI);
1478 CopyMI->eraseFromParent();
1480 // We don't track kills for reserved registers.
1481 MRI->clearKillFlags(CP.getSrcReg());
1486 //===----------------------------------------------------------------------===//
1487 // Interference checking and interval joining
1488 //===----------------------------------------------------------------------===//
1490 // In the easiest case, the two live ranges being joined are disjoint, and
1491 // there is no interference to consider. It is quite common, though, to have
1492 // overlapping live ranges, and we need to check if the interference can be
1495 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1496 // This means that two SSA values overlap if and only if the def of one value
1497 // is contained in the live range of the other value. As a special case, the
1498 // overlapping values can be defined at the same index.
1500 // The interference from an overlapping def can be resolved in these cases:
1502 // 1. Coalescable copies. The value is defined by a copy that would become an
1503 // identity copy after joining SrcReg and DstReg. The copy instruction will
1504 // be removed, and the value will be merged with the source value.
1506 // There can be several copies back and forth, causing many values to be
1507 // merged into one. We compute a list of ultimate values in the joined live
1508 // range as well as a mappings from the old value numbers.
1510 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1511 // predecessors have a live out value. It doesn't cause real interference,
1512 // and can be merged into the value it overlaps. Like a coalescable copy, it
1513 // can be erased after joining.
1515 // 3. Copy of external value. The overlapping def may be a copy of a value that
1516 // is already in the other register. This is like a coalescable copy, but
1517 // the live range of the source register must be trimmed after erasing the
1518 // copy instruction:
1521 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1523 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1524 // defining one lane at a time:
1526 // %dst:ssub0<def,read-undef> = FOO
1528 // %dst:ssub1<def> = COPY %src
1530 // The live range of %src overlaps the %dst value defined by FOO, but
1531 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1532 // which was undef anyway.
1534 // The value mapping is more complicated in this case. The final live range
1535 // will have different value numbers for both FOO and BAR, but there is no
1536 // simple mapping from old to new values. It may even be necessary to add
1539 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1540 // is live, but never read. This can happen because we don't compute
1541 // individual live ranges per lane.
1545 // %dst:ssub1<def> = COPY %src
1547 // This kind of interference is only resolved locally. If the clobbered
1548 // lane value escapes the block, the join is aborted.
1551 /// Track information about values in a single virtual register about to be
1552 /// joined. Objects of this class are always created in pairs - one for each
1553 /// side of the CoalescerPair (or one for each lane of a side of the coalescer
1556 /// Live range we work on.
1558 /// (Main) register we work on.
1561 /// Reg (and therefore the values in this liverange) will end up as
1562 /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
1564 const unsigned SubIdx;
1565 /// The LaneMask that this liverange will occupy the coalesced register. May
1566 /// be smaller than the lanemask produced by SubIdx when merging subranges.
1567 const unsigned LaneMask;
1569 /// This is true when joining sub register ranges, false when joining main
1571 const bool SubRangeJoin;
1572 /// Whether the current LiveInterval tracks subregister liveness.
1573 const bool TrackSubRegLiveness;
1575 /// Values that will be present in the final live range.
1576 SmallVectorImpl<VNInfo*> &NewVNInfo;
1578 const CoalescerPair &CP;
1580 SlotIndexes *Indexes;
1581 const TargetRegisterInfo *TRI;
1583 /// Value number assignments. Maps value numbers in LI to entries in
1584 /// NewVNInfo. This is suitable for passing to LiveInterval::join().
1585 SmallVector<int, 8> Assignments;
1587 /// Conflict resolution for overlapping values.
1588 enum ConflictResolution {
1589 /// No overlap, simply keep this value.
1592 /// Merge this value into OtherVNI and erase the defining instruction.
1593 /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
1597 /// Merge this value into OtherVNI but keep the defining instruction.
1598 /// This is for the special case where OtherVNI is defined by the same
1602 /// Keep this value, and have it replace OtherVNI where possible. This
1603 /// complicates value mapping since OtherVNI maps to two different values
1604 /// before and after this def.
1605 /// Used when clobbering undefined or dead lanes.
1608 /// Unresolved conflict. Visit later when all values have been mapped.
1611 /// Unresolvable conflict. Abort the join.
1615 /// Per-value info for LI. The lane bit masks are all relative to the final
1616 /// joined register, so they can be compared directly between SrcReg and
1619 ConflictResolution Resolution;
1621 /// Lanes written by this def, 0 for unanalyzed values.
1622 unsigned WriteLanes;
1624 /// Lanes with defined values in this register. Other lanes are undef and
1625 /// safe to clobber.
1626 unsigned ValidLanes;
1628 /// Value in LI being redefined by this def.
1631 /// Value in the other live range that overlaps this def, if any.
1634 /// Is this value an IMPLICIT_DEF that can be erased?
1636 /// IMPLICIT_DEF values should only exist at the end of a basic block that
1637 /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1638 /// safely erased if they are overlapping a live value in the other live
1641 /// Weird control flow graphs and incomplete PHI handling in
1642 /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1643 /// longer live ranges. Such IMPLICIT_DEF values should be treated like
1645 bool ErasableImplicitDef;
1647 /// True when the live range of this value will be pruned because of an
1648 /// overlapping CR_Replace value in the other live range.
1651 /// True once Pruned above has been computed.
1652 bool PrunedComputed;
1654 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1655 RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false),
1656 Pruned(false), PrunedComputed(false) {}
1658 bool isAnalyzed() const { return WriteLanes != 0; }
1661 /// One entry per value number in LI.
1662 SmallVector<Val, 8> Vals;
1664 /// Compute the bitmask of lanes actually written by DefMI.
1665 /// Set Redef if there are any partial register definitions that depend on the
1666 /// previous value of the register.
1667 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
1669 /// Find the ultimate value that VNI was copied from.
1670 std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const;
1672 bool valuesIdentical(VNInfo *Val0, VNInfo *Val1, const JoinVals &Other) const;
1674 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1675 /// Return a conflict resolution when possible, but leave the hard cases as
1677 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1678 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1679 /// The recursion always goes upwards in the dominator tree, making loops
1681 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1683 /// Compute the value assignment for ValNo in RI.
1684 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1686 void computeAssignment(unsigned ValNo, JoinVals &Other);
1688 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
1689 /// the extent of the tainted lanes in the block.
1691 /// Multiple values in Other.LR can be affected since partial redefinitions
1692 /// can preserve previously tainted lanes.
1694 /// 1 %dst = VLOAD <-- Define all lanes in %dst
1695 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
1696 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
1697 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1699 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1700 /// entry to TaintedVals.
1702 /// Returns false if the tainted lanes extend beyond the basic block.
1703 bool taintExtent(unsigned, unsigned, JoinVals&,
1704 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1706 /// Return true if MI uses any of the given Lanes from Reg.
1707 /// This does not include partial redefinitions of Reg.
1708 bool usesLanes(const MachineInstr *MI, unsigned, unsigned, unsigned) const;
1710 /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
1713 /// %dst = COPY %src
1714 /// %src = COPY %dst <-- This value to be pruned.
1715 /// %dst = COPY %src <-- This value is a copy of a pruned value.
1716 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1719 JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, unsigned LaneMask,
1720 SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp,
1721 LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
1722 bool TrackSubRegLiveness)
1723 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
1724 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
1725 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
1726 TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums())
1729 /// Analyze defs in LR and compute a value mapping in NewVNInfo.
1730 /// Returns false if any conflicts were impossible to resolve.
1731 bool mapValues(JoinVals &Other);
1733 /// Try to resolve conflicts that require all values to be mapped.
1734 /// Returns false if any conflicts were impossible to resolve.
1735 bool resolveConflicts(JoinVals &Other);
1737 /// Prune the live range of values in Other.LR where they would conflict with
1738 /// CR_Replace values in LR. Collect end points for restoring the live range
1740 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
1743 /// Removes subranges starting at copies that get removed. This sometimes
1744 /// happens when undefined subranges are copied around. These ranges contain
1745 /// no usefull information and can be removed.
1746 void pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask);
1748 /// Erase any machine instructions that have been coalesced away.
1749 /// Add erased instructions to ErasedInstrs.
1750 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1751 /// the erased instrs.
1752 void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
1753 SmallVectorImpl<unsigned> &ShrinkRegs);
1755 /// Get the value assignments suitable for passing to LiveInterval::join.
1756 const int *getAssignments() const { return Assignments.data(); }
1758 } // end anonymous namespace
1760 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
1763 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1764 if (!MO->isReg() || MO->getReg() != Reg || !MO->isDef())
1766 L |= TRI->getSubRegIndexLaneMask(
1767 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1774 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
1775 const VNInfo *VNI) const {
1776 unsigned Reg = this->Reg;
1778 while (!VNI->isPHIDef()) {
1779 SlotIndex Def = VNI->def;
1780 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1781 assert(MI && "No defining instruction");
1782 if (!MI->isFullCopy())
1783 return std::make_pair(VNI, Reg);
1784 unsigned SrcReg = MI->getOperand(1).getReg();
1785 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1786 return std::make_pair(VNI, Reg);
1788 const LiveInterval &LI = LIS->getInterval(SrcReg);
1789 const VNInfo *ValueIn;
1790 // No subrange involved.
1791 if (!SubRangeJoin || !LI.hasSubRanges()) {
1792 LiveQueryResult LRQ = LI.Query(Def);
1793 ValueIn = LRQ.valueIn();
1795 // Query subranges. Pick the first matching one.
1797 for (const LiveInterval::SubRange &S : LI.subranges()) {
1798 // Transform lanemask to a mask in the joined live interval.
1799 unsigned SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
1800 if ((SMask & LaneMask) == 0)
1802 LiveQueryResult LRQ = S.Query(Def);
1803 ValueIn = LRQ.valueIn();
1807 if (ValueIn == nullptr)
1812 return std::make_pair(VNI, Reg);
1815 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
1816 const JoinVals &Other) const {
1817 const VNInfo *Orig0;
1819 std::tie(Orig0, Reg0) = followCopyChain(Value0);
1820 if (Orig0 == Value1)
1823 const VNInfo *Orig1;
1825 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
1827 // The values are equal if they are defined at the same place and use the
1828 // same register. Note that we cannot compare VNInfos directly as some of
1829 // them might be from a copy created in mergeSubRangeInto() while the other
1830 // is from the original LiveInterval.
1831 return Orig0->def == Orig1->def && Reg0 == Reg1;
1834 JoinVals::ConflictResolution
1835 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1836 Val &V = Vals[ValNo];
1837 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1838 VNInfo *VNI = LR.getValNumInfo(ValNo);
1839 if (VNI->isUnused()) {
1844 // Get the instruction defining this value, compute the lanes written.
1845 const MachineInstr *DefMI = nullptr;
1846 if (VNI->isPHIDef()) {
1847 // Conservatively assume that all lanes in a PHI are valid.
1848 unsigned Lanes = SubRangeJoin ? 1 : TRI->getSubRegIndexLaneMask(SubIdx);
1849 V.ValidLanes = V.WriteLanes = Lanes;
1851 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1852 assert(DefMI != nullptr);
1854 // We don't care about the lanes when joining subregister ranges.
1855 V.ValidLanes = V.WriteLanes = 1;
1858 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1860 // If this is a read-modify-write instruction, there may be more valid
1861 // lanes than the ones written by this instruction.
1862 // This only covers partial redef operands. DefMI may have normal use
1863 // operands reading the register. They don't contribute valid lanes.
1865 // This adds ssub1 to the set of valid lanes in %src:
1867 // %src:ssub1<def> = FOO
1869 // This leaves only ssub1 valid, making any other lanes undef:
1871 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1873 // The <read-undef> flag on the def operand means that old lane values are
1876 V.RedefVNI = LR.Query(VNI->def).valueIn();
1877 assert((TrackSubRegLiveness || V.RedefVNI) &&
1878 "Instruction is reading nonexistent value");
1879 if (V.RedefVNI != nullptr) {
1880 computeAssignment(V.RedefVNI->id, Other);
1881 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1885 // An IMPLICIT_DEF writes undef values.
1886 if (DefMI->isImplicitDef()) {
1887 // We normally expect IMPLICIT_DEF values to be live only until the end
1888 // of their block. If the value is really live longer and gets pruned in
1889 // another block, this flag is cleared again.
1890 V.ErasableImplicitDef = true;
1891 V.ValidLanes &= ~V.WriteLanes;
1896 // Find the value in Other that overlaps VNI->def, if any.
1897 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
1899 // It is possible that both values are defined by the same instruction, or
1900 // the values are PHIs defined in the same block. When that happens, the two
1901 // values should be merged into one, but not into any preceding value.
1902 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1903 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1904 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1906 // One value stays, the other is merged. Keep the earlier one, or the first
1908 if (OtherVNI->def < VNI->def)
1909 Other.computeAssignment(OtherVNI->id, *this);
1910 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1911 // This is an early-clobber def overlapping a live-in value in the other
1912 // register. Not mergeable.
1913 V.OtherVNI = OtherLRQ.valueIn();
1914 return CR_Impossible;
1916 V.OtherVNI = OtherVNI;
1917 Val &OtherV = Other.Vals[OtherVNI->id];
1918 // Keep this value, check for conflicts when analyzing OtherVNI.
1919 if (!OtherV.isAnalyzed())
1921 // Both sides have been analyzed now.
1922 // Allow overlapping PHI values. Any real interference would show up in a
1923 // predecessor, the PHI itself can't introduce any conflicts.
1924 if (VNI->isPHIDef())
1926 if (V.ValidLanes & OtherV.ValidLanes)
1927 // Overlapping lanes can't be resolved.
1928 return CR_Impossible;
1933 // No simultaneous def. Is Other live at the def?
1934 V.OtherVNI = OtherLRQ.valueIn();
1936 // No overlap, no conflict.
1939 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1941 // We have overlapping values, or possibly a kill of Other.
1942 // Recursively compute assignments up the dominator tree.
1943 Other.computeAssignment(V.OtherVNI->id, *this);
1944 Val &OtherV = Other.Vals[V.OtherVNI->id];
1946 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
1947 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
1948 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
1951 // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
1952 // to erase the IMPLICIT_DEF instruction.
1953 if (OtherV.ErasableImplicitDef && DefMI &&
1954 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
1955 DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
1956 << " extends into BB#" << DefMI->getParent()->getNumber()
1957 << ", keeping it.\n");
1958 OtherV.ErasableImplicitDef = false;
1961 // Allow overlapping PHI values. Any real interference would show up in a
1962 // predecessor, the PHI itself can't introduce any conflicts.
1963 if (VNI->isPHIDef())
1966 // Check for simple erasable conflicts.
1967 if (DefMI->isImplicitDef()) {
1968 // We need the def for the subregister if there is nothing else live at the
1969 // subrange at this point.
1970 if (TrackSubRegLiveness
1971 && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)) == 0)
1976 // Include the non-conflict where DefMI is a coalescable copy that kills
1977 // OtherVNI. We still want the copy erased and value numbers merged.
1978 if (CP.isCoalescable(DefMI)) {
1979 // Some of the lanes copied from OtherVNI may be undef, making them undef
1981 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1985 // This may not be a real conflict if DefMI simply kills Other and defines
1987 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1990 // Handle the case where VNI and OtherVNI can be proven to be identical:
1992 // %other = COPY %ext
1993 // %this = COPY %ext <-- Erase this copy
1995 if (DefMI->isFullCopy() && !CP.isPartial()
1996 && valuesIdentical(VNI, V.OtherVNI, Other))
1999 // If the lanes written by this instruction were all undef in OtherVNI, it is
2000 // still safe to join the live ranges. This can't be done with a simple value
2001 // mapping, though - OtherVNI will map to multiple values:
2003 // 1 %dst:ssub0 = FOO <-- OtherVNI
2004 // 2 %src = BAR <-- VNI
2005 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
2007 // 5 QUUX %src<kill>
2009 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
2010 // handles this complex value mapping.
2011 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
2014 // If the other live range is killed by DefMI and the live ranges are still
2015 // overlapping, it must be because we're looking at an early clobber def:
2017 // %dst<def,early-clobber> = ASM %src<kill>
2019 // In this case, it is illegal to merge the two live ranges since the early
2020 // clobber def would clobber %src before it was read.
2021 if (OtherLRQ.isKill()) {
2022 // This case where the def doesn't overlap the kill is handled above.
2023 assert(VNI->def.isEarlyClobber() &&
2024 "Only early clobber defs can overlap a kill");
2025 return CR_Impossible;
2028 // VNI is clobbering live lanes in OtherVNI, but there is still the
2029 // possibility that no instructions actually read the clobbered lanes.
2030 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
2031 // Otherwise Other.RI wouldn't be live here.
2032 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
2033 return CR_Impossible;
2035 // We need to verify that no instructions are reading the clobbered lanes. To
2036 // save compile time, we'll only check that locally. Don't allow the tainted
2037 // value to escape the basic block.
2038 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2039 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
2040 return CR_Impossible;
2042 // There are still some things that could go wrong besides clobbered lanes
2043 // being read, for example OtherVNI may be only partially redefined in MBB,
2044 // and some clobbered lanes could escape the block. Save this analysis for
2045 // resolveConflicts() when all values have been mapped. We need to know
2046 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
2047 // that now - the recursive analyzeValue() calls must go upwards in the
2049 return CR_Unresolved;
2052 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
2053 Val &V = Vals[ValNo];
2054 if (V.isAnalyzed()) {
2055 // Recursion should always move up the dominator tree, so ValNo is not
2056 // supposed to reappear before it has been assigned.
2057 assert(Assignments[ValNo] != -1 && "Bad recursion?");
2060 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2063 // Merge this ValNo into OtherVNI.
2064 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
2065 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
2066 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2067 DEBUG(dbgs() << "\t\tmerge " << PrintReg(Reg) << ':' << ValNo << '@'
2068 << LR.getValNumInfo(ValNo)->def << " into "
2069 << PrintReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
2070 << V.OtherVNI->def << " --> @"
2071 << NewVNInfo[Assignments[ValNo]]->def << '\n');
2074 case CR_Unresolved: {
2075 // The other value is going to be pruned if this join is successful.
2076 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
2077 Val &OtherV = Other.Vals[V.OtherVNI->id];
2078 // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
2080 if ((OtherV.WriteLanes & ~V.ValidLanes) != 0 && TrackSubRegLiveness)
2081 OtherV.ErasableImplicitDef = false;
2082 OtherV.Pruned = true;
2086 // This value number needs to go in the final joined live range.
2087 Assignments[ValNo] = NewVNInfo.size();
2088 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
2093 bool JoinVals::mapValues(JoinVals &Other) {
2094 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2095 computeAssignment(i, Other);
2096 if (Vals[i].Resolution == CR_Impossible) {
2097 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(Reg) << ':' << i
2098 << '@' << LR.getValNumInfo(i)->def << '\n');
2106 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
2107 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
2108 VNInfo *VNI = LR.getValNumInfo(ValNo);
2109 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2110 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2112 // Scan Other.LR from VNI.def to MBBEnd.
2113 LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
2114 assert(OtherI != Other.LR.end() && "No conflict?");
2116 // OtherI is pointing to a tainted value. Abort the join if the tainted
2117 // lanes escape the block.
2118 SlotIndex End = OtherI->end;
2119 if (End >= MBBEnd) {
2120 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.Reg) << ':'
2121 << OtherI->valno->id << '@' << OtherI->start << '\n');
2124 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.Reg) << ':'
2125 << OtherI->valno->id << '@' << OtherI->start
2126 << " to " << End << '\n');
2127 // A dead def is not a problem.
2130 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2132 // Check for another def in the MBB.
2133 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2136 // Lanes written by the new def are no longer tainted.
2137 const Val &OV = Other.Vals[OtherI->valno->id];
2138 TaintedLanes &= ~OV.WriteLanes;
2141 } while (TaintedLanes);
2145 bool JoinVals::usesLanes(const MachineInstr *MI, unsigned Reg, unsigned SubIdx,
2146 unsigned Lanes) const {
2147 if (MI->isDebugValue())
2149 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
2150 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
2152 if (!MO->readsReg())
2154 if (Lanes & TRI->getSubRegIndexLaneMask(
2155 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
2161 bool JoinVals::resolveConflicts(JoinVals &Other) {
2162 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2164 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
2165 if (V.Resolution != CR_Unresolved)
2167 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(Reg) << ':' << i
2168 << '@' << LR.getValNumInfo(i)->def << '\n');
2173 assert(V.OtherVNI && "Inconsistent conflict resolution.");
2174 VNInfo *VNI = LR.getValNumInfo(i);
2175 const Val &OtherV = Other.Vals[V.OtherVNI->id];
2177 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
2178 // join, those lanes will be tainted with a wrong value. Get the extent of
2179 // the tainted lanes.
2180 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2181 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
2182 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2183 // Tainted lanes would extend beyond the basic block.
2186 assert(!TaintExtent.empty() && "There should be at least one conflict.");
2188 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
2189 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2190 MachineBasicBlock::iterator MI = MBB->begin();
2191 if (!VNI->isPHIDef()) {
2192 MI = Indexes->getInstructionFromIndex(VNI->def);
2193 // No need to check the instruction defining VNI for reads.
2196 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
2197 "Interference ends on VNI->def. Should have been handled earlier");
2198 MachineInstr *LastMI =
2199 Indexes->getInstructionFromIndex(TaintExtent.front().first);
2200 assert(LastMI && "Range must end at a proper instruction");
2201 unsigned TaintNum = 0;
2203 assert(MI != MBB->end() && "Bad LastMI");
2204 if (usesLanes(MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2205 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
2208 // LastMI is the last instruction to use the current value.
2209 if (&*MI == LastMI) {
2210 if (++TaintNum == TaintExtent.size())
2212 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
2213 assert(LastMI && "Range must end at a proper instruction");
2214 TaintedLanes = TaintExtent[TaintNum].second;
2219 // The tainted lanes are unused.
2220 V.Resolution = CR_Replace;
2226 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
2227 Val &V = Vals[ValNo];
2228 if (V.Pruned || V.PrunedComputed)
2231 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2234 // Follow copies up the dominator tree and check if any intermediate value
2236 V.PrunedComputed = true;
2237 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
2241 void JoinVals::pruneValues(JoinVals &Other,
2242 SmallVectorImpl<SlotIndex> &EndPoints,
2243 bool changeInstrs) {
2244 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2245 SlotIndex Def = LR.getValNumInfo(i)->def;
2246 switch (Vals[i].Resolution) {
2250 // This value takes precedence over the value in Other.LR.
2251 LIS->pruneValue(Other.LR, Def, &EndPoints);
2252 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
2253 // instructions are only inserted to provide a live-out value for PHI
2254 // predecessors, so the instruction should simply go away once its value
2255 // has been replaced.
2256 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2257 bool EraseImpDef = OtherV.ErasableImplicitDef &&
2258 OtherV.Resolution == CR_Keep;
2259 if (!Def.isBlock()) {
2261 // Remove <def,read-undef> flags. This def is now a partial redef.
2262 // Also remove <def,dead> flags since the joined live range will
2263 // continue past this instruction.
2264 for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
2265 MO.isValid(); ++MO) {
2266 if (MO->isReg() && MO->isDef() && MO->getReg() == Reg) {
2267 MO->setIsUndef(EraseImpDef);
2268 MO->setIsDead(false);
2272 // This value will reach instructions below, but we need to make sure
2273 // the live range also reaches the instruction at Def.
2275 EndPoints.push_back(Def);
2277 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.Reg) << " at " << Def
2278 << ": " << Other.LR << '\n');
2283 if (isPrunedValue(i, Other)) {
2284 // This value is ultimately a copy of a pruned value in LR or Other.LR.
2285 // We can no longer trust the value mapping computed by
2286 // computeAssignment(), the value that was originally copied could have
2288 LIS->pruneValue(LR, Def, &EndPoints);
2289 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(Reg) << " at "
2290 << Def << ": " << LR << '\n');
2295 llvm_unreachable("Unresolved conflicts");
2300 void JoinVals::pruneSubRegValues(LiveInterval &LI, unsigned &ShrinkMask)
2302 // Look for values being erased.
2303 bool DidPrune = false;
2304 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2305 if (Vals[i].Resolution != CR_Erase)
2308 // Check subranges at the point where the copy will be removed.
2309 SlotIndex Def = LR.getValNumInfo(i)->def;
2310 for (LiveInterval::SubRange &S : LI.subranges()) {
2311 LiveQueryResult Q = S.Query(Def);
2313 // If a subrange starts at the copy then an undefined value has been
2314 // copied and we must remove that subrange value as well.
2315 VNInfo *ValueOut = Q.valueOutOrDead();
2316 if (ValueOut != nullptr && Q.valueIn() == nullptr) {
2317 DEBUG(dbgs() << "\t\tPrune sublane " << format("%04X", S.LaneMask)
2318 << " at " << Def << "\n");
2319 LIS->pruneValue(S, Def, nullptr);
2321 // Mark value number as unused.
2322 ValueOut->markUnused();
2325 // If a subrange ends at the copy, then a value was copied but only
2326 // partially used later. Shrink the subregister range apropriately.
2327 if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
2328 DEBUG(dbgs() << "\t\tDead uses at sublane "
2329 << format("%04X", S.LaneMask) << " at " << Def << "\n");
2330 ShrinkMask |= S.LaneMask;
2335 LI.removeEmptySubRanges();
2338 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2339 SmallVectorImpl<unsigned> &ShrinkRegs) {
2340 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2341 // Get the def location before markUnused() below invalidates it.
2342 SlotIndex Def = LR.getValNumInfo(i)->def;
2343 switch (Vals[i].Resolution) {
2345 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
2346 // longer. The IMPLICIT_DEF instructions are only inserted by
2347 // PHIElimination to guarantee that all PHI predecessors have a value.
2348 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
2350 // Remove value number i from LR.
2351 VNInfo *VNI = LR.getValNumInfo(i);
2352 LR.removeValNo(VNI);
2353 // Note that this VNInfo is reused and still referenced in NewVNInfo,
2354 // make it appear like an unused value number.
2356 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n');
2361 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2362 assert(MI && "No instruction to erase");
2364 unsigned Reg = MI->getOperand(1).getReg();
2365 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
2366 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
2367 ShrinkRegs.push_back(Reg);
2369 ErasedInstrs.insert(MI);
2370 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
2371 LIS->RemoveMachineInstrFromMaps(MI);
2372 MI->eraseFromParent();
2381 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
2383 const CoalescerPair &CP) {
2384 SmallVector<VNInfo*, 16> NewVNInfo;
2385 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
2386 NewVNInfo, CP, LIS, TRI, true, true);
2387 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
2388 NewVNInfo, CP, LIS, TRI, true, true);
2390 // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
2391 // Conflicts should already be resolved so the mapping/resolution should
2393 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2394 llvm_unreachable("Can't join subrange although main ranges are compatible");
2395 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2396 llvm_unreachable("Can't join subrange although main ranges are compatible");
2398 // The merging algorithm in LiveInterval::join() can't handle conflicting
2399 // value mappings, so we need to remove any live ranges that overlap a
2400 // CR_Replace resolution. Collect a set of end points that can be used to
2401 // restore the live range after joining.
2402 SmallVector<SlotIndex, 8> EndPoints;
2403 LHSVals.pruneValues(RHSVals, EndPoints, false);
2404 RHSVals.pruneValues(LHSVals, EndPoints, false);
2409 // Join RRange into LHS.
2410 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
2413 DEBUG(dbgs() << "\t\tjoined lanes: " << LRange << "\n");
2414 if (EndPoints.empty())
2417 // Recompute the parts of the live range we had to remove because of
2418 // CR_Replace conflicts.
2419 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2420 << " points: " << LRange << '\n');
2421 LIS->extendToIndices(LRange, EndPoints);
2424 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
2425 const LiveRange &ToMerge,
2426 unsigned LaneMask, CoalescerPair &CP) {
2427 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2428 for (LiveInterval::SubRange &R : LI.subranges()) {
2429 unsigned RMask = R.LaneMask;
2430 // LaneMask of subregisters common to subrange R and ToMerge.
2431 unsigned Common = RMask & LaneMask;
2432 // There is nothing to do without common subregs.
2436 DEBUG(dbgs() << format("\t\tCopy+Merge %04X into %04X\n", RMask, Common));
2437 // LaneMask of subregisters contained in the R range but not in ToMerge,
2438 // they have to split into their own subrange.
2439 unsigned LRest = RMask & ~LaneMask;
2440 LiveInterval::SubRange *CommonRange;
2443 DEBUG(dbgs() << format("\t\tReduce Lane to %04X\n", LRest));
2444 // Duplicate SubRange for newly merged common stuff.
2445 CommonRange = LI.createSubRangeFrom(Allocator, Common, R);
2447 // Reuse the existing range.
2448 R.LaneMask = Common;
2451 LiveRange RangeCopy(ToMerge, Allocator);
2452 joinSubRegRanges(*CommonRange, RangeCopy, Common, CP);
2456 if (LaneMask != 0) {
2457 DEBUG(dbgs() << format("\t\tNew Lane %04X\n", LaneMask));
2458 LI.createSubRangeFrom(Allocator, LaneMask, ToMerge);
2462 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
2463 SmallVector<VNInfo*, 16> NewVNInfo;
2464 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
2465 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
2466 bool TrackSubRegLiveness = MRI->tracksSubRegLiveness();
2467 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), 0, NewVNInfo, CP, LIS,
2468 TRI, false, TrackSubRegLiveness);
2469 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), 0, NewVNInfo, CP, LIS,
2470 TRI, false, TrackSubRegLiveness);
2472 DEBUG(dbgs() << "\t\tRHS = " << RHS
2473 << "\n\t\tLHS = " << LHS
2476 // First compute NewVNInfo and the simple value mappings.
2477 // Detect impossible conflicts early.
2478 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2481 // Some conflicts can only be resolved after all values have been mapped.
2482 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2485 // All clear, the live ranges can be merged.
2486 if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
2487 BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2489 // Transform lanemasks from the LHS to masks in the coalesced register and
2490 // create initial subranges if necessary.
2491 unsigned DstIdx = CP.getDstIdx();
2492 if (!LHS.hasSubRanges()) {
2493 unsigned Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
2494 : TRI->getSubRegIndexLaneMask(DstIdx);
2495 // LHS must support subregs or we wouldn't be in this codepath.
2497 LHS.createSubRangeFrom(Allocator, Mask, LHS);
2498 } else if (DstIdx != 0) {
2499 // Transform LHS lanemasks to new register class if necessary.
2500 for (LiveInterval::SubRange &R : LHS.subranges()) {
2501 unsigned Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
2505 DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
2506 << ' ' << LHS << '\n');
2508 // Determine lanemasks of RHS in the coalesced register and merge subranges.
2509 unsigned SrcIdx = CP.getSrcIdx();
2510 if (!RHS.hasSubRanges()) {
2511 unsigned Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
2512 : TRI->getSubRegIndexLaneMask(SrcIdx);
2513 mergeSubRangeInto(LHS, RHS, Mask, CP);
2515 // Pair up subranges and merge.
2516 for (LiveInterval::SubRange &R : RHS.subranges()) {
2517 unsigned Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
2518 mergeSubRangeInto(LHS, R, Mask, CP);
2522 DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
2524 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
2525 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
2528 // The merging algorithm in LiveInterval::join() can't handle conflicting
2529 // value mappings, so we need to remove any live ranges that overlap a
2530 // CR_Replace resolution. Collect a set of end points that can be used to
2531 // restore the live range after joining.
2532 SmallVector<SlotIndex, 8> EndPoints;
2533 LHSVals.pruneValues(RHSVals, EndPoints, true);
2534 RHSVals.pruneValues(LHSVals, EndPoints, true);
2536 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
2537 // registers to require trimming.
2538 SmallVector<unsigned, 8> ShrinkRegs;
2539 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2540 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
2541 while (!ShrinkRegs.empty())
2542 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
2544 // Join RHS into LHS.
2545 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
2547 // Kill flags are going to be wrong if the live ranges were overlapping.
2548 // Eventually, we should simply clear all kill flags when computing live
2549 // ranges. They are reinserted after register allocation.
2550 MRI->clearKillFlags(LHS.reg);
2551 MRI->clearKillFlags(RHS.reg);
2553 if (!EndPoints.empty()) {
2554 // Recompute the parts of the live range we had to remove because of
2555 // CR_Replace conflicts.
2556 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2557 << " points: " << LHS << '\n');
2558 LIS->extendToIndices((LiveRange&)LHS, EndPoints);
2564 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
2565 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
2569 /// Information concerning MBB coalescing priority.
2570 struct MBBPriorityInfo {
2571 MachineBasicBlock *MBB;
2575 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
2576 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
2580 /// C-style comparator that sorts first based on the loop depth of the basic
2581 /// block (the unsigned), and then on the MBB number.
2583 /// EnableGlobalCopies assumes that the primary sort key is loop depth.
2584 static int compareMBBPriority(const MBBPriorityInfo *LHS,
2585 const MBBPriorityInfo *RHS) {
2586 // Deeper loops first
2587 if (LHS->Depth != RHS->Depth)
2588 return LHS->Depth > RHS->Depth ? -1 : 1;
2590 // Try to unsplit critical edges next.
2591 if (LHS->IsSplit != RHS->IsSplit)
2592 return LHS->IsSplit ? -1 : 1;
2594 // Prefer blocks that are more connected in the CFG. This takes care of
2595 // the most difficult copies first while intervals are short.
2596 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
2597 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
2599 return cl > cr ? -1 : 1;
2601 // As a last resort, sort by block number.
2602 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
2605 /// \returns true if the given copy uses or defines a local live range.
2606 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
2607 if (!Copy->isCopy())
2610 if (Copy->getOperand(1).isUndef())
2613 unsigned SrcReg = Copy->getOperand(1).getReg();
2614 unsigned DstReg = Copy->getOperand(0).getReg();
2615 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
2616 || TargetRegisterInfo::isPhysicalRegister(DstReg))
2619 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
2620 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
2623 bool RegisterCoalescer::
2624 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2625 bool Progress = false;
2626 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2629 // Skip instruction pointers that have already been erased, for example by
2630 // dead code elimination.
2631 if (ErasedInstrs.erase(CurrList[i])) {
2632 CurrList[i] = nullptr;
2636 bool Success = joinCopy(CurrList[i], Again);
2637 Progress |= Success;
2638 if (Success || !Again)
2639 CurrList[i] = nullptr;
2645 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2646 DEBUG(dbgs() << MBB->getName() << ":\n");
2648 // Collect all copy-like instructions in MBB. Don't start coalescing anything
2649 // yet, it might invalidate the iterator.
2650 const unsigned PrevSize = WorkList.size();
2651 if (JoinGlobalCopies) {
2652 // Coalesce copies bottom-up to coalesce local defs before local uses. They
2653 // are not inherently easier to resolve, but slightly preferable until we
2654 // have local live range splitting. In particular this is required by
2655 // cmp+jmp macro fusion.
2656 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2658 if (!MII->isCopyLike())
2660 if (isLocalCopy(&(*MII), LIS))
2661 LocalWorkList.push_back(&(*MII));
2663 WorkList.push_back(&(*MII));
2667 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2669 if (MII->isCopyLike())
2670 WorkList.push_back(MII);
2672 // Try coalescing the collected copies immediately, and remove the nulls.
2673 // This prevents the WorkList from getting too large since most copies are
2674 // joinable on the first attempt.
2675 MutableArrayRef<MachineInstr*>
2676 CurrList(WorkList.begin() + PrevSize, WorkList.end());
2677 if (copyCoalesceWorkList(CurrList))
2678 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2679 (MachineInstr*)nullptr), WorkList.end());
2682 void RegisterCoalescer::coalesceLocals() {
2683 copyCoalesceWorkList(LocalWorkList);
2684 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2685 if (LocalWorkList[j])
2686 WorkList.push_back(LocalWorkList[j]);
2688 LocalWorkList.clear();
2691 void RegisterCoalescer::joinAllIntervals() {
2692 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2693 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2695 std::vector<MBBPriorityInfo> MBBs;
2696 MBBs.reserve(MF->size());
2697 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2698 MachineBasicBlock *MBB = I;
2699 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2700 JoinSplitEdges && isSplitEdge(MBB)));
2702 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
2704 // Coalesce intervals in MBB priority order.
2705 unsigned CurrDepth = UINT_MAX;
2706 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2707 // Try coalescing the collected local copies for deeper loops.
2708 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
2710 CurrDepth = MBBs[i].Depth;
2712 copyCoalesceInMBB(MBBs[i].MBB);
2716 // Joining intervals can allow other intervals to be joined. Iteratively join
2717 // until we make no progress.
2718 while (copyCoalesceWorkList(WorkList))
2722 void RegisterCoalescer::releaseMemory() {
2723 ErasedInstrs.clear();
2726 InflateRegs.clear();
2729 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2731 MRI = &fn.getRegInfo();
2732 TM = &fn.getTarget();
2733 TRI = TM->getSubtargetImpl()->getRegisterInfo();
2734 TII = TM->getSubtargetImpl()->getInstrInfo();
2735 LIS = &getAnalysis<LiveIntervals>();
2736 AA = &getAnalysis<AliasAnalysis>();
2737 Loops = &getAnalysis<MachineLoopInfo>();
2739 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
2740 if (EnableGlobalCopies == cl::BOU_UNSET)
2741 JoinGlobalCopies = ST.useMachineScheduler();
2743 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2745 // The MachineScheduler does not currently require JoinSplitEdges. This will
2746 // either be enabled unconditionally or replaced by a more general live range
2747 // splitting optimization.
2748 JoinSplitEdges = EnableJoinSplits;
2750 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2751 << "********** Function: " << MF->getName() << '\n');
2753 if (VerifyCoalescing)
2754 MF->verify(this, "Before register coalescing");
2756 RegClassInfo.runOnMachineFunction(fn);
2758 // Join (coalesce) intervals if requested.
2762 // After deleting a lot of copies, register classes may be less constrained.
2763 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2765 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2766 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2768 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2769 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2770 unsigned Reg = InflateRegs[i];
2771 if (MRI->reg_nodbg_empty(Reg))
2773 if (MRI->recomputeRegClass(Reg, *TM)) {
2774 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2775 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
2776 LiveInterval &LI = LIS->getInterval(Reg);
2777 unsigned MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
2779 // If the inflated register class does not support subregisters anymore
2780 // remove the subranges.
2781 LI.clearSubRanges();
2784 // If subranges are still supported, then the same subregs should still
2786 for (LiveInterval::SubRange &S : LI.subranges()) {
2787 assert ((S.LaneMask & ~MaxMask) == 0);
2796 if (VerifyCoalescing)
2797 MF->verify(this, "After register coalescing");
2801 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {