1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15 
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/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/CodeGen/VirtRegMap.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <algorithm>
42 #include <cmath>
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "regalloc"
46 
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");
55 
56 static cl::opt<bool>
57 EnableJoining("join-liveintervals",
58               cl::desc("Coalesce copies (default=true)"),
59               cl::init(true));
60 
61 static cl::opt<bool> UseTerminalRule("terminal-rule",
62                                      cl::desc("Apply the terminal rule"),
63                                      cl::init(false), cl::Hidden);
64 
65 /// Temporary flag to test critical edge unsplitting.
66 static cl::opt<bool>
67 EnableJoinSplits("join-splitedges",
68   cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
69 
70 /// Temporary flag to test global copy optimization.
71 static cl::opt<cl::boolOrDefault>
72 EnableGlobalCopies("join-globalcopies",
73   cl::desc("Coalesce copies that span blocks (default=subtarget)"),
74   cl::init(cl::BOU_UNSET), cl::Hidden);
75 
76 static cl::opt<bool>
77 VerifyCoalescing("verify-coalescing",
78          cl::desc("Verify machine instrs before and after register coalescing"),
79          cl::Hidden);
80 
81 namespace {
82   class RegisterCoalescer : public MachineFunctionPass,
83                             private LiveRangeEdit::Delegate {
84     MachineFunction* MF;
85     MachineRegisterInfo* MRI;
86     const TargetMachine* TM;
87     const TargetRegisterInfo* TRI;
88     const TargetInstrInfo* TII;
89     LiveIntervals *LIS;
90     const MachineLoopInfo* Loops;
91     AliasAnalysis *AA;
92     RegisterClassInfo RegClassInfo;
93 
94     /// A LaneMask to remember on which subregister live ranges we need to call
95     /// shrinkToUses() later.
96     LaneBitmask ShrinkMask;
97 
98     /// True if the main range of the currently coalesced intervals should be
99     /// checked for smaller live intervals.
100     bool ShrinkMainRange;
101 
102     /// \brief True if the coalescer should aggressively coalesce global copies
103     /// in favor of keeping local copies.
104     bool JoinGlobalCopies;
105 
106     /// \brief True if the coalescer should aggressively coalesce fall-thru
107     /// blocks exclusively containing copies.
108     bool JoinSplitEdges;
109 
110     /// Copy instructions yet to be coalesced.
111     SmallVector<MachineInstr*, 8> WorkList;
112     SmallVector<MachineInstr*, 8> LocalWorkList;
113 
114     /// Set of instruction pointers that have been erased, and
115     /// that may be present in WorkList.
116     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
117 
118     /// Dead instructions that are about to be deleted.
119     SmallVector<MachineInstr*, 8> DeadDefs;
120 
121     /// Virtual registers to be considered for register class inflation.
122     SmallVector<unsigned, 8> InflateRegs;
123 
124     /// Recursively eliminate dead defs in DeadDefs.
125     void eliminateDeadDefs();
126 
127     /// LiveRangeEdit callback for eliminateDeadDefs().
128     void LRE_WillEraseInstruction(MachineInstr *MI) override;
129 
130     /// Coalesce the LocalWorkList.
131     void coalesceLocals();
132 
133     /// Join compatible live intervals
134     void joinAllIntervals();
135 
136     /// Coalesce copies in the specified MBB, putting
137     /// copies that cannot yet be coalesced into WorkList.
138     void copyCoalesceInMBB(MachineBasicBlock *MBB);
139 
140     /// Tries to coalesce all copies in CurrList. Returns true if any progress
141     /// was made.
142     bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
143 
144     /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
145     /// src/dst of the copy instruction CopyMI.  This returns true if the copy
146     /// was successfully coalesced away. If it is not currently possible to
147     /// coalesce this interval, but it may be possible if other things get
148     /// coalesced, then it returns true by reference in 'Again'.
149     bool joinCopy(MachineInstr *TheCopy, bool &Again);
150 
151     /// Attempt to join these two intervals.  On failure, this
152     /// returns false.  The output "SrcInt" will not have been modified, so we
153     /// can use this information below to update aliases.
154     bool joinIntervals(CoalescerPair &CP);
155 
156     /// Attempt joining two virtual registers. Return true on success.
157     bool joinVirtRegs(CoalescerPair &CP);
158 
159     /// Attempt joining with a reserved physreg.
160     bool joinReservedPhysReg(CoalescerPair &CP);
161 
162     /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
163     /// Subranges in @p LI which only partially interfere with the desired
164     /// LaneMask are split as necessary. @p LaneMask are the lanes that
165     /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
166     /// lanemasks already adjusted to the coalesced register.
167     void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
168                            LaneBitmask LaneMask, CoalescerPair &CP);
169 
170     /// Join the liveranges of two subregisters. Joins @p RRange into
171     /// @p LRange, @p RRange may be invalid afterwards.
172     void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
173                           LaneBitmask LaneMask, const CoalescerPair &CP);
174 
175     /// We found a non-trivially-coalescable copy. If the source value number is
176     /// defined by a copy from the destination reg see if we can merge these two
177     /// destination reg valno# into a single value number, eliminating a copy.
178     /// This returns true if an interval was modified.
179     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
180 
181     /// Return true if there are definitions of IntB
182     /// other than BValNo val# that can reach uses of AValno val# of IntA.
183     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
184                               VNInfo *AValNo, VNInfo *BValNo);
185 
186     /// We found a non-trivially-coalescable copy.
187     /// If the source value number is defined by a commutable instruction and
188     /// its other operand is coalesced to the copy dest register, see if we
189     /// can transform the copy into a noop by commuting the definition.
190     /// This returns true if an interval was modified.
191     bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
192 
193     /// We found a copy which can be moved to its less frequent predecessor.
194     bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI);
195 
196     /// If the source of a copy is defined by a
197     /// trivial computation, replace the copy by rematerialize the definition.
198     bool reMaterializeTrivialDef(const CoalescerPair &CP, MachineInstr *CopyMI,
199                                  bool &IsDefCopy);
200 
201     /// Return true if a copy involving a physreg should be joined.
202     bool canJoinPhys(const CoalescerPair &CP);
203 
204     /// Replace all defs and uses of SrcReg to DstReg and update the subregister
205     /// number if it is not zero. If DstReg is a physical register and the
206     /// existing subregister number of the def / use being updated is not zero,
207     /// make sure to set it to the correct physical subregister.
208     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
209 
210     /// If the given machine operand reads only undefined lanes add an undef
211     /// flag.
212     /// This can happen when undef uses were previously concealed by a copy
213     /// which we coalesced. Example:
214     ///    %vreg0:sub0<def,read-undef> = ...
215     ///    %vreg1 = COPY %vreg0       <-- Coalescing COPY reveals undef
216     ///           = use %vreg1:sub1   <-- hidden undef use
217     void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
218                       MachineOperand &MO, unsigned SubRegIdx);
219 
220     /// Handle copies of undef values.
221     /// Returns true if @p CopyMI was a copy of an undef value and eliminated.
222     bool eliminateUndefCopy(MachineInstr *CopyMI);
223 
224     /// Check whether or not we should apply the terminal rule on the
225     /// destination (Dst) of \p Copy.
226     /// When the terminal rule applies, Copy is not profitable to
227     /// coalesce.
228     /// Dst is terminal if it has exactly one affinity (Dst, Src) and
229     /// at least one interference (Dst, Dst2). If Dst is terminal, the
230     /// terminal rule consists in checking that at least one of
231     /// interfering node, say Dst2, has an affinity of equal or greater
232     /// weight with Src.
233     /// In that case, Dst2 and Dst will not be able to be both coalesced
234     /// with Src. Since Dst2 exposes more coalescing opportunities than
235     /// Dst, we can drop \p Copy.
236     bool applyTerminalRule(const MachineInstr &Copy) const;
237 
238     /// Wrapper method for \see LiveIntervals::shrinkToUses.
239     /// This method does the proper fixing of the live-ranges when the afore
240     /// mentioned method returns true.
241     void shrinkToUses(LiveInterval *LI,
242                       SmallVectorImpl<MachineInstr * > *Dead = nullptr) {
243       if (LIS->shrinkToUses(LI, Dead)) {
244         /// Check whether or not \p LI is composed by multiple connected
245         /// components and if that is the case, fix that.
246         SmallVector<LiveInterval*, 8> SplitLIs;
247         LIS->splitSeparateComponents(*LI, SplitLIs);
248       }
249     }
250 
251   public:
252     static char ID; ///< Class identification, replacement for typeinfo
253     RegisterCoalescer() : MachineFunctionPass(ID) {
254       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
255     }
256 
257     void getAnalysisUsage(AnalysisUsage &AU) const override;
258 
259     void releaseMemory() override;
260 
261     /// This is the pass entry point.
262     bool runOnMachineFunction(MachineFunction&) override;
263 
264     /// Implement the dump method.
265     void print(raw_ostream &O, const Module* = nullptr) const override;
266   };
267 } // end anonymous namespace
268 
269 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
270 
271 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
272                       "Simple Register Coalescing", false, false)
273 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
274 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
275 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
276 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
277 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
278                     "Simple Register Coalescing", false, false)
279 
280 char RegisterCoalescer::ID = 0;
281 
282 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
283                         unsigned &Src, unsigned &Dst,
284                         unsigned &SrcSub, unsigned &DstSub) {
285   if (MI->isCopy()) {
286     Dst = MI->getOperand(0).getReg();
287     DstSub = MI->getOperand(0).getSubReg();
288     Src = MI->getOperand(1).getReg();
289     SrcSub = MI->getOperand(1).getSubReg();
290   } else if (MI->isSubregToReg()) {
291     Dst = MI->getOperand(0).getReg();
292     DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
293                                       MI->getOperand(3).getImm());
294     Src = MI->getOperand(2).getReg();
295     SrcSub = MI->getOperand(2).getSubReg();
296   } else
297     return false;
298   return true;
299 }
300 
301 /// Return true if this block should be vacated by the coalescer to eliminate
302 /// branches. The important cases to handle in the coalescer are critical edges
303 /// split during phi elimination which contain only copies. Simple blocks that
304 /// contain non-branches should also be vacated, but this can be handled by an
305 /// earlier pass similar to early if-conversion.
306 static bool isSplitEdge(const MachineBasicBlock *MBB) {
307   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
308     return false;
309 
310   for (const auto &MI : *MBB) {
311     if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
312       return false;
313   }
314   return true;
315 }
316 
317 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
318   SrcReg = DstReg = 0;
319   SrcIdx = DstIdx = 0;
320   NewRC = nullptr;
321   Flipped = CrossClass = false;
322 
323   unsigned Src, Dst, SrcSub, DstSub;
324   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
325     return false;
326   Partial = SrcSub || DstSub;
327 
328   // If one register is a physreg, it must be Dst.
329   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
330     if (TargetRegisterInfo::isPhysicalRegister(Dst))
331       return false;
332     std::swap(Src, Dst);
333     std::swap(SrcSub, DstSub);
334     Flipped = true;
335   }
336 
337   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
338 
339   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
340     // Eliminate DstSub on a physreg.
341     if (DstSub) {
342       Dst = TRI.getSubReg(Dst, DstSub);
343       if (!Dst) return false;
344       DstSub = 0;
345     }
346 
347     // Eliminate SrcSub by picking a corresponding Dst superregister.
348     if (SrcSub) {
349       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
350       if (!Dst) return false;
351     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
352       return false;
353     }
354   } else {
355     // Both registers are virtual.
356     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
357     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
358 
359     // Both registers have subreg indices.
360     if (SrcSub && DstSub) {
361       // Copies between different sub-registers are never coalescable.
362       if (Src == Dst && SrcSub != DstSub)
363         return false;
364 
365       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
366                                          SrcIdx, DstIdx);
367       if (!NewRC)
368         return false;
369     } else if (DstSub) {
370       // SrcReg will be merged with a sub-register of DstReg.
371       SrcIdx = DstSub;
372       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
373     } else if (SrcSub) {
374       // DstReg will be merged with a sub-register of SrcReg.
375       DstIdx = SrcSub;
376       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
377     } else {
378       // This is a straight copy without sub-registers.
379       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
380     }
381 
382     // The combined constraint may be impossible to satisfy.
383     if (!NewRC)
384       return false;
385 
386     // Prefer SrcReg to be a sub-register of DstReg.
387     // FIXME: Coalescer should support subregs symmetrically.
388     if (DstIdx && !SrcIdx) {
389       std::swap(Src, Dst);
390       std::swap(SrcIdx, DstIdx);
391       Flipped = !Flipped;
392     }
393 
394     CrossClass = NewRC != DstRC || NewRC != SrcRC;
395   }
396   // Check our invariants
397   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
398   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
399          "Cannot have a physical SubIdx");
400   SrcReg = Src;
401   DstReg = Dst;
402   return true;
403 }
404 
405 bool CoalescerPair::flip() {
406   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
407     return false;
408   std::swap(SrcReg, DstReg);
409   std::swap(SrcIdx, DstIdx);
410   Flipped = !Flipped;
411   return true;
412 }
413 
414 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
415   if (!MI)
416     return false;
417   unsigned Src, Dst, SrcSub, DstSub;
418   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
419     return false;
420 
421   // Find the virtual register that is SrcReg.
422   if (Dst == SrcReg) {
423     std::swap(Src, Dst);
424     std::swap(SrcSub, DstSub);
425   } else if (Src != SrcReg) {
426     return false;
427   }
428 
429   // Now check that Dst matches DstReg.
430   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
431     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
432       return false;
433     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
434     // DstSub could be set for a physreg from INSERT_SUBREG.
435     if (DstSub)
436       Dst = TRI.getSubReg(Dst, DstSub);
437     // Full copy of Src.
438     if (!SrcSub)
439       return DstReg == Dst;
440     // This is a partial register copy. Check that the parts match.
441     return TRI.getSubReg(DstReg, SrcSub) == Dst;
442   } else {
443     // DstReg is virtual.
444     if (DstReg != Dst)
445       return false;
446     // Registers match, do the subregisters line up?
447     return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
448            TRI.composeSubRegIndices(DstIdx, DstSub);
449   }
450 }
451 
452 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
453   AU.setPreservesCFG();
454   AU.addRequired<AAResultsWrapperPass>();
455   AU.addRequired<LiveIntervals>();
456   AU.addPreserved<LiveIntervals>();
457   AU.addPreserved<SlotIndexes>();
458   AU.addRequired<MachineLoopInfo>();
459   AU.addPreserved<MachineLoopInfo>();
460   AU.addPreservedID(MachineDominatorsID);
461   MachineFunctionPass::getAnalysisUsage(AU);
462 }
463 
464 void RegisterCoalescer::eliminateDeadDefs() {
465   SmallVector<unsigned, 8> NewRegs;
466   LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
467                 nullptr, this).eliminateDeadDefs(DeadDefs);
468 }
469 
470 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
471   // MI may be in WorkList. Make sure we don't visit it.
472   ErasedInstrs.insert(MI);
473 }
474 
475 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
476                                              MachineInstr *CopyMI) {
477   assert(!CP.isPartial() && "This doesn't work for partial copies.");
478   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
479 
480   LiveInterval &IntA =
481     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
482   LiveInterval &IntB =
483     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
484   SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
485 
486   // We have a non-trivially-coalescable copy with IntA being the source and
487   // IntB being the dest, thus this defines a value number in IntB.  If the
488   // source value number (in IntA) is defined by a copy from B, see if we can
489   // merge these two pieces of B into a single value number, eliminating a copy.
490   // For example:
491   //
492   //  A3 = B0
493   //    ...
494   //  B1 = A3      <- this copy
495   //
496   // In this case, B0 can be extended to where the B1 copy lives, allowing the
497   // B1 value number to be replaced with B0 (which simplifies the B
498   // liveinterval).
499 
500   // BValNo is a value number in B that is defined by a copy from A.  'B1' in
501   // the example above.
502   LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
503   if (BS == IntB.end()) return false;
504   VNInfo *BValNo = BS->valno;
505 
506   // Get the location that B is defined at.  Two options: either this value has
507   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
508   // can't process it.
509   if (BValNo->def != CopyIdx) return false;
510 
511   // AValNo is the value number in A that defines the copy, A3 in the example.
512   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
513   LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
514   // The live segment might not exist after fun with physreg coalescing.
515   if (AS == IntA.end()) return false;
516   VNInfo *AValNo = AS->valno;
517 
518   // If AValNo is defined as a copy from IntB, we can potentially process this.
519   // Get the instruction that defines this value number.
520   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
521   // Don't allow any partial copies, even if isCoalescable() allows them.
522   if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
523     return false;
524 
525   // Get the Segment in IntB that this value number starts with.
526   LiveInterval::iterator ValS =
527     IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
528   if (ValS == IntB.end())
529     return false;
530 
531   // Make sure that the end of the live segment is inside the same block as
532   // CopyMI.
533   MachineInstr *ValSEndInst =
534     LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
535   if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
536     return false;
537 
538   // Okay, we now know that ValS ends in the same block that the CopyMI
539   // live-range starts.  If there are no intervening live segments between them
540   // in IntB, we can merge them.
541   if (ValS+1 != BS) return false;
542 
543   DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
544 
545   SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
546   // We are about to delete CopyMI, so need to remove it as the 'instruction
547   // that defines this value #'. Update the valnum with the new defining
548   // instruction #.
549   BValNo->def = FillerStart;
550 
551   // Okay, we can merge them.  We need to insert a new liverange:
552   // [ValS.end, BS.begin) of either value number, then we merge the
553   // two value numbers.
554   IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
555 
556   // Okay, merge "B1" into the same value number as "B0".
557   if (BValNo != ValS->valno)
558     IntB.MergeValueNumberInto(BValNo, ValS->valno);
559 
560   // Do the same for the subregister segments.
561   for (LiveInterval::SubRange &S : IntB.subranges()) {
562     VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
563     S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
564     VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
565     if (SubBValNo != SubValSNo)
566       S.MergeValueNumberInto(SubBValNo, SubValSNo);
567   }
568 
569   DEBUG(dbgs() << "   result = " << IntB << '\n');
570 
571   // If the source instruction was killing the source register before the
572   // merge, unset the isKill marker given the live range has been extended.
573   int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
574   if (UIdx != -1) {
575     ValSEndInst->getOperand(UIdx).setIsKill(false);
576   }
577 
578   // Rewrite the copy. If the copy instruction was killing the destination
579   // register before the merge, find the last use and trim the live range. That
580   // will also add the isKill marker.
581   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
582   if (AS->end == CopyIdx)
583     shrinkToUses(&IntA);
584 
585   ++numExtends;
586   return true;
587 }
588 
589 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
590                                              LiveInterval &IntB,
591                                              VNInfo *AValNo,
592                                              VNInfo *BValNo) {
593   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
594   // the PHI values.
595   if (LIS->hasPHIKill(IntA, AValNo))
596     return true;
597 
598   for (LiveRange::Segment &ASeg : IntA.segments) {
599     if (ASeg.valno != AValNo) continue;
600     LiveInterval::iterator BI =
601       std::upper_bound(IntB.begin(), IntB.end(), ASeg.start);
602     if (BI != IntB.begin())
603       --BI;
604     for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
605       if (BI->valno == BValNo)
606         continue;
607       if (BI->start <= ASeg.start && BI->end > ASeg.start)
608         return true;
609       if (BI->start > ASeg.start && BI->start < ASeg.end)
610         return true;
611     }
612   }
613   return false;
614 }
615 
616 /// Copy segements with value number @p SrcValNo from liverange @p Src to live
617 /// range @Dst and use value number @p DstValNo there.
618 static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo,
619                                  const LiveRange &Src, const VNInfo *SrcValNo)
620 {
621   for (const LiveRange::Segment &S : Src.segments) {
622     if (S.valno != SrcValNo)
623       continue;
624     Dst.addSegment(LiveRange::Segment(S.start, S.end, DstValNo));
625   }
626 }
627 
628 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
629                                                  MachineInstr *CopyMI) {
630   assert(!CP.isPhys());
631 
632   LiveInterval &IntA =
633       LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
634   LiveInterval &IntB =
635       LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
636 
637   // We found a non-trivially-coalescable copy with IntA being the source and
638   // IntB being the dest, thus this defines a value number in IntB.  If the
639   // source value number (in IntA) is defined by a commutable instruction and
640   // its other operand is coalesced to the copy dest register, see if we can
641   // transform the copy into a noop by commuting the definition. For example,
642   //
643   //  A3 = op A2 B0<kill>
644   //    ...
645   //  B1 = A3      <- this copy
646   //    ...
647   //     = op A3   <- more uses
648   //
649   // ==>
650   //
651   //  B2 = op B0 A2<kill>
652   //    ...
653   //  B1 = B2      <- now an identity copy
654   //    ...
655   //     = op B2   <- more uses
656 
657   // BValNo is a value number in B that is defined by a copy from A. 'B1' in
658   // the example above.
659   SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
660   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
661   assert(BValNo != nullptr && BValNo->def == CopyIdx);
662 
663   // AValNo is the value number in A that defines the copy, A3 in the example.
664   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
665   assert(AValNo && !AValNo->isUnused() && "COPY source not live");
666   if (AValNo->isPHIDef())
667     return false;
668   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
669   if (!DefMI)
670     return false;
671   if (!DefMI->isCommutable())
672     return false;
673   // If DefMI is a two-address instruction then commuting it will change the
674   // destination register.
675   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
676   assert(DefIdx != -1);
677   unsigned UseOpIdx;
678   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
679     return false;
680 
681   // FIXME: The code below tries to commute 'UseOpIdx' operand with some other
682   // commutable operand which is expressed by 'CommuteAnyOperandIndex'value
683   // passed to the method. That _other_ operand is chosen by
684   // the findCommutedOpIndices() method.
685   //
686   // That is obviously an area for improvement in case of instructions having
687   // more than 2 operands. For example, if some instruction has 3 commutable
688   // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
689   // op#2<->op#3) of commute transformation should be considered/tried here.
690   unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
691   if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
692     return false;
693 
694   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
695   unsigned NewReg = NewDstMO.getReg();
696   if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
697     return false;
698 
699   // Make sure there are no other definitions of IntB that would reach the
700   // uses which the new definition can reach.
701   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
702     return false;
703 
704   // If some of the uses of IntA.reg is already coalesced away, return false.
705   // It's not possible to determine whether it's safe to perform the coalescing.
706   for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
707     MachineInstr *UseMI = MO.getParent();
708     unsigned OpNo = &MO - &UseMI->getOperand(0);
709     SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
710     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
711     if (US == IntA.end() || US->valno != AValNo)
712       continue;
713     // If this use is tied to a def, we can't rewrite the register.
714     if (UseMI->isRegTiedToDefOperand(OpNo))
715       return false;
716   }
717 
718   DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
719                << *DefMI);
720 
721   // At this point we have decided that it is legal to do this
722   // transformation.  Start by commuting the instruction.
723   MachineBasicBlock *MBB = DefMI->getParent();
724   MachineInstr *NewMI =
725       TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx);
726   if (!NewMI)
727     return false;
728   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
729       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
730       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
731     return false;
732   if (NewMI != DefMI) {
733     LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
734     MachineBasicBlock::iterator Pos = DefMI;
735     MBB->insert(Pos, NewMI);
736     MBB->erase(DefMI);
737   }
738 
739   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
740   // A = or A, B
741   // ...
742   // B = A
743   // ...
744   // C = A<kill>
745   // ...
746   //   = B
747 
748   // Update uses of IntA of the specific Val# with IntB.
749   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
750                                          UE = MRI->use_end();
751        UI != UE; /* ++UI is below because of possible MI removal */) {
752     MachineOperand &UseMO = *UI;
753     ++UI;
754     if (UseMO.isUndef())
755       continue;
756     MachineInstr *UseMI = UseMO.getParent();
757     if (UseMI->isDebugValue()) {
758       // FIXME These don't have an instruction index.  Not clear we have enough
759       // info to decide whether to do this replacement or not.  For now do it.
760       UseMO.setReg(NewReg);
761       continue;
762     }
763     SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
764     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
765     assert(US != IntA.end() && "Use must be live");
766     if (US->valno != AValNo)
767       continue;
768     // Kill flags are no longer accurate. They are recomputed after RA.
769     UseMO.setIsKill(false);
770     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
771       UseMO.substPhysReg(NewReg, *TRI);
772     else
773       UseMO.setReg(NewReg);
774     if (UseMI == CopyMI)
775       continue;
776     if (!UseMI->isCopy())
777       continue;
778     if (UseMI->getOperand(0).getReg() != IntB.reg ||
779         UseMI->getOperand(0).getSubReg())
780       continue;
781 
782     // This copy will become a noop. If it's defining a new val#, merge it into
783     // BValNo.
784     SlotIndex DefIdx = UseIdx.getRegSlot();
785     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
786     if (!DVNI)
787       continue;
788     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
789     assert(DVNI->def == DefIdx);
790     BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
791     for (LiveInterval::SubRange &S : IntB.subranges()) {
792       VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
793       if (!SubDVNI)
794         continue;
795       VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
796       assert(SubBValNo->def == CopyIdx);
797       S.MergeValueNumberInto(SubDVNI, SubBValNo);
798     }
799 
800     ErasedInstrs.insert(UseMI);
801     LIS->RemoveMachineInstrFromMaps(*UseMI);
802     UseMI->eraseFromParent();
803   }
804 
805   // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
806   // is updated.
807   BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
808   if (IntB.hasSubRanges()) {
809     if (!IntA.hasSubRanges()) {
810       LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(IntA.reg);
811       IntA.createSubRangeFrom(Allocator, Mask, IntA);
812     }
813     SlotIndex AIdx = CopyIdx.getRegSlot(true);
814     for (LiveInterval::SubRange &SA : IntA.subranges()) {
815       VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
816       assert(ASubValNo != nullptr);
817 
818       LaneBitmask AMask = SA.LaneMask;
819       for (LiveInterval::SubRange &SB : IntB.subranges()) {
820         LaneBitmask BMask = SB.LaneMask;
821         LaneBitmask Common = BMask & AMask;
822         if (Common.none())
823           continue;
824 
825         DEBUG( dbgs() << "\t\tCopy_Merge " << PrintLaneMask(BMask)
826                       << " into " << PrintLaneMask(Common) << '\n');
827         LaneBitmask BRest = BMask & ~AMask;
828         LiveInterval::SubRange *CommonRange;
829         if (BRest.any()) {
830           SB.LaneMask = BRest;
831           DEBUG(dbgs() << "\t\tReduce Lane to " << PrintLaneMask(BRest)
832                        << '\n');
833           // Duplicate SubRange for newly merged common stuff.
834           CommonRange = IntB.createSubRangeFrom(Allocator, Common, SB);
835         } else {
836           // We van reuse the L SubRange.
837           SB.LaneMask = Common;
838           CommonRange = &SB;
839         }
840         LiveRange RangeCopy(SB, Allocator);
841 
842         VNInfo *BSubValNo = CommonRange->getVNInfoAt(CopyIdx);
843         assert(BSubValNo->def == CopyIdx);
844         BSubValNo->def = ASubValNo->def;
845         addSegmentsWithValNo(*CommonRange, BSubValNo, SA, ASubValNo);
846         AMask &= ~BMask;
847       }
848       if (AMask.any()) {
849         DEBUG(dbgs() << "\t\tNew Lane " << PrintLaneMask(AMask) << '\n');
850         LiveRange *NewRange = IntB.createSubRange(Allocator, AMask);
851         VNInfo *BSubValNo = NewRange->getNextValue(CopyIdx, Allocator);
852         addSegmentsWithValNo(*NewRange, BSubValNo, SA, ASubValNo);
853       }
854     }
855   }
856 
857   BValNo->def = AValNo->def;
858   addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
859   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
860 
861   LIS->removeVRegDefAt(IntA, AValNo->def);
862 
863   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
864   ++numCommutes;
865   return true;
866 }
867 
868 /// For copy B = A in BB2, if A is defined by A = B in BB0 which is a
869 /// predecessor of BB2, and if B is not redefined on the way from A = B
870 /// in BB2 to B = A in BB2, B = A in BB2 is partially redundant if the
871 /// execution goes through the path from BB0 to BB2. We may move B = A
872 /// to the predecessor without such reversed copy.
873 /// So we will transform the program from:
874 ///   BB0:
875 ///      A = B;    BB1:
876 ///       ...         ...
877 ///     /     \      /
878 ///             BB2:
879 ///               ...
880 ///               B = A;
881 ///
882 /// to:
883 ///
884 ///   BB0:         BB1:
885 ///      A = B;        ...
886 ///       ...          B = A;
887 ///     /     \       /
888 ///             BB2:
889 ///               ...
890 ///
891 /// A special case is when BB0 and BB2 are the same BB which is the only
892 /// BB in a loop:
893 ///   BB1:
894 ///        ...
895 ///   BB0/BB2:  ----
896 ///        B = A;   |
897 ///        ...      |
898 ///        A = B;   |
899 ///          |-------
900 ///          |
901 /// We may hoist B = A from BB0/BB2 to BB1.
902 ///
903 /// The major preconditions for correctness to remove such partial
904 /// redundancy include:
905 /// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of
906 ///    the PHI is defined by the reversed copy A = B in BB0.
907 /// 2. No B is referenced from the start of BB2 to B = A.
908 /// 3. No B is defined from A = B to the end of BB0.
909 /// 4. BB1 has only one successor.
910 ///
911 /// 2 and 4 implicitly ensure B is not live at the end of BB1.
912 /// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a
913 /// colder place, which not only prevent endless loop, but also make sure
914 /// the movement of copy is beneficial.
915 bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP,
916                                                 MachineInstr &CopyMI) {
917   assert(!CP.isPhys());
918   if (!CopyMI.isFullCopy())
919     return false;
920 
921   MachineBasicBlock &MBB = *CopyMI.getParent();
922   if (MBB.isEHPad())
923     return false;
924 
925   if (MBB.pred_size() != 2)
926     return false;
927 
928   LiveInterval &IntA =
929       LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
930   LiveInterval &IntB =
931       LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
932 
933   // A is defined by PHI at the entry of MBB.
934   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
935   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx);
936   assert(AValNo && !AValNo->isUnused() && "COPY source not live");
937   if (!AValNo->isPHIDef())
938     return false;
939 
940   // No B is referenced before CopyMI in MBB.
941   if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
942     return false;
943 
944   // MBB has two predecessors: one contains A = B so no copy will be inserted
945   // for it. The other one will have a copy moved from MBB.
946   bool FoundReverseCopy = false;
947   MachineBasicBlock *CopyLeftBB = nullptr;
948   for (MachineBasicBlock *Pred : MBB.predecessors()) {
949     VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred));
950     MachineInstr *DefMI = LIS->getInstructionFromIndex(PVal->def);
951     if (!DefMI || !DefMI->isFullCopy()) {
952       CopyLeftBB = Pred;
953       continue;
954     }
955     // Check DefMI is a reverse copy and it is in BB Pred.
956     if (DefMI->getOperand(0).getReg() != IntA.reg ||
957         DefMI->getOperand(1).getReg() != IntB.reg ||
958         DefMI->getParent() != Pred) {
959       CopyLeftBB = Pred;
960       continue;
961     }
962     // If there is any other def of B after DefMI and before the end of Pred,
963     // we need to keep the copy of B = A at the end of Pred if we remove
964     // B = A from MBB.
965     bool ValB_Changed = false;
966     for (auto VNI : IntB.valnos) {
967       if (VNI->isUnused())
968         continue;
969       if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
970         ValB_Changed = true;
971         break;
972       }
973     }
974     if (ValB_Changed) {
975       CopyLeftBB = Pred;
976       continue;
977     }
978     FoundReverseCopy = true;
979   }
980 
981   // If no reverse copy is found in predecessors, nothing to do.
982   if (!FoundReverseCopy)
983     return false;
984 
985   // If CopyLeftBB is nullptr, it means every predecessor of MBB contains
986   // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated.
987   // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and
988   // update IntA/IntB.
989   //
990   // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so
991   // MBB is hotter than CopyLeftBB.
992   if (CopyLeftBB && CopyLeftBB->succ_size() > 1)
993     return false;
994 
995   // Now ok to move copy.
996   if (CopyLeftBB) {
997     DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to BB#"
998                  << CopyLeftBB->getNumber() << '\t' << CopyMI);
999 
1000     // Insert new copy to CopyLeftBB.
1001     auto InsPos = CopyLeftBB->getFirstTerminator();
1002     MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(),
1003                                       TII->get(TargetOpcode::COPY), IntB.reg)
1004                                   .addReg(IntA.reg);
1005     SlotIndex NewCopyIdx =
1006         LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot();
1007     VNInfo *VNI = IntB.getNextValue(NewCopyIdx, LIS->getVNInfoAllocator());
1008     IntB.createDeadDef(VNI);
1009   } else {
1010     DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from BB#"
1011                  << MBB.getNumber() << '\t' << CopyMI);
1012   }
1013 
1014   // Remove CopyMI.
1015   SmallVector<SlotIndex, 8> EndPoints;
1016   VNInfo *BValNo = IntB.Query(CopyIdx.getRegSlot()).valueOutOrDead();
1017   LIS->pruneValue(IntB, CopyIdx.getRegSlot(), &EndPoints);
1018   BValNo->markUnused();
1019   LIS->RemoveMachineInstrFromMaps(CopyMI);
1020   CopyMI.eraseFromParent();
1021 
1022   // Extend IntB to the EndPoints of its original live interval.
1023   LIS->extendToIndices(IntB, EndPoints);
1024 
1025   shrinkToUses(&IntA);
1026   return true;
1027 }
1028 
1029 /// Returns true if @p MI defines the full vreg @p Reg, as opposed to just
1030 /// defining a subregister.
1031 static bool definesFullReg(const MachineInstr &MI, unsigned Reg) {
1032   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) &&
1033          "This code cannot handle physreg aliasing");
1034   for (const MachineOperand &Op : MI.operands()) {
1035     if (!Op.isReg() || !Op.isDef() || Op.getReg() != Reg)
1036       continue;
1037     // Return true if we define the full register or don't care about the value
1038     // inside other subregisters.
1039     if (Op.getSubReg() == 0 || Op.isUndef())
1040       return true;
1041   }
1042   return false;
1043 }
1044 
1045 bool RegisterCoalescer::reMaterializeTrivialDef(const CoalescerPair &CP,
1046                                                 MachineInstr *CopyMI,
1047                                                 bool &IsDefCopy) {
1048   IsDefCopy = false;
1049   unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
1050   unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
1051   unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
1052   unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
1053   if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
1054     return false;
1055 
1056   LiveInterval &SrcInt = LIS->getInterval(SrcReg);
1057   SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1058   VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
1059   assert(ValNo && "CopyMI input register not live");
1060   if (ValNo->isPHIDef() || ValNo->isUnused())
1061     return false;
1062   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
1063   if (!DefMI)
1064     return false;
1065   if (DefMI->isCopyLike()) {
1066     IsDefCopy = true;
1067     return false;
1068   }
1069   if (!TII->isAsCheapAsAMove(*DefMI))
1070     return false;
1071   if (!TII->isTriviallyReMaterializable(*DefMI, AA))
1072     return false;
1073   if (!definesFullReg(*DefMI, SrcReg))
1074     return false;
1075   bool SawStore = false;
1076   if (!DefMI->isSafeToMove(AA, SawStore))
1077     return false;
1078   const MCInstrDesc &MCID = DefMI->getDesc();
1079   if (MCID.getNumDefs() != 1)
1080     return false;
1081   // Only support subregister destinations when the def is read-undef.
1082   MachineOperand &DstOperand = CopyMI->getOperand(0);
1083   unsigned CopyDstReg = DstOperand.getReg();
1084   if (DstOperand.getSubReg() && !DstOperand.isUndef())
1085     return false;
1086 
1087   // If both SrcIdx and DstIdx are set, correct rematerialization would widen
1088   // the register substantially (beyond both source and dest size). This is bad
1089   // for performance since it can cascade through a function, introducing many
1090   // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
1091   // around after a few subreg copies).
1092   if (SrcIdx && DstIdx)
1093     return false;
1094 
1095   const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
1096   if (!DefMI->isImplicitDef()) {
1097     if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1098       unsigned NewDstReg = DstReg;
1099 
1100       unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
1101                                               DefMI->getOperand(0).getSubReg());
1102       if (NewDstIdx)
1103         NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
1104 
1105       // Finally, make sure that the physical subregister that will be
1106       // constructed later is permitted for the instruction.
1107       if (!DefRC->contains(NewDstReg))
1108         return false;
1109     } else {
1110       // Theoretically, some stack frame reference could exist. Just make sure
1111       // it hasn't actually happened.
1112       assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
1113              "Only expect to deal with virtual or physical registers");
1114     }
1115   }
1116 
1117   DebugLoc DL = CopyMI->getDebugLoc();
1118   MachineBasicBlock *MBB = CopyMI->getParent();
1119   MachineBasicBlock::iterator MII =
1120     std::next(MachineBasicBlock::iterator(CopyMI));
1121   TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, *DefMI, *TRI);
1122   MachineInstr &NewMI = *std::prev(MII);
1123   NewMI.setDebugLoc(DL);
1124 
1125   // In a situation like the following:
1126   //     %vreg0:subreg = instr              ; DefMI, subreg = DstIdx
1127   //     %vreg1        = copy %vreg0:subreg ; CopyMI, SrcIdx = 0
1128   // instead of widening %vreg1 to the register class of %vreg0 simply do:
1129   //     %vreg1 = instr
1130   const TargetRegisterClass *NewRC = CP.getNewRC();
1131   if (DstIdx != 0) {
1132     MachineOperand &DefMO = NewMI.getOperand(0);
1133     if (DefMO.getSubReg() == DstIdx) {
1134       assert(SrcIdx == 0 && CP.isFlipped()
1135              && "Shouldn't have SrcIdx+DstIdx at this point");
1136       const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
1137       const TargetRegisterClass *CommonRC =
1138         TRI->getCommonSubClass(DefRC, DstRC);
1139       if (CommonRC != nullptr) {
1140         NewRC = CommonRC;
1141         DstIdx = 0;
1142         DefMO.setSubReg(0);
1143         DefMO.setIsUndef(false); // Only subregs can have def+undef.
1144       }
1145     }
1146   }
1147 
1148   // CopyMI may have implicit operands, save them so that we can transfer them
1149   // over to the newly materialized instruction after CopyMI is removed.
1150   SmallVector<MachineOperand, 4> ImplicitOps;
1151   ImplicitOps.reserve(CopyMI->getNumOperands() -
1152                       CopyMI->getDesc().getNumOperands());
1153   for (unsigned I = CopyMI->getDesc().getNumOperands(),
1154                 E = CopyMI->getNumOperands();
1155        I != E; ++I) {
1156     MachineOperand &MO = CopyMI->getOperand(I);
1157     if (MO.isReg()) {
1158       assert(MO.isImplicit() && "No explicit operands after implict operands.");
1159       // Discard VReg implicit defs.
1160       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1161         ImplicitOps.push_back(MO);
1162     }
1163   }
1164 
1165   LIS->ReplaceMachineInstrInMaps(*CopyMI, NewMI);
1166   CopyMI->eraseFromParent();
1167   ErasedInstrs.insert(CopyMI);
1168 
1169   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
1170   // We need to remember these so we can add intervals once we insert
1171   // NewMI into SlotIndexes.
1172   SmallVector<unsigned, 4> NewMIImplDefs;
1173   for (unsigned i = NewMI.getDesc().getNumOperands(),
1174                 e = NewMI.getNumOperands();
1175        i != e; ++i) {
1176     MachineOperand &MO = NewMI.getOperand(i);
1177     if (MO.isReg() && MO.isDef()) {
1178       assert(MO.isImplicit() && MO.isDead() &&
1179              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
1180       NewMIImplDefs.push_back(MO.getReg());
1181     }
1182   }
1183 
1184   if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
1185     unsigned NewIdx = NewMI.getOperand(0).getSubReg();
1186 
1187     if (DefRC != nullptr) {
1188       if (NewIdx)
1189         NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
1190       else
1191         NewRC = TRI->getCommonSubClass(NewRC, DefRC);
1192       assert(NewRC && "subreg chosen for remat incompatible with instruction");
1193     }
1194     // Remap subranges to new lanemask and change register class.
1195     LiveInterval &DstInt = LIS->getInterval(DstReg);
1196     for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1197       SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
1198     }
1199     MRI->setRegClass(DstReg, NewRC);
1200 
1201     // Update machine operands and add flags.
1202     updateRegDefsUses(DstReg, DstReg, DstIdx);
1203     NewMI.getOperand(0).setSubReg(NewIdx);
1204     // Add dead subregister definitions if we are defining the whole register
1205     // but only part of it is live.
1206     // This could happen if the rematerialization instruction is rematerializing
1207     // more than actually is used in the register.
1208     // An example would be:
1209     // vreg1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs
1210     // ; Copying only part of the register here, but the rest is undef.
1211     // vreg2:sub_16bit<def, read-undef> = COPY vreg1:sub_16bit
1212     // ==>
1213     // ; Materialize all the constants but only using one
1214     // vreg2 = LOAD_CONSTANTS 5, 8
1215     //
1216     // at this point for the part that wasn't defined before we could have
1217     // subranges missing the definition.
1218     if (NewIdx == 0 && DstInt.hasSubRanges()) {
1219       SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1220       SlotIndex DefIndex =
1221           CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
1222       LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg);
1223       VNInfo::Allocator& Alloc = LIS->getVNInfoAllocator();
1224       for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1225         if (!SR.liveAt(DefIndex))
1226           SR.createDeadDef(DefIndex, Alloc);
1227         MaxMask &= ~SR.LaneMask;
1228       }
1229       if (MaxMask.any()) {
1230         LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask);
1231         SR->createDeadDef(DefIndex, Alloc);
1232       }
1233     }
1234   } else if (NewMI.getOperand(0).getReg() != CopyDstReg) {
1235     // The New instruction may be defining a sub-register of what's actually
1236     // been asked for. If so it must implicitly define the whole thing.
1237     assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
1238            "Only expect virtual or physical registers in remat");
1239     NewMI.getOperand(0).setIsDead(true);
1240     NewMI.addOperand(MachineOperand::CreateReg(
1241         CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/));
1242     // Record small dead def live-ranges for all the subregisters
1243     // of the destination register.
1244     // Otherwise, variables that live through may miss some
1245     // interferences, thus creating invalid allocation.
1246     // E.g., i386 code:
1247     // vreg1 = somedef ; vreg1 GR8
1248     // vreg2 = remat ; vreg2 GR32
1249     // CL = COPY vreg2.sub_8bit
1250     // = somedef vreg1 ; vreg1 GR8
1251     // =>
1252     // vreg1 = somedef ; vreg1 GR8
1253     // ECX<def, dead> = remat ; CL<imp-def>
1254     // = somedef vreg1 ; vreg1 GR8
1255     // vreg1 will see the inteferences with CL but not with CH since
1256     // no live-ranges would have been created for ECX.
1257     // Fix that!
1258     SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1259     for (MCRegUnitIterator Units(NewMI.getOperand(0).getReg(), TRI);
1260          Units.isValid(); ++Units)
1261       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1262         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1263   }
1264 
1265   if (NewMI.getOperand(0).getSubReg())
1266     NewMI.getOperand(0).setIsUndef();
1267 
1268   // Transfer over implicit operands to the rematerialized instruction.
1269   for (MachineOperand &MO : ImplicitOps)
1270     NewMI.addOperand(MO);
1271 
1272   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1273   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
1274     unsigned Reg = NewMIImplDefs[i];
1275     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1276       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
1277         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1278   }
1279 
1280   DEBUG(dbgs() << "Remat: " << NewMI);
1281   ++NumReMats;
1282 
1283   // The source interval can become smaller because we removed a use.
1284   shrinkToUses(&SrcInt, &DeadDefs);
1285   if (!DeadDefs.empty()) {
1286     // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1287     // to describe DstReg instead.
1288     for (MachineOperand &UseMO : MRI->use_operands(SrcReg)) {
1289       MachineInstr *UseMI = UseMO.getParent();
1290       if (UseMI->isDebugValue()) {
1291         UseMO.setReg(DstReg);
1292         DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1293       }
1294     }
1295     eliminateDeadDefs();
1296   }
1297 
1298   return true;
1299 }
1300 
1301 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1302   // ProcessImpicitDefs may leave some copies of <undef> values, it only removes
1303   // local variables. When we have a copy like:
1304   //
1305   //   %vreg1 = COPY %vreg2<undef>
1306   //
1307   // We delete the copy and remove the corresponding value number from %vreg1.
1308   // Any uses of that value number are marked as <undef>.
1309 
1310   // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1311   // CoalescerPair may have a new register class with adjusted subreg indices
1312   // at this point.
1313   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1314   isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1315 
1316   SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
1317   const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1318   // CopyMI is undef iff SrcReg is not live before the instruction.
1319   if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1320     LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1321     for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1322       if ((SR.LaneMask & SrcMask).none())
1323         continue;
1324       if (SR.liveAt(Idx))
1325         return false;
1326     }
1327   } else if (SrcLI.liveAt(Idx))
1328     return false;
1329 
1330   DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1331 
1332   // Remove any DstReg segments starting at the instruction.
1333   LiveInterval &DstLI = LIS->getInterval(DstReg);
1334   SlotIndex RegIndex = Idx.getRegSlot();
1335   // Remove value or merge with previous one in case of a subregister def.
1336   if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1337     VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
1338     DstLI.MergeValueNumberInto(VNI, PrevVNI);
1339 
1340     // The affected subregister segments can be removed.
1341     LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1342     for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1343       if ((SR.LaneMask & DstMask).none())
1344         continue;
1345 
1346       VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1347       assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
1348       SR.removeValNo(SVNI);
1349     }
1350     DstLI.removeEmptySubRanges();
1351   } else
1352     LIS->removeVRegDefAt(DstLI, RegIndex);
1353 
1354   // Mark uses as undef.
1355   for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1356     if (MO.isDef() /*|| MO.isUndef()*/)
1357       continue;
1358     const MachineInstr &MI = *MO.getParent();
1359     SlotIndex UseIdx = LIS->getInstructionIndex(MI);
1360     LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1361     bool isLive;
1362     if (!UseMask.all() && DstLI.hasSubRanges()) {
1363       isLive = false;
1364       for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1365         if ((SR.LaneMask & UseMask).none())
1366           continue;
1367         if (SR.liveAt(UseIdx)) {
1368           isLive = true;
1369           break;
1370         }
1371       }
1372     } else
1373       isLive = DstLI.liveAt(UseIdx);
1374     if (isLive)
1375       continue;
1376     MO.setIsUndef(true);
1377     DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1378   }
1379 
1380   // A def of a subregister may be a use of the other subregisters, so
1381   // deleting a def of a subregister may also remove uses. Since CopyMI
1382   // is still part of the function (but about to be erased), mark all
1383   // defs of DstReg in it as <undef>, so that shrinkToUses would
1384   // ignore them.
1385   for (MachineOperand &MO : CopyMI->operands())
1386     if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1387       MO.setIsUndef(true);
1388   LIS->shrinkToUses(&DstLI);
1389 
1390   return true;
1391 }
1392 
1393 void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
1394                                      MachineOperand &MO, unsigned SubRegIdx) {
1395   LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1396   if (MO.isDef())
1397     Mask = ~Mask;
1398   bool IsUndef = true;
1399   for (const LiveInterval::SubRange &S : Int.subranges()) {
1400     if ((S.LaneMask & Mask).none())
1401       continue;
1402     if (S.liveAt(UseIdx)) {
1403       IsUndef = false;
1404       break;
1405     }
1406   }
1407   if (IsUndef) {
1408     MO.setIsUndef(true);
1409     // We found out some subregister use is actually reading an undefined
1410     // value. In some cases the whole vreg has become undefined at this
1411     // point so we have to potentially shrink the main range if the
1412     // use was ending a live segment there.
1413     LiveQueryResult Q = Int.Query(UseIdx);
1414     if (Q.valueOut() == nullptr)
1415       ShrinkMainRange = true;
1416   }
1417 }
1418 
1419 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
1420                                           unsigned DstReg,
1421                                           unsigned SubIdx) {
1422   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1423   LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1424 
1425   if (DstInt && DstInt->hasSubRanges() && DstReg != SrcReg) {
1426     for (MachineOperand &MO : MRI->reg_operands(DstReg)) {
1427       unsigned SubReg = MO.getSubReg();
1428       if (SubReg == 0 || MO.isUndef())
1429         continue;
1430       MachineInstr &MI = *MO.getParent();
1431       if (MI.isDebugValue())
1432         continue;
1433       SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot(true);
1434       addUndefFlag(*DstInt, UseIdx, MO, SubReg);
1435     }
1436   }
1437 
1438   SmallPtrSet<MachineInstr*, 8> Visited;
1439   for (MachineRegisterInfo::reg_instr_iterator
1440        I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
1441        I != E; ) {
1442     MachineInstr *UseMI = &*(I++);
1443 
1444     // Each instruction can only be rewritten once because sub-register
1445     // composition is not always idempotent. When SrcReg != DstReg, rewriting
1446     // the UseMI operands removes them from the SrcReg use-def chain, but when
1447     // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1448     // operands mentioning the virtual register.
1449     if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1450       continue;
1451 
1452     SmallVector<unsigned,8> Ops;
1453     bool Reads, Writes;
1454     std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1455 
1456     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1457     // because SrcReg is a sub-register.
1458     if (DstInt && !Reads && SubIdx)
1459       Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI));
1460 
1461     // Replace SrcReg with DstReg in all UseMI operands.
1462     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1463       MachineOperand &MO = UseMI->getOperand(Ops[i]);
1464 
1465       // Adjust <undef> flags in case of sub-register joins. We don't want to
1466       // turn a full def into a read-modify-write sub-register def and vice
1467       // versa.
1468       if (SubIdx && MO.isDef())
1469         MO.setIsUndef(!Reads);
1470 
1471       // A subreg use of a partially undef (super) register may be a complete
1472       // undef use now and then has to be marked that way.
1473       if (SubIdx != 0 && MO.isUse() && MRI->shouldTrackSubRegLiveness(DstReg)) {
1474         if (!DstInt->hasSubRanges()) {
1475           BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
1476           LaneBitmask Mask = MRI->getMaxLaneMaskForVReg(DstInt->reg);
1477           DstInt->createSubRangeFrom(Allocator, Mask, *DstInt);
1478         }
1479         SlotIndex MIIdx = UseMI->isDebugValue()
1480                               ? LIS->getSlotIndexes()->getIndexBefore(*UseMI)
1481                               : LIS->getInstructionIndex(*UseMI);
1482         SlotIndex UseIdx = MIIdx.getRegSlot(true);
1483         addUndefFlag(*DstInt, UseIdx, MO, SubIdx);
1484       }
1485 
1486       if (DstIsPhys)
1487         MO.substPhysReg(DstReg, *TRI);
1488       else
1489         MO.substVirtReg(DstReg, SubIdx, *TRI);
1490     }
1491 
1492     DEBUG({
1493         dbgs() << "\t\tupdated: ";
1494         if (!UseMI->isDebugValue())
1495           dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";
1496         dbgs() << *UseMI;
1497       });
1498   }
1499 }
1500 
1501 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1502   // Always join simple intervals that are defined by a single copy from a
1503   // reserved register. This doesn't increase register pressure, so it is
1504   // always beneficial.
1505   if (!MRI->isReserved(CP.getDstReg())) {
1506     DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
1507     return false;
1508   }
1509 
1510   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1511   if (JoinVInt.containsOneValue())
1512     return true;
1513 
1514   DEBUG(dbgs() << "\tCannot join complex intervals into reserved register.\n");
1515   return false;
1516 }
1517 
1518 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1519 
1520   Again = false;
1521   DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
1522 
1523   CoalescerPair CP(*TRI);
1524   if (!CP.setRegisters(CopyMI)) {
1525     DEBUG(dbgs() << "\tNot coalescable.\n");
1526     return false;
1527   }
1528 
1529   if (CP.getNewRC()) {
1530     auto SrcRC = MRI->getRegClass(CP.getSrcReg());
1531     auto DstRC = MRI->getRegClass(CP.getDstReg());
1532     unsigned SrcIdx = CP.getSrcIdx();
1533     unsigned DstIdx = CP.getDstIdx();
1534     if (CP.isFlipped()) {
1535       std::swap(SrcIdx, DstIdx);
1536       std::swap(SrcRC, DstRC);
1537     }
1538     if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1539                             CP.getNewRC())) {
1540       DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
1541       return false;
1542     }
1543   }
1544 
1545   // Dead code elimination. This really should be handled by MachineDCE, but
1546   // sometimes dead copies slip through, and we can't generate invalid live
1547   // ranges.
1548   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1549     DEBUG(dbgs() << "\tCopy is dead.\n");
1550     DeadDefs.push_back(CopyMI);
1551     eliminateDeadDefs();
1552     return true;
1553   }
1554 
1555   // Eliminate undefs.
1556   if (!CP.isPhys() && eliminateUndefCopy(CopyMI)) {
1557     LIS->RemoveMachineInstrFromMaps(*CopyMI);
1558     CopyMI->eraseFromParent();
1559     return false;  // Not coalescable.
1560   }
1561 
1562   // Coalesced copies are normally removed immediately, but transformations
1563   // like removeCopyByCommutingDef() can inadvertently create identity copies.
1564   // When that happens, just join the values and remove the copy.
1565   if (CP.getSrcReg() == CP.getDstReg()) {
1566     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1567     DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1568     const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1569     LiveQueryResult LRQ = LI.Query(CopyIdx);
1570     if (VNInfo *DefVNI = LRQ.valueDefined()) {
1571       VNInfo *ReadVNI = LRQ.valueIn();
1572       assert(ReadVNI && "No value before copy and no <undef> flag.");
1573       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1574       LI.MergeValueNumberInto(DefVNI, ReadVNI);
1575 
1576       // Process subregister liveranges.
1577       for (LiveInterval::SubRange &S : LI.subranges()) {
1578         LiveQueryResult SLRQ = S.Query(CopyIdx);
1579         if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
1580           VNInfo *SReadVNI = SLRQ.valueIn();
1581           S.MergeValueNumberInto(SDefVNI, SReadVNI);
1582         }
1583       }
1584       DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
1585     }
1586     LIS->RemoveMachineInstrFromMaps(*CopyMI);
1587     CopyMI->eraseFromParent();
1588     return true;
1589   }
1590 
1591   // Enforce policies.
1592   if (CP.isPhys()) {
1593     DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1594                  << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1595                  << '\n');
1596     if (!canJoinPhys(CP)) {
1597       // Before giving up coalescing, if definition of source is defined by
1598       // trivial computation, try rematerializing it.
1599       bool IsDefCopy;
1600       if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1601         return true;
1602       if (IsDefCopy)
1603         Again = true;  // May be possible to coalesce later.
1604       return false;
1605     }
1606   } else {
1607     // When possible, let DstReg be the larger interval.
1608     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1609                            LIS->getInterval(CP.getDstReg()).size())
1610       CP.flip();
1611 
1612     DEBUG({
1613       dbgs() << "\tConsidering merging to "
1614              << TRI->getRegClassName(CP.getNewRC()) << " with ";
1615       if (CP.getDstIdx() && CP.getSrcIdx())
1616         dbgs() << PrintReg(CP.getDstReg()) << " in "
1617                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1618                << PrintReg(CP.getSrcReg()) << " in "
1619                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1620       else
1621         dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1622                << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1623     });
1624   }
1625 
1626   ShrinkMask = LaneBitmask::getNone();
1627   ShrinkMainRange = false;
1628 
1629   // Okay, attempt to join these two intervals.  On failure, this returns false.
1630   // Otherwise, if one of the intervals being joined is a physreg, this method
1631   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1632   // been modified, so we can use this information below to update aliases.
1633   if (!joinIntervals(CP)) {
1634     // Coalescing failed.
1635 
1636     // If definition of source is defined by trivial computation, try
1637     // rematerializing it.
1638     bool IsDefCopy;
1639     if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1640       return true;
1641 
1642     // If we can eliminate the copy without merging the live segments, do so
1643     // now.
1644     if (!CP.isPartial() && !CP.isPhys()) {
1645       if (adjustCopiesBackFrom(CP, CopyMI) ||
1646           removeCopyByCommutingDef(CP, CopyMI)) {
1647         LIS->RemoveMachineInstrFromMaps(*CopyMI);
1648         CopyMI->eraseFromParent();
1649         DEBUG(dbgs() << "\tTrivial!\n");
1650         return true;
1651       }
1652     }
1653 
1654     // Try and see if we can partially eliminate the copy by moving the copy to
1655     // its predecessor.
1656     if (!CP.isPartial() && !CP.isPhys())
1657       if (removePartialRedundancy(CP, *CopyMI))
1658         return true;
1659 
1660     // Otherwise, we are unable to join the intervals.
1661     DEBUG(dbgs() << "\tInterference!\n");
1662     Again = true;  // May be possible to coalesce later.
1663     return false;
1664   }
1665 
1666   // Coalescing to a virtual register that is of a sub-register class of the
1667   // other. Make sure the resulting register is set to the right register class.
1668   if (CP.isCrossClass()) {
1669     ++numCrossRCs;
1670     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1671   }
1672 
1673   // Removing sub-register copies can ease the register class constraints.
1674   // Make sure we attempt to inflate the register class of DstReg.
1675   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1676     InflateRegs.push_back(CP.getDstReg());
1677 
1678   // CopyMI has been erased by joinIntervals at this point. Remove it from
1679   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1680   // to the work list. This keeps ErasedInstrs from growing needlessly.
1681   ErasedInstrs.erase(CopyMI);
1682 
1683   // Rewrite all SrcReg operands to DstReg.
1684   // Also update DstReg operands to include DstIdx if it is set.
1685   if (CP.getDstIdx())
1686     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1687   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1688 
1689   // Shrink subregister ranges if necessary.
1690   if (ShrinkMask.any()) {
1691     LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1692     for (LiveInterval::SubRange &S : LI.subranges()) {
1693       if ((S.LaneMask & ShrinkMask).none())
1694         continue;
1695       DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)
1696                    << ")\n");
1697       LIS->shrinkToUses(S, LI.reg);
1698     }
1699     LI.removeEmptySubRanges();
1700   }
1701   if (ShrinkMainRange) {
1702     LiveInterval &LI = LIS->getInterval(CP.getDstReg());
1703     shrinkToUses(&LI);
1704   }
1705 
1706   // SrcReg is guaranteed to be the register whose live interval that is
1707   // being merged.
1708   LIS->removeInterval(CP.getSrcReg());
1709 
1710   // Update regalloc hint.
1711   TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1712 
1713   DEBUG({
1714     dbgs() << "\tSuccess: " << PrintReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
1715            << " -> " << PrintReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
1716     dbgs() << "\tResult = ";
1717     if (CP.isPhys())
1718       dbgs() << PrintReg(CP.getDstReg(), TRI);
1719     else
1720       dbgs() << LIS->getInterval(CP.getDstReg());
1721     dbgs() << '\n';
1722   });
1723 
1724   ++numJoins;
1725   return true;
1726 }
1727 
1728 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1729   unsigned DstReg = CP.getDstReg();
1730   assert(CP.isPhys() && "Must be a physreg copy");
1731   assert(MRI->isReserved(DstReg) && "Not a reserved register");
1732   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1733   DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1734 
1735   assert(RHS.containsOneValue() && "Invalid join with reserved register");
1736 
1737   // Optimization for reserved registers like ESP. We can only merge with a
1738   // reserved physreg if RHS has a single value that is a copy of DstReg.
1739   // The live range of the reserved register will look like a set of dead defs
1740   // - we don't properly track the live range of reserved registers.
1741 
1742   // Deny any overlapping intervals.  This depends on all the reserved
1743   // register live ranges to look like dead defs.
1744   if (!MRI->isConstantPhysReg(DstReg)) {
1745     for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
1746       // Abort if not all the regunits are reserved.
1747       for (MCRegUnitRootIterator RI(*UI, TRI); RI.isValid(); ++RI) {
1748         if (!MRI->isReserved(*RI))
1749           return false;
1750       }
1751       if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1752         DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1753         return false;
1754       }
1755     }
1756 
1757     // We must also check for overlaps with regmask clobbers.
1758     BitVector RegMaskUsable;
1759     if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
1760         !RegMaskUsable.test(DstReg)) {
1761       DEBUG(dbgs() << "\t\tRegMask interference\n");
1762       return false;
1763     }
1764   }
1765 
1766   // Skip any value computations, we are not adding new values to the
1767   // reserved register.  Also skip merging the live ranges, the reserved
1768   // register live range doesn't need to be accurate as long as all the
1769   // defs are there.
1770 
1771   // Delete the identity copy.
1772   MachineInstr *CopyMI;
1773   if (CP.isFlipped()) {
1774     CopyMI = MRI->getVRegDef(RHS.reg);
1775   } else {
1776     if (!MRI->hasOneNonDBGUse(RHS.reg)) {
1777       DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
1778       return false;
1779     }
1780 
1781     MachineInstr *DestMI = MRI->getVRegDef(RHS.reg);
1782     CopyMI = &*MRI->use_instr_nodbg_begin(RHS.reg);
1783     const SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
1784     const SlotIndex DestRegIdx = LIS->getInstructionIndex(*DestMI).getRegSlot();
1785 
1786     if (!MRI->isConstantPhysReg(DstReg)) {
1787       // We checked above that there are no interfering defs of the physical
1788       // register. However, for this case, where we intent to move up the def of
1789       // the physical register, we also need to check for interfering uses.
1790       SlotIndexes *Indexes = LIS->getSlotIndexes();
1791       for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
1792            SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
1793         MachineInstr *MI = LIS->getInstructionFromIndex(SI);
1794         if (MI->readsRegister(DstReg, TRI)) {
1795           DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
1796           return false;
1797         }
1798       }
1799     }
1800 
1801     // We're going to remove the copy which defines a physical reserved
1802     // register, so remove its valno, etc.
1803     DEBUG(dbgs() << "\t\tRemoving phys reg def of " << DstReg << " at "
1804           << CopyRegIdx << "\n");
1805 
1806     LIS->removePhysRegDefAt(DstReg, CopyRegIdx);
1807     // Create a new dead def at the new def location.
1808     for (MCRegUnitIterator UI(DstReg, TRI); UI.isValid(); ++UI) {
1809       LiveRange &LR = LIS->getRegUnit(*UI);
1810       LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
1811     }
1812   }
1813 
1814   LIS->RemoveMachineInstrFromMaps(*CopyMI);
1815   CopyMI->eraseFromParent();
1816 
1817   // We don't track kills for reserved registers.
1818   MRI->clearKillFlags(CP.getSrcReg());
1819 
1820   return true;
1821 }
1822 
1823 //===----------------------------------------------------------------------===//
1824 //                 Interference checking and interval joining
1825 //===----------------------------------------------------------------------===//
1826 //
1827 // In the easiest case, the two live ranges being joined are disjoint, and
1828 // there is no interference to consider. It is quite common, though, to have
1829 // overlapping live ranges, and we need to check if the interference can be
1830 // resolved.
1831 //
1832 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1833 // This means that two SSA values overlap if and only if the def of one value
1834 // is contained in the live range of the other value. As a special case, the
1835 // overlapping values can be defined at the same index.
1836 //
1837 // The interference from an overlapping def can be resolved in these cases:
1838 //
1839 // 1. Coalescable copies. The value is defined by a copy that would become an
1840 //    identity copy after joining SrcReg and DstReg. The copy instruction will
1841 //    be removed, and the value will be merged with the source value.
1842 //
1843 //    There can be several copies back and forth, causing many values to be
1844 //    merged into one. We compute a list of ultimate values in the joined live
1845 //    range as well as a mappings from the old value numbers.
1846 //
1847 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1848 //    predecessors have a live out value. It doesn't cause real interference,
1849 //    and can be merged into the value it overlaps. Like a coalescable copy, it
1850 //    can be erased after joining.
1851 //
1852 // 3. Copy of external value. The overlapping def may be a copy of a value that
1853 //    is already in the other register. This is like a coalescable copy, but
1854 //    the live range of the source register must be trimmed after erasing the
1855 //    copy instruction:
1856 //
1857 //      %src = COPY %ext
1858 //      %dst = COPY %ext  <-- Remove this COPY, trim the live range of %ext.
1859 //
1860 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1861 //    defining one lane at a time:
1862 //
1863 //      %dst:ssub0<def,read-undef> = FOO
1864 //      %src = BAR
1865 //      %dst:ssub1<def> = COPY %src
1866 //
1867 //    The live range of %src overlaps the %dst value defined by FOO, but
1868 //    merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1869 //    which was undef anyway.
1870 //
1871 //    The value mapping is more complicated in this case. The final live range
1872 //    will have different value numbers for both FOO and BAR, but there is no
1873 //    simple mapping from old to new values. It may even be necessary to add
1874 //    new PHI values.
1875 //
1876 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1877 //    is live, but never read. This can happen because we don't compute
1878 //    individual live ranges per lane.
1879 //
1880 //      %dst<def> = FOO
1881 //      %src = BAR
1882 //      %dst:ssub1<def> = COPY %src
1883 //
1884 //    This kind of interference is only resolved locally. If the clobbered
1885 //    lane value escapes the block, the join is aborted.
1886 
1887 namespace {
1888 /// Track information about values in a single virtual register about to be
1889 /// joined. Objects of this class are always created in pairs - one for each
1890 /// side of the CoalescerPair (or one for each lane of a side of the coalescer
1891 /// pair)
1892 class JoinVals {
1893   /// Live range we work on.
1894   LiveRange &LR;
1895   /// (Main) register we work on.
1896   const unsigned Reg;
1897 
1898   /// Reg (and therefore the values in this liverange) will end up as
1899   /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
1900   /// CP.SrcIdx.
1901   const unsigned SubIdx;
1902   /// The LaneMask that this liverange will occupy the coalesced register. May
1903   /// be smaller than the lanemask produced by SubIdx when merging subranges.
1904   const LaneBitmask LaneMask;
1905 
1906   /// This is true when joining sub register ranges, false when joining main
1907   /// ranges.
1908   const bool SubRangeJoin;
1909   /// Whether the current LiveInterval tracks subregister liveness.
1910   const bool TrackSubRegLiveness;
1911 
1912   /// Values that will be present in the final live range.
1913   SmallVectorImpl<VNInfo*> &NewVNInfo;
1914 
1915   const CoalescerPair &CP;
1916   LiveIntervals *LIS;
1917   SlotIndexes *Indexes;
1918   const TargetRegisterInfo *TRI;
1919 
1920   /// Value number assignments. Maps value numbers in LI to entries in
1921   /// NewVNInfo. This is suitable for passing to LiveInterval::join().
1922   SmallVector<int, 8> Assignments;
1923 
1924   /// Conflict resolution for overlapping values.
1925   enum ConflictResolution {
1926     /// No overlap, simply keep this value.
1927     CR_Keep,
1928 
1929     /// Merge this value into OtherVNI and erase the defining instruction.
1930     /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
1931     /// values.
1932     CR_Erase,
1933 
1934     /// Merge this value into OtherVNI but keep the defining instruction.
1935     /// This is for the special case where OtherVNI is defined by the same
1936     /// instruction.
1937     CR_Merge,
1938 
1939     /// Keep this value, and have it replace OtherVNI where possible. This
1940     /// complicates value mapping since OtherVNI maps to two different values
1941     /// before and after this def.
1942     /// Used when clobbering undefined or dead lanes.
1943     CR_Replace,
1944 
1945     /// Unresolved conflict. Visit later when all values have been mapped.
1946     CR_Unresolved,
1947 
1948     /// Unresolvable conflict. Abort the join.
1949     CR_Impossible
1950   };
1951 
1952   /// Per-value info for LI. The lane bit masks are all relative to the final
1953   /// joined register, so they can be compared directly between SrcReg and
1954   /// DstReg.
1955   struct Val {
1956     ConflictResolution Resolution;
1957 
1958     /// Lanes written by this def, 0 for unanalyzed values.
1959     LaneBitmask WriteLanes;
1960 
1961     /// Lanes with defined values in this register. Other lanes are undef and
1962     /// safe to clobber.
1963     LaneBitmask ValidLanes;
1964 
1965     /// Value in LI being redefined by this def.
1966     VNInfo *RedefVNI;
1967 
1968     /// Value in the other live range that overlaps this def, if any.
1969     VNInfo *OtherVNI;
1970 
1971     /// Is this value an IMPLICIT_DEF that can be erased?
1972     ///
1973     /// IMPLICIT_DEF values should only exist at the end of a basic block that
1974     /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1975     /// safely erased if they are overlapping a live value in the other live
1976     /// interval.
1977     ///
1978     /// Weird control flow graphs and incomplete PHI handling in
1979     /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1980     /// longer live ranges. Such IMPLICIT_DEF values should be treated like
1981     /// normal values.
1982     bool ErasableImplicitDef;
1983 
1984     /// True when the live range of this value will be pruned because of an
1985     /// overlapping CR_Replace value in the other live range.
1986     bool Pruned;
1987 
1988     /// True once Pruned above has been computed.
1989     bool PrunedComputed;
1990 
1991     Val() : Resolution(CR_Keep), WriteLanes(), ValidLanes(),
1992             RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false),
1993             Pruned(false), PrunedComputed(false) {}
1994 
1995     bool isAnalyzed() const { return WriteLanes.any(); }
1996   };
1997 
1998   /// One entry per value number in LI.
1999   SmallVector<Val, 8> Vals;
2000 
2001   /// Compute the bitmask of lanes actually written by DefMI.
2002   /// Set Redef if there are any partial register definitions that depend on the
2003   /// previous value of the register.
2004   LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
2005 
2006   /// Find the ultimate value that VNI was copied from.
2007   std::pair<const VNInfo*,unsigned> followCopyChain(const VNInfo *VNI) const;
2008 
2009   bool valuesIdentical(VNInfo *Val0, VNInfo *Val1, const JoinVals &Other) const;
2010 
2011   /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
2012   /// Return a conflict resolution when possible, but leave the hard cases as
2013   /// CR_Unresolved.
2014   /// Recursively calls computeAssignment() on this and Other, guaranteeing that
2015   /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
2016   /// The recursion always goes upwards in the dominator tree, making loops
2017   /// impossible.
2018   ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
2019 
2020   /// Compute the value assignment for ValNo in RI.
2021   /// This may be called recursively by analyzeValue(), but never for a ValNo on
2022   /// the stack.
2023   void computeAssignment(unsigned ValNo, JoinVals &Other);
2024 
2025   /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
2026   /// the extent of the tainted lanes in the block.
2027   ///
2028   /// Multiple values in Other.LR can be affected since partial redefinitions
2029   /// can preserve previously tainted lanes.
2030   ///
2031   ///   1 %dst = VLOAD           <-- Define all lanes in %dst
2032   ///   2 %src = FOO             <-- ValNo to be joined with %dst:ssub0
2033   ///   3 %dst:ssub1 = BAR       <-- Partial redef doesn't clear taint in ssub0
2034   ///   4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
2035   ///
2036   /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
2037   /// entry to TaintedVals.
2038   ///
2039   /// Returns false if the tainted lanes extend beyond the basic block.
2040   bool taintExtent(unsigned, LaneBitmask, JoinVals&,
2041                    SmallVectorImpl<std::pair<SlotIndex, LaneBitmask> >&);
2042 
2043   /// Return true if MI uses any of the given Lanes from Reg.
2044   /// This does not include partial redefinitions of Reg.
2045   bool usesLanes(const MachineInstr &MI, unsigned, unsigned, LaneBitmask) const;
2046 
2047   /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
2048   /// be pruned:
2049   ///
2050   ///   %dst = COPY %src
2051   ///   %src = COPY %dst  <-- This value to be pruned.
2052   ///   %dst = COPY %src  <-- This value is a copy of a pruned value.
2053   bool isPrunedValue(unsigned ValNo, JoinVals &Other);
2054 
2055 public:
2056   JoinVals(LiveRange &LR, unsigned Reg, unsigned SubIdx, LaneBitmask LaneMask,
2057            SmallVectorImpl<VNInfo*> &newVNInfo, const CoalescerPair &cp,
2058            LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
2059            bool TrackSubRegLiveness)
2060     : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
2061       SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
2062       NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
2063       TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums())
2064   {}
2065 
2066   /// Analyze defs in LR and compute a value mapping in NewVNInfo.
2067   /// Returns false if any conflicts were impossible to resolve.
2068   bool mapValues(JoinVals &Other);
2069 
2070   /// Try to resolve conflicts that require all values to be mapped.
2071   /// Returns false if any conflicts were impossible to resolve.
2072   bool resolveConflicts(JoinVals &Other);
2073 
2074   /// Prune the live range of values in Other.LR where they would conflict with
2075   /// CR_Replace values in LR. Collect end points for restoring the live range
2076   /// after joining.
2077   void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
2078                    bool changeInstrs);
2079 
2080   /// Removes subranges starting at copies that get removed. This sometimes
2081   /// happens when undefined subranges are copied around. These ranges contain
2082   /// no useful information and can be removed.
2083   void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask);
2084 
2085   /// Pruning values in subranges can lead to removing segments in these
2086   /// subranges started by IMPLICIT_DEFs. The corresponding segments in
2087   /// the main range also need to be removed. This function will mark
2088   /// the corresponding values in the main range as pruned, so that
2089   /// eraseInstrs can do the final cleanup.
2090   /// The parameter @p LI must be the interval whose main range is the
2091   /// live range LR.
2092   void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange);
2093 
2094   /// Erase any machine instructions that have been coalesced away.
2095   /// Add erased instructions to ErasedInstrs.
2096   /// Add foreign virtual registers to ShrinkRegs if their live range ended at
2097   /// the erased instrs.
2098   void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2099                    SmallVectorImpl<unsigned> &ShrinkRegs,
2100                    LiveInterval *LI = nullptr);
2101 
2102   /// Remove liverange defs at places where implicit defs will be removed.
2103   void removeImplicitDefs();
2104 
2105   /// Get the value assignments suitable for passing to LiveInterval::join.
2106   const int *getAssignments() const { return Assignments.data(); }
2107 };
2108 } // end anonymous namespace
2109 
2110 LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef)
2111   const {
2112   LaneBitmask L;
2113   for (const MachineOperand &MO : DefMI->operands()) {
2114     if (!MO.isReg() || MO.getReg() != Reg || !MO.isDef())
2115       continue;
2116     L |= TRI->getSubRegIndexLaneMask(
2117            TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
2118     if (MO.readsReg())
2119       Redef = true;
2120   }
2121   return L;
2122 }
2123 
2124 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
2125     const VNInfo *VNI) const {
2126   unsigned Reg = this->Reg;
2127 
2128   while (!VNI->isPHIDef()) {
2129     SlotIndex Def = VNI->def;
2130     MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2131     assert(MI && "No defining instruction");
2132     if (!MI->isFullCopy())
2133       return std::make_pair(VNI, Reg);
2134     unsigned SrcReg = MI->getOperand(1).getReg();
2135     if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
2136       return std::make_pair(VNI, Reg);
2137 
2138     const LiveInterval &LI = LIS->getInterval(SrcReg);
2139     const VNInfo *ValueIn;
2140     // No subrange involved.
2141     if (!SubRangeJoin || !LI.hasSubRanges()) {
2142       LiveQueryResult LRQ = LI.Query(Def);
2143       ValueIn = LRQ.valueIn();
2144     } else {
2145       // Query subranges. Pick the first matching one.
2146       ValueIn = nullptr;
2147       for (const LiveInterval::SubRange &S : LI.subranges()) {
2148         // Transform lanemask to a mask in the joined live interval.
2149         LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
2150         if ((SMask & LaneMask).none())
2151           continue;
2152         LiveQueryResult LRQ = S.Query(Def);
2153         ValueIn = LRQ.valueIn();
2154         break;
2155       }
2156     }
2157     if (ValueIn == nullptr)
2158       break;
2159     VNI = ValueIn;
2160     Reg = SrcReg;
2161   }
2162   return std::make_pair(VNI, Reg);
2163 }
2164 
2165 bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
2166                                const JoinVals &Other) const {
2167   const VNInfo *Orig0;
2168   unsigned Reg0;
2169   std::tie(Orig0, Reg0) = followCopyChain(Value0);
2170   if (Orig0 == Value1)
2171     return true;
2172 
2173   const VNInfo *Orig1;
2174   unsigned Reg1;
2175   std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
2176 
2177   // The values are equal if they are defined at the same place and use the
2178   // same register. Note that we cannot compare VNInfos directly as some of
2179   // them might be from a copy created in mergeSubRangeInto()  while the other
2180   // is from the original LiveInterval.
2181   return Orig0->def == Orig1->def && Reg0 == Reg1;
2182 }
2183 
2184 JoinVals::ConflictResolution
2185 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
2186   Val &V = Vals[ValNo];
2187   assert(!V.isAnalyzed() && "Value has already been analyzed!");
2188   VNInfo *VNI = LR.getValNumInfo(ValNo);
2189   if (VNI->isUnused()) {
2190     V.WriteLanes = LaneBitmask::getAll();
2191     return CR_Keep;
2192   }
2193 
2194   // Get the instruction defining this value, compute the lanes written.
2195   const MachineInstr *DefMI = nullptr;
2196   if (VNI->isPHIDef()) {
2197     // Conservatively assume that all lanes in a PHI are valid.
2198     LaneBitmask Lanes = SubRangeJoin ? LaneBitmask(1)
2199                                      : TRI->getSubRegIndexLaneMask(SubIdx);
2200     V.ValidLanes = V.WriteLanes = Lanes;
2201   } else {
2202     DefMI = Indexes->getInstructionFromIndex(VNI->def);
2203     assert(DefMI != nullptr);
2204     if (SubRangeJoin) {
2205       // We don't care about the lanes when joining subregister ranges.
2206       V.WriteLanes = V.ValidLanes = LaneBitmask(1);
2207       if (DefMI->isImplicitDef()) {
2208         V.ValidLanes = LaneBitmask::getNone();
2209         V.ErasableImplicitDef = true;
2210       }
2211     } else {
2212       bool Redef = false;
2213       V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
2214 
2215       // If this is a read-modify-write instruction, there may be more valid
2216       // lanes than the ones written by this instruction.
2217       // This only covers partial redef operands. DefMI may have normal use
2218       // operands reading the register. They don't contribute valid lanes.
2219       //
2220       // This adds ssub1 to the set of valid lanes in %src:
2221       //
2222       //   %src:ssub1<def> = FOO
2223       //
2224       // This leaves only ssub1 valid, making any other lanes undef:
2225       //
2226       //   %src:ssub1<def,read-undef> = FOO %src:ssub2
2227       //
2228       // The <read-undef> flag on the def operand means that old lane values are
2229       // not important.
2230       if (Redef) {
2231         V.RedefVNI = LR.Query(VNI->def).valueIn();
2232         assert((TrackSubRegLiveness || V.RedefVNI) &&
2233                "Instruction is reading nonexistent value");
2234         if (V.RedefVNI != nullptr) {
2235           computeAssignment(V.RedefVNI->id, Other);
2236           V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
2237         }
2238       }
2239 
2240       // An IMPLICIT_DEF writes undef values.
2241       if (DefMI->isImplicitDef()) {
2242         // We normally expect IMPLICIT_DEF values to be live only until the end
2243         // of their block. If the value is really live longer and gets pruned in
2244         // another block, this flag is cleared again.
2245         V.ErasableImplicitDef = true;
2246         V.ValidLanes &= ~V.WriteLanes;
2247       }
2248     }
2249   }
2250 
2251   // Find the value in Other that overlaps VNI->def, if any.
2252   LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
2253 
2254   // It is possible that both values are defined by the same instruction, or
2255   // the values are PHIs defined in the same block. When that happens, the two
2256   // values should be merged into one, but not into any preceding value.
2257   // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
2258   if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
2259     assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
2260 
2261     // One value stays, the other is merged. Keep the earlier one, or the first
2262     // one we see.
2263     if (OtherVNI->def < VNI->def)
2264       Other.computeAssignment(OtherVNI->id, *this);
2265     else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
2266       // This is an early-clobber def overlapping a live-in value in the other
2267       // register. Not mergeable.
2268       V.OtherVNI = OtherLRQ.valueIn();
2269       return CR_Impossible;
2270     }
2271     V.OtherVNI = OtherVNI;
2272     Val &OtherV = Other.Vals[OtherVNI->id];
2273     // Keep this value, check for conflicts when analyzing OtherVNI.
2274     if (!OtherV.isAnalyzed())
2275       return CR_Keep;
2276     // Both sides have been analyzed now.
2277     // Allow overlapping PHI values. Any real interference would show up in a
2278     // predecessor, the PHI itself can't introduce any conflicts.
2279     if (VNI->isPHIDef())
2280       return CR_Merge;
2281     if ((V.ValidLanes & OtherV.ValidLanes).any())
2282       // Overlapping lanes can't be resolved.
2283       return CR_Impossible;
2284     else
2285       return CR_Merge;
2286   }
2287 
2288   // No simultaneous def. Is Other live at the def?
2289   V.OtherVNI = OtherLRQ.valueIn();
2290   if (!V.OtherVNI)
2291     // No overlap, no conflict.
2292     return CR_Keep;
2293 
2294   assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
2295 
2296   // We have overlapping values, or possibly a kill of Other.
2297   // Recursively compute assignments up the dominator tree.
2298   Other.computeAssignment(V.OtherVNI->id, *this);
2299   Val &OtherV = Other.Vals[V.OtherVNI->id];
2300 
2301   // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
2302   // This shouldn't normally happen, but ProcessImplicitDefs can leave such
2303   // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
2304   // technically.
2305   //
2306   // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try
2307   // to erase the IMPLICIT_DEF instruction.
2308   if (OtherV.ErasableImplicitDef && DefMI &&
2309       DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
2310     DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
2311                  << " extends into BB#" << DefMI->getParent()->getNumber()
2312                  << ", keeping it.\n");
2313     OtherV.ErasableImplicitDef = false;
2314   }
2315 
2316   // Allow overlapping PHI values. Any real interference would show up in a
2317   // predecessor, the PHI itself can't introduce any conflicts.
2318   if (VNI->isPHIDef())
2319     return CR_Replace;
2320 
2321   // Check for simple erasable conflicts.
2322   if (DefMI->isImplicitDef()) {
2323     // We need the def for the subregister if there is nothing else live at the
2324     // subrange at this point.
2325     if (TrackSubRegLiveness
2326         && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)).none())
2327       return CR_Replace;
2328     return CR_Erase;
2329   }
2330 
2331   // Include the non-conflict where DefMI is a coalescable copy that kills
2332   // OtherVNI. We still want the copy erased and value numbers merged.
2333   if (CP.isCoalescable(DefMI)) {
2334     // Some of the lanes copied from OtherVNI may be undef, making them undef
2335     // here too.
2336     V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
2337     return CR_Erase;
2338   }
2339 
2340   // This may not be a real conflict if DefMI simply kills Other and defines
2341   // VNI.
2342   if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
2343     return CR_Keep;
2344 
2345   // Handle the case where VNI and OtherVNI can be proven to be identical:
2346   //
2347   //   %other = COPY %ext
2348   //   %this  = COPY %ext <-- Erase this copy
2349   //
2350   if (DefMI->isFullCopy() && !CP.isPartial()
2351       && valuesIdentical(VNI, V.OtherVNI, Other))
2352     return CR_Erase;
2353 
2354   // If the lanes written by this instruction were all undef in OtherVNI, it is
2355   // still safe to join the live ranges. This can't be done with a simple value
2356   // mapping, though - OtherVNI will map to multiple values:
2357   //
2358   //   1 %dst:ssub0 = FOO                <-- OtherVNI
2359   //   2 %src = BAR                      <-- VNI
2360   //   3 %dst:ssub1 = COPY %src<kill>    <-- Eliminate this copy.
2361   //   4 BAZ %dst<kill>
2362   //   5 QUUX %src<kill>
2363   //
2364   // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
2365   // handles this complex value mapping.
2366   if ((V.WriteLanes & OtherV.ValidLanes).none())
2367     return CR_Replace;
2368 
2369   // If the other live range is killed by DefMI and the live ranges are still
2370   // overlapping, it must be because we're looking at an early clobber def:
2371   //
2372   //   %dst<def,early-clobber> = ASM %src<kill>
2373   //
2374   // In this case, it is illegal to merge the two live ranges since the early
2375   // clobber def would clobber %src before it was read.
2376   if (OtherLRQ.isKill()) {
2377     // This case where the def doesn't overlap the kill is handled above.
2378     assert(VNI->def.isEarlyClobber() &&
2379            "Only early clobber defs can overlap a kill");
2380     return CR_Impossible;
2381   }
2382 
2383   // VNI is clobbering live lanes in OtherVNI, but there is still the
2384   // possibility that no instructions actually read the clobbered lanes.
2385   // If we're clobbering all the lanes in OtherVNI, at least one must be read.
2386   // Otherwise Other.RI wouldn't be live here.
2387   if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
2388     return CR_Impossible;
2389 
2390   // We need to verify that no instructions are reading the clobbered lanes. To
2391   // save compile time, we'll only check that locally. Don't allow the tainted
2392   // value to escape the basic block.
2393   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2394   if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
2395     return CR_Impossible;
2396 
2397   // There are still some things that could go wrong besides clobbered lanes
2398   // being read, for example OtherVNI may be only partially redefined in MBB,
2399   // and some clobbered lanes could escape the block. Save this analysis for
2400   // resolveConflicts() when all values have been mapped. We need to know
2401   // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
2402   // that now - the recursive analyzeValue() calls must go upwards in the
2403   // dominator tree.
2404   return CR_Unresolved;
2405 }
2406 
2407 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
2408   Val &V = Vals[ValNo];
2409   if (V.isAnalyzed()) {
2410     // Recursion should always move up the dominator tree, so ValNo is not
2411     // supposed to reappear before it has been assigned.
2412     assert(Assignments[ValNo] != -1 && "Bad recursion?");
2413     return;
2414   }
2415   switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2416   case CR_Erase:
2417   case CR_Merge:
2418     // Merge this ValNo into OtherVNI.
2419     assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
2420     assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
2421     Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2422     DEBUG(dbgs() << "\t\tmerge " << PrintReg(Reg) << ':' << ValNo << '@'
2423                  << LR.getValNumInfo(ValNo)->def << " into "
2424                  << PrintReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
2425                  << V.OtherVNI->def << " --> @"
2426                  << NewVNInfo[Assignments[ValNo]]->def << '\n');
2427     break;
2428   case CR_Replace:
2429   case CR_Unresolved: {
2430     // The other value is going to be pruned if this join is successful.
2431     assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
2432     Val &OtherV = Other.Vals[V.OtherVNI->id];
2433     // We cannot erase an IMPLICIT_DEF if we don't have valid values for all
2434     // its lanes.
2435     if ((OtherV.WriteLanes & ~V.ValidLanes).any() && TrackSubRegLiveness)
2436       OtherV.ErasableImplicitDef = false;
2437     OtherV.Pruned = true;
2438     LLVM_FALLTHROUGH;
2439   }
2440   default:
2441     // This value number needs to go in the final joined live range.
2442     Assignments[ValNo] = NewVNInfo.size();
2443     NewVNInfo.push_back(LR.getValNumInfo(ValNo));
2444     break;
2445   }
2446 }
2447 
2448 bool JoinVals::mapValues(JoinVals &Other) {
2449   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2450     computeAssignment(i, Other);
2451     if (Vals[i].Resolution == CR_Impossible) {
2452       DEBUG(dbgs() << "\t\tinterference at " << PrintReg(Reg) << ':' << i
2453                    << '@' << LR.getValNumInfo(i)->def << '\n');
2454       return false;
2455     }
2456   }
2457   return true;
2458 }
2459 
2460 bool JoinVals::
2461 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
2462             SmallVectorImpl<std::pair<SlotIndex, LaneBitmask> > &TaintExtent) {
2463   VNInfo *VNI = LR.getValNumInfo(ValNo);
2464   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2465   SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
2466 
2467   // Scan Other.LR from VNI.def to MBBEnd.
2468   LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
2469   assert(OtherI != Other.LR.end() && "No conflict?");
2470   do {
2471     // OtherI is pointing to a tainted value. Abort the join if the tainted
2472     // lanes escape the block.
2473     SlotIndex End = OtherI->end;
2474     if (End >= MBBEnd) {
2475       DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.Reg) << ':'
2476                    << OtherI->valno->id << '@' << OtherI->start << '\n');
2477       return false;
2478     }
2479     DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.Reg) << ':'
2480                  << OtherI->valno->id << '@' << OtherI->start
2481                  << " to " << End << '\n');
2482     // A dead def is not a problem.
2483     if (End.isDead())
2484       break;
2485     TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2486 
2487     // Check for another def in the MBB.
2488     if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2489       break;
2490 
2491     // Lanes written by the new def are no longer tainted.
2492     const Val &OV = Other.Vals[OtherI->valno->id];
2493     TaintedLanes &= ~OV.WriteLanes;
2494     if (!OV.RedefVNI)
2495       break;
2496   } while (TaintedLanes.any());
2497   return true;
2498 }
2499 
2500 bool JoinVals::usesLanes(const MachineInstr &MI, unsigned Reg, unsigned SubIdx,
2501                          LaneBitmask Lanes) const {
2502   if (MI.isDebugValue())
2503     return false;
2504   for (const MachineOperand &MO : MI.operands()) {
2505     if (!MO.isReg() || MO.isDef() || MO.getReg() != Reg)
2506       continue;
2507     if (!MO.readsReg())
2508       continue;
2509     unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
2510     if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
2511       return true;
2512   }
2513   return false;
2514 }
2515 
2516 bool JoinVals::resolveConflicts(JoinVals &Other) {
2517   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2518     Val &V = Vals[i];
2519     assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
2520     if (V.Resolution != CR_Unresolved)
2521       continue;
2522     DEBUG(dbgs() << "\t\tconflict at " << PrintReg(Reg) << ':' << i
2523                  << '@' << LR.getValNumInfo(i)->def << '\n');
2524     if (SubRangeJoin)
2525       return false;
2526 
2527     ++NumLaneConflicts;
2528     assert(V.OtherVNI && "Inconsistent conflict resolution.");
2529     VNInfo *VNI = LR.getValNumInfo(i);
2530     const Val &OtherV = Other.Vals[V.OtherVNI->id];
2531 
2532     // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
2533     // join, those lanes will be tainted with a wrong value. Get the extent of
2534     // the tainted lanes.
2535     LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2536     SmallVector<std::pair<SlotIndex, LaneBitmask>, 8> TaintExtent;
2537     if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2538       // Tainted lanes would extend beyond the basic block.
2539       return false;
2540 
2541     assert(!TaintExtent.empty() && "There should be at least one conflict.");
2542 
2543     // Now look at the instructions from VNI->def to TaintExtent (inclusive).
2544     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
2545     MachineBasicBlock::iterator MI = MBB->begin();
2546     if (!VNI->isPHIDef()) {
2547       MI = Indexes->getInstructionFromIndex(VNI->def);
2548       // No need to check the instruction defining VNI for reads.
2549       ++MI;
2550     }
2551     assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
2552            "Interference ends on VNI->def. Should have been handled earlier");
2553     MachineInstr *LastMI =
2554       Indexes->getInstructionFromIndex(TaintExtent.front().first);
2555     assert(LastMI && "Range must end at a proper instruction");
2556     unsigned TaintNum = 0;
2557     for (;;) {
2558       assert(MI != MBB->end() && "Bad LastMI");
2559       if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2560         DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
2561         return false;
2562       }
2563       // LastMI is the last instruction to use the current value.
2564       if (&*MI == LastMI) {
2565         if (++TaintNum == TaintExtent.size())
2566           break;
2567         LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
2568         assert(LastMI && "Range must end at a proper instruction");
2569         TaintedLanes = TaintExtent[TaintNum].second;
2570       }
2571       ++MI;
2572     }
2573 
2574     // The tainted lanes are unused.
2575     V.Resolution = CR_Replace;
2576     ++NumLaneResolves;
2577   }
2578   return true;
2579 }
2580 
2581 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
2582   Val &V = Vals[ValNo];
2583   if (V.Pruned || V.PrunedComputed)
2584     return V.Pruned;
2585 
2586   if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2587     return V.Pruned;
2588 
2589   // Follow copies up the dominator tree and check if any intermediate value
2590   // has been pruned.
2591   V.PrunedComputed = true;
2592   V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
2593   return V.Pruned;
2594 }
2595 
2596 void JoinVals::pruneValues(JoinVals &Other,
2597                            SmallVectorImpl<SlotIndex> &EndPoints,
2598                            bool changeInstrs) {
2599   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2600     SlotIndex Def = LR.getValNumInfo(i)->def;
2601     switch (Vals[i].Resolution) {
2602     case CR_Keep:
2603       break;
2604     case CR_Replace: {
2605       // This value takes precedence over the value in Other.LR.
2606       LIS->pruneValue(Other.LR, Def, &EndPoints);
2607       // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
2608       // instructions are only inserted to provide a live-out value for PHI
2609       // predecessors, so the instruction should simply go away once its value
2610       // has been replaced.
2611       Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2612       bool EraseImpDef = OtherV.ErasableImplicitDef &&
2613                          OtherV.Resolution == CR_Keep;
2614       if (!Def.isBlock()) {
2615         if (changeInstrs) {
2616           // Remove <def,read-undef> flags. This def is now a partial redef.
2617           // Also remove <def,dead> flags since the joined live range will
2618           // continue past this instruction.
2619           for (MachineOperand &MO :
2620                Indexes->getInstructionFromIndex(Def)->operands()) {
2621             if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
2622               if (MO.getSubReg() != 0)
2623                 MO.setIsUndef(EraseImpDef);
2624               MO.setIsDead(false);
2625             }
2626           }
2627         }
2628         // This value will reach instructions below, but we need to make sure
2629         // the live range also reaches the instruction at Def.
2630         if (!EraseImpDef)
2631           EndPoints.push_back(Def);
2632       }
2633       DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.Reg) << " at " << Def
2634                    << ": " << Other.LR << '\n');
2635       break;
2636     }
2637     case CR_Erase:
2638     case CR_Merge:
2639       if (isPrunedValue(i, Other)) {
2640         // This value is ultimately a copy of a pruned value in LR or Other.LR.
2641         // We can no longer trust the value mapping computed by
2642         // computeAssignment(), the value that was originally copied could have
2643         // been replaced.
2644         LIS->pruneValue(LR, Def, &EndPoints);
2645         DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(Reg) << " at "
2646                      << Def << ": " << LR << '\n');
2647       }
2648       break;
2649     case CR_Unresolved:
2650     case CR_Impossible:
2651       llvm_unreachable("Unresolved conflicts");
2652     }
2653   }
2654 }
2655 
2656 void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) {
2657   // Look for values being erased.
2658   bool DidPrune = false;
2659   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2660     if (Vals[i].Resolution != CR_Erase)
2661       continue;
2662 
2663     // Check subranges at the point where the copy will be removed.
2664     SlotIndex Def = LR.getValNumInfo(i)->def;
2665     for (LiveInterval::SubRange &S : LI.subranges()) {
2666       LiveQueryResult Q = S.Query(Def);
2667 
2668       // If a subrange starts at the copy then an undefined value has been
2669       // copied and we must remove that subrange value as well.
2670       VNInfo *ValueOut = Q.valueOutOrDead();
2671       if (ValueOut != nullptr && Q.valueIn() == nullptr) {
2672         DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)
2673                      << " at " << Def << "\n");
2674         LIS->pruneValue(S, Def, nullptr);
2675         DidPrune = true;
2676         // Mark value number as unused.
2677         ValueOut->markUnused();
2678         continue;
2679       }
2680       // If a subrange ends at the copy, then a value was copied but only
2681       // partially used later. Shrink the subregister range appropriately.
2682       if (Q.valueIn() != nullptr && Q.valueOut() == nullptr) {
2683         DEBUG(dbgs() << "\t\tDead uses at sublane " << PrintLaneMask(S.LaneMask)
2684                      << " at " << Def << "\n");
2685         ShrinkMask |= S.LaneMask;
2686       }
2687     }
2688   }
2689   if (DidPrune)
2690     LI.removeEmptySubRanges();
2691 }
2692 
2693 /// Check if any of the subranges of @p LI contain a definition at @p Def.
2694 static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def) {
2695   for (LiveInterval::SubRange &SR : LI.subranges()) {
2696     if (VNInfo *VNI = SR.Query(Def).valueOutOrDead())
2697       if (VNI->def == Def)
2698         return true;
2699   }
2700   return false;
2701 }
2702 
2703 void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) {
2704   assert(&static_cast<LiveRange&>(LI) == &LR);
2705 
2706   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2707     if (Vals[i].Resolution != CR_Keep)
2708       continue;
2709     VNInfo *VNI = LR.getValNumInfo(i);
2710     if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def))
2711       continue;
2712     Vals[i].Pruned = true;
2713     ShrinkMainRange = true;
2714   }
2715 }
2716 
2717 void JoinVals::removeImplicitDefs() {
2718   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2719     Val &V = Vals[i];
2720     if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
2721       continue;
2722 
2723     VNInfo *VNI = LR.getValNumInfo(i);
2724     VNI->markUnused();
2725     LR.removeValNo(VNI);
2726   }
2727 }
2728 
2729 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
2730                            SmallVectorImpl<unsigned> &ShrinkRegs,
2731                            LiveInterval *LI) {
2732   for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
2733     // Get the def location before markUnused() below invalidates it.
2734     SlotIndex Def = LR.getValNumInfo(i)->def;
2735     switch (Vals[i].Resolution) {
2736     case CR_Keep: {
2737       // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
2738       // longer. The IMPLICIT_DEF instructions are only inserted by
2739       // PHIElimination to guarantee that all PHI predecessors have a value.
2740       if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
2741         break;
2742       // Remove value number i from LR.
2743       // For intervals with subranges, removing a segment from the main range
2744       // may require extending the previous segment: for each definition of
2745       // a subregister, there will be a corresponding def in the main range.
2746       // That def may fall in the middle of a segment from another subrange.
2747       // In such cases, removing this def from the main range must be
2748       // complemented by extending the main range to account for the liveness
2749       // of the other subrange.
2750       VNInfo *VNI = LR.getValNumInfo(i);
2751       SlotIndex Def = VNI->def;
2752       // The new end point of the main range segment to be extended.
2753       SlotIndex NewEnd;
2754       if (LI != nullptr) {
2755         LiveRange::iterator I = LR.FindSegmentContaining(Def);
2756         assert(I != LR.end());
2757         // Do not extend beyond the end of the segment being removed.
2758         // The segment may have been pruned in preparation for joining
2759         // live ranges.
2760         NewEnd = I->end;
2761       }
2762 
2763       LR.removeValNo(VNI);
2764       // Note that this VNInfo is reused and still referenced in NewVNInfo,
2765       // make it appear like an unused value number.
2766       VNI->markUnused();
2767 
2768       if (LI != nullptr && LI->hasSubRanges()) {
2769         assert(static_cast<LiveRange*>(LI) == &LR);
2770         // Determine the end point based on the subrange information:
2771         // minimum of (earliest def of next segment,
2772         //             latest end point of containing segment)
2773         SlotIndex ED, LE;
2774         for (LiveInterval::SubRange &SR : LI->subranges()) {
2775           LiveRange::iterator I = SR.find(Def);
2776           if (I == SR.end())
2777             continue;
2778           if (I->start > Def)
2779             ED = ED.isValid() ? std::min(ED, I->start) : I->start;
2780           else
2781             LE = LE.isValid() ? std::max(LE, I->end) : I->end;
2782         }
2783         if (LE.isValid())
2784           NewEnd = std::min(NewEnd, LE);
2785         if (ED.isValid())
2786           NewEnd = std::min(NewEnd, ED);
2787 
2788         // We only want to do the extension if there was a subrange that
2789         // was live across Def.
2790         if (LE.isValid()) {
2791           LiveRange::iterator S = LR.find(Def);
2792           if (S != LR.begin())
2793             std::prev(S)->end = NewEnd;
2794         }
2795       }
2796       DEBUG({
2797         dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';
2798         if (LI != nullptr)
2799           dbgs() << "\t\t  LHS = " << *LI << '\n';
2800       });
2801       LLVM_FALLTHROUGH;
2802     }
2803 
2804     case CR_Erase: {
2805       MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2806       assert(MI && "No instruction to erase");
2807       if (MI->isCopy()) {
2808         unsigned Reg = MI->getOperand(1).getReg();
2809         if (TargetRegisterInfo::isVirtualRegister(Reg) &&
2810             Reg != CP.getSrcReg() && Reg != CP.getDstReg())
2811           ShrinkRegs.push_back(Reg);
2812       }
2813       ErasedInstrs.insert(MI);
2814       DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
2815       LIS->RemoveMachineInstrFromMaps(*MI);
2816       MI->eraseFromParent();
2817       break;
2818     }
2819     default:
2820       break;
2821     }
2822   }
2823 }
2824 
2825 void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
2826                                          LaneBitmask LaneMask,
2827                                          const CoalescerPair &CP) {
2828   SmallVector<VNInfo*, 16> NewVNInfo;
2829   JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask,
2830                    NewVNInfo, CP, LIS, TRI, true, true);
2831   JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
2832                    NewVNInfo, CP, LIS, TRI, true, true);
2833 
2834   // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
2835   // We should be able to resolve all conflicts here as we could successfully do
2836   // it on the mainrange already. There is however a problem when multiple
2837   // ranges get mapped to the "overflow" lane mask bit which creates unexpected
2838   // interferences.
2839   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
2840     // We already determined that it is legal to merge the intervals, so this
2841     // should never fail.
2842     llvm_unreachable("*** Couldn't join subrange!\n");
2843   }
2844   if (!LHSVals.resolveConflicts(RHSVals) ||
2845       !RHSVals.resolveConflicts(LHSVals)) {
2846     // We already determined that it is legal to merge the intervals, so this
2847     // should never fail.
2848     llvm_unreachable("*** Couldn't join subrange!\n");
2849   }
2850 
2851   // The merging algorithm in LiveInterval::join() can't handle conflicting
2852   // value mappings, so we need to remove any live ranges that overlap a
2853   // CR_Replace resolution. Collect a set of end points that can be used to
2854   // restore the live range after joining.
2855   SmallVector<SlotIndex, 8> EndPoints;
2856   LHSVals.pruneValues(RHSVals, EndPoints, false);
2857   RHSVals.pruneValues(LHSVals, EndPoints, false);
2858 
2859   LHSVals.removeImplicitDefs();
2860   RHSVals.removeImplicitDefs();
2861 
2862   LRange.verify();
2863   RRange.verify();
2864 
2865   // Join RRange into LHS.
2866   LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
2867               NewVNInfo);
2868 
2869   DEBUG(dbgs() << "\t\tjoined lanes: " << LRange << "\n");
2870   if (EndPoints.empty())
2871     return;
2872 
2873   // Recompute the parts of the live range we had to remove because of
2874   // CR_Replace conflicts.
2875   DEBUG({
2876     dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
2877     for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
2878       dbgs() << EndPoints[i];
2879       if (i != n-1)
2880         dbgs() << ',';
2881     }
2882     dbgs() << ":  " << LRange << '\n';
2883   });
2884   LIS->extendToIndices(LRange, EndPoints);
2885 }
2886 
2887 void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
2888                                           const LiveRange &ToMerge,
2889                                           LaneBitmask LaneMask,
2890                                           CoalescerPair &CP) {
2891   BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2892   for (LiveInterval::SubRange &R : LI.subranges()) {
2893     LaneBitmask RMask = R.LaneMask;
2894     // LaneMask of subregisters common to subrange R and ToMerge.
2895     LaneBitmask Common = RMask & LaneMask;
2896     // There is nothing to do without common subregs.
2897     if (Common.none())
2898       continue;
2899 
2900     DEBUG(dbgs() << "\t\tCopy+Merge " << PrintLaneMask(RMask) << " into "
2901                  << PrintLaneMask(Common) << '\n');
2902     // LaneMask of subregisters contained in the R range but not in ToMerge,
2903     // they have to split into their own subrange.
2904     LaneBitmask LRest = RMask & ~LaneMask;
2905     LiveInterval::SubRange *CommonRange;
2906     if (LRest.any()) {
2907       R.LaneMask = LRest;
2908       DEBUG(dbgs() << "\t\tReduce Lane to " << PrintLaneMask(LRest) << '\n');
2909       // Duplicate SubRange for newly merged common stuff.
2910       CommonRange = LI.createSubRangeFrom(Allocator, Common, R);
2911     } else {
2912       // Reuse the existing range.
2913       R.LaneMask = Common;
2914       CommonRange = &R;
2915     }
2916     LiveRange RangeCopy(ToMerge, Allocator);
2917     joinSubRegRanges(*CommonRange, RangeCopy, Common, CP);
2918     LaneMask &= ~RMask;
2919   }
2920 
2921   if (LaneMask.any()) {
2922     DEBUG(dbgs() << "\t\tNew Lane " << PrintLaneMask(LaneMask) << '\n');
2923     LI.createSubRangeFrom(Allocator, LaneMask, ToMerge);
2924   }
2925 }
2926 
2927 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
2928   SmallVector<VNInfo*, 16> NewVNInfo;
2929   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
2930   LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
2931   bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
2932   JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(),
2933                    NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
2934   JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
2935                    NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
2936 
2937   DEBUG(dbgs() << "\t\tRHS = " << RHS
2938                << "\n\t\tLHS = " << LHS
2939                << '\n');
2940 
2941   // First compute NewVNInfo and the simple value mappings.
2942   // Detect impossible conflicts early.
2943   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2944     return false;
2945 
2946   // Some conflicts can only be resolved after all values have been mapped.
2947   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2948     return false;
2949 
2950   // All clear, the live ranges can be merged.
2951   if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
2952     BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
2953 
2954     // Transform lanemasks from the LHS to masks in the coalesced register and
2955     // create initial subranges if necessary.
2956     unsigned DstIdx = CP.getDstIdx();
2957     if (!LHS.hasSubRanges()) {
2958       LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
2959                                      : TRI->getSubRegIndexLaneMask(DstIdx);
2960       // LHS must support subregs or we wouldn't be in this codepath.
2961       assert(Mask.any());
2962       LHS.createSubRangeFrom(Allocator, Mask, LHS);
2963     } else if (DstIdx != 0) {
2964       // Transform LHS lanemasks to new register class if necessary.
2965       for (LiveInterval::SubRange &R : LHS.subranges()) {
2966         LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
2967         R.LaneMask = Mask;
2968       }
2969     }
2970     DEBUG(dbgs() << "\t\tLHST = " << PrintReg(CP.getDstReg())
2971                  << ' ' << LHS << '\n');
2972 
2973     // Determine lanemasks of RHS in the coalesced register and merge subranges.
2974     unsigned SrcIdx = CP.getSrcIdx();
2975     if (!RHS.hasSubRanges()) {
2976       LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
2977                                      : TRI->getSubRegIndexLaneMask(SrcIdx);
2978       mergeSubRangeInto(LHS, RHS, Mask, CP);
2979     } else {
2980       // Pair up subranges and merge.
2981       for (LiveInterval::SubRange &R : RHS.subranges()) {
2982         LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
2983         mergeSubRangeInto(LHS, R, Mask, CP);
2984       }
2985     }
2986     DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
2987 
2988     // Pruning implicit defs from subranges may result in the main range
2989     // having stale segments.
2990     LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
2991 
2992     LHSVals.pruneSubRegValues(LHS, ShrinkMask);
2993     RHSVals.pruneSubRegValues(LHS, ShrinkMask);
2994   }
2995 
2996   // The merging algorithm in LiveInterval::join() can't handle conflicting
2997   // value mappings, so we need to remove any live ranges that overlap a
2998   // CR_Replace resolution. Collect a set of end points that can be used to
2999   // restore the live range after joining.
3000   SmallVector<SlotIndex, 8> EndPoints;
3001   LHSVals.pruneValues(RHSVals, EndPoints, true);
3002   RHSVals.pruneValues(LHSVals, EndPoints, true);
3003 
3004   // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
3005   // registers to require trimming.
3006   SmallVector<unsigned, 8> ShrinkRegs;
3007   LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
3008   RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
3009   while (!ShrinkRegs.empty())
3010     shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
3011 
3012   // Join RHS into LHS.
3013   LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
3014 
3015   // Kill flags are going to be wrong if the live ranges were overlapping.
3016   // Eventually, we should simply clear all kill flags when computing live
3017   // ranges. They are reinserted after register allocation.
3018   MRI->clearKillFlags(LHS.reg);
3019   MRI->clearKillFlags(RHS.reg);
3020 
3021   if (!EndPoints.empty()) {
3022     // Recompute the parts of the live range we had to remove because of
3023     // CR_Replace conflicts.
3024     DEBUG({
3025       dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
3026       for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
3027         dbgs() << EndPoints[i];
3028         if (i != n-1)
3029           dbgs() << ',';
3030       }
3031       dbgs() << ":  " << LHS << '\n';
3032     });
3033     LIS->extendToIndices((LiveRange&)LHS, EndPoints);
3034   }
3035 
3036   return true;
3037 }
3038 
3039 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
3040   return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
3041 }
3042 
3043 namespace {
3044 /// Information concerning MBB coalescing priority.
3045 struct MBBPriorityInfo {
3046   MachineBasicBlock *MBB;
3047   unsigned Depth;
3048   bool IsSplit;
3049 
3050   MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
3051     : MBB(mbb), Depth(depth), IsSplit(issplit) {}
3052 };
3053 }
3054 
3055 /// C-style comparator that sorts first based on the loop depth of the basic
3056 /// block (the unsigned), and then on the MBB number.
3057 ///
3058 /// EnableGlobalCopies assumes that the primary sort key is loop depth.
3059 static int compareMBBPriority(const MBBPriorityInfo *LHS,
3060                               const MBBPriorityInfo *RHS) {
3061   // Deeper loops first
3062   if (LHS->Depth != RHS->Depth)
3063     return LHS->Depth > RHS->Depth ? -1 : 1;
3064 
3065   // Try to unsplit critical edges next.
3066   if (LHS->IsSplit != RHS->IsSplit)
3067     return LHS->IsSplit ? -1 : 1;
3068 
3069   // Prefer blocks that are more connected in the CFG. This takes care of
3070   // the most difficult copies first while intervals are short.
3071   unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
3072   unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
3073   if (cl != cr)
3074     return cl > cr ? -1 : 1;
3075 
3076   // As a last resort, sort by block number.
3077   return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
3078 }
3079 
3080 /// \returns true if the given copy uses or defines a local live range.
3081 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
3082   if (!Copy->isCopy())
3083     return false;
3084 
3085   if (Copy->getOperand(1).isUndef())
3086     return false;
3087 
3088   unsigned SrcReg = Copy->getOperand(1).getReg();
3089   unsigned DstReg = Copy->getOperand(0).getReg();
3090   if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
3091       || TargetRegisterInfo::isPhysicalRegister(DstReg))
3092     return false;
3093 
3094   return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
3095     || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
3096 }
3097 
3098 bool RegisterCoalescer::
3099 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
3100   bool Progress = false;
3101   for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
3102     if (!CurrList[i])
3103       continue;
3104     // Skip instruction pointers that have already been erased, for example by
3105     // dead code elimination.
3106     if (ErasedInstrs.erase(CurrList[i])) {
3107       CurrList[i] = nullptr;
3108       continue;
3109     }
3110     bool Again = false;
3111     bool Success = joinCopy(CurrList[i], Again);
3112     Progress |= Success;
3113     if (Success || !Again)
3114       CurrList[i] = nullptr;
3115   }
3116   return Progress;
3117 }
3118 
3119 /// Check if DstReg is a terminal node.
3120 /// I.e., it does not have any affinity other than \p Copy.
3121 static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy,
3122                           const MachineRegisterInfo *MRI) {
3123   assert(Copy.isCopyLike());
3124   // Check if the destination of this copy as any other affinity.
3125   for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
3126     if (&MI != &Copy && MI.isCopyLike())
3127       return false;
3128   return true;
3129 }
3130 
3131 bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
3132   assert(Copy.isCopyLike());
3133   if (!UseTerminalRule)
3134     return false;
3135   unsigned DstReg, DstSubReg, SrcReg, SrcSubReg;
3136   isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg);
3137   // Check if the destination of this copy has any other affinity.
3138   if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
3139       // If SrcReg is a physical register, the copy won't be coalesced.
3140       // Ignoring it may have other side effect (like missing
3141       // rematerialization). So keep it.
3142       TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
3143       !isTerminalReg(DstReg, Copy, MRI))
3144     return false;
3145 
3146   // DstReg is a terminal node. Check if it interferes with any other
3147   // copy involving SrcReg.
3148   const MachineBasicBlock *OrigBB = Copy.getParent();
3149   const LiveInterval &DstLI = LIS->getInterval(DstReg);
3150   for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
3151     // Technically we should check if the weight of the new copy is
3152     // interesting compared to the other one and update the weight
3153     // of the copies accordingly. However, this would only work if
3154     // we would gather all the copies first then coalesce, whereas
3155     // right now we interleave both actions.
3156     // For now, just consider the copies that are in the same block.
3157     if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
3158       continue;
3159     unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg;
3160     isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
3161                 OtherSubReg);
3162     if (OtherReg == SrcReg)
3163       OtherReg = OtherSrcReg;
3164     // Check if OtherReg is a non-terminal.
3165     if (TargetRegisterInfo::isPhysicalRegister(OtherReg) ||
3166         isTerminalReg(OtherReg, MI, MRI))
3167       continue;
3168     // Check that OtherReg interfere with DstReg.
3169     if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
3170       DEBUG(dbgs() << "Apply terminal rule for: " << PrintReg(DstReg) << '\n');
3171       return true;
3172     }
3173   }
3174   return false;
3175 }
3176 
3177 void
3178 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
3179   DEBUG(dbgs() << MBB->getName() << ":\n");
3180 
3181   // Collect all copy-like instructions in MBB. Don't start coalescing anything
3182   // yet, it might invalidate the iterator.
3183   const unsigned PrevSize = WorkList.size();
3184   if (JoinGlobalCopies) {
3185     SmallVector<MachineInstr*, 2> LocalTerminals;
3186     SmallVector<MachineInstr*, 2> GlobalTerminals;
3187     // Coalesce copies bottom-up to coalesce local defs before local uses. They
3188     // are not inherently easier to resolve, but slightly preferable until we
3189     // have local live range splitting. In particular this is required by
3190     // cmp+jmp macro fusion.
3191     for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
3192          MII != E; ++MII) {
3193       if (!MII->isCopyLike())
3194         continue;
3195       bool ApplyTerminalRule = applyTerminalRule(*MII);
3196       if (isLocalCopy(&(*MII), LIS)) {
3197         if (ApplyTerminalRule)
3198           LocalTerminals.push_back(&(*MII));
3199         else
3200           LocalWorkList.push_back(&(*MII));
3201       } else {
3202         if (ApplyTerminalRule)
3203           GlobalTerminals.push_back(&(*MII));
3204         else
3205           WorkList.push_back(&(*MII));
3206       }
3207     }
3208     // Append the copies evicted by the terminal rule at the end of the list.
3209     LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
3210     WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
3211   }
3212   else {
3213     SmallVector<MachineInstr*, 2> Terminals;
3214     for (MachineInstr &MII : *MBB)
3215       if (MII.isCopyLike()) {
3216         if (applyTerminalRule(MII))
3217           Terminals.push_back(&MII);
3218         else
3219           WorkList.push_back(&MII);
3220       }
3221     // Append the copies evicted by the terminal rule at the end of the list.
3222     WorkList.append(Terminals.begin(), Terminals.end());
3223   }
3224   // Try coalescing the collected copies immediately, and remove the nulls.
3225   // This prevents the WorkList from getting too large since most copies are
3226   // joinable on the first attempt.
3227   MutableArrayRef<MachineInstr*>
3228     CurrList(WorkList.begin() + PrevSize, WorkList.end());
3229   if (copyCoalesceWorkList(CurrList))
3230     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
3231                                (MachineInstr*)nullptr), WorkList.end());
3232 }
3233 
3234 void RegisterCoalescer::coalesceLocals() {
3235   copyCoalesceWorkList(LocalWorkList);
3236   for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
3237     if (LocalWorkList[j])
3238       WorkList.push_back(LocalWorkList[j]);
3239   }
3240   LocalWorkList.clear();
3241 }
3242 
3243 void RegisterCoalescer::joinAllIntervals() {
3244   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
3245   assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
3246 
3247   std::vector<MBBPriorityInfo> MBBs;
3248   MBBs.reserve(MF->size());
3249   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
3250     MachineBasicBlock *MBB = &*I;
3251     MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
3252                                    JoinSplitEdges && isSplitEdge(MBB)));
3253   }
3254   array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
3255 
3256   // Coalesce intervals in MBB priority order.
3257   unsigned CurrDepth = UINT_MAX;
3258   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
3259     // Try coalescing the collected local copies for deeper loops.
3260     if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
3261       coalesceLocals();
3262       CurrDepth = MBBs[i].Depth;
3263     }
3264     copyCoalesceInMBB(MBBs[i].MBB);
3265   }
3266   coalesceLocals();
3267 
3268   // Joining intervals can allow other intervals to be joined.  Iteratively join
3269   // until we make no progress.
3270   while (copyCoalesceWorkList(WorkList))
3271     /* empty */ ;
3272 }
3273 
3274 void RegisterCoalescer::releaseMemory() {
3275   ErasedInstrs.clear();
3276   WorkList.clear();
3277   DeadDefs.clear();
3278   InflateRegs.clear();
3279 }
3280 
3281 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
3282   MF = &fn;
3283   MRI = &fn.getRegInfo();
3284   TM = &fn.getTarget();
3285   const TargetSubtargetInfo &STI = fn.getSubtarget();
3286   TRI = STI.getRegisterInfo();
3287   TII = STI.getInstrInfo();
3288   LIS = &getAnalysis<LiveIntervals>();
3289   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3290   Loops = &getAnalysis<MachineLoopInfo>();
3291   if (EnableGlobalCopies == cl::BOU_UNSET)
3292     JoinGlobalCopies = STI.enableJoinGlobalCopies();
3293   else
3294     JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
3295 
3296   // The MachineScheduler does not currently require JoinSplitEdges. This will
3297   // either be enabled unconditionally or replaced by a more general live range
3298   // splitting optimization.
3299   JoinSplitEdges = EnableJoinSplits;
3300 
3301   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
3302                << "********** Function: " << MF->getName() << '\n');
3303 
3304   if (VerifyCoalescing)
3305     MF->verify(this, "Before register coalescing");
3306 
3307   RegClassInfo.runOnMachineFunction(fn);
3308 
3309   // Join (coalesce) intervals if requested.
3310   if (EnableJoining)
3311     joinAllIntervals();
3312 
3313   // After deleting a lot of copies, register classes may be less constrained.
3314   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
3315   // DPR inflation.
3316   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
3317   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
3318                     InflateRegs.end());
3319   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
3320   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
3321     unsigned Reg = InflateRegs[i];
3322     if (MRI->reg_nodbg_empty(Reg))
3323       continue;
3324     if (MRI->recomputeRegClass(Reg)) {
3325       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
3326                    << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
3327       ++NumInflated;
3328 
3329       LiveInterval &LI = LIS->getInterval(Reg);
3330       if (LI.hasSubRanges()) {
3331         // If the inflated register class does not support subregisters anymore
3332         // remove the subranges.
3333         if (!MRI->shouldTrackSubRegLiveness(Reg)) {
3334           LI.clearSubRanges();
3335         } else {
3336 #ifndef NDEBUG
3337           LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
3338           // If subranges are still supported, then the same subregs
3339           // should still be supported.
3340           for (LiveInterval::SubRange &S : LI.subranges()) {
3341             assert((S.LaneMask & ~MaxMask).none());
3342           }
3343 #endif
3344         }
3345       }
3346     }
3347   }
3348 
3349   DEBUG(dump());
3350   if (VerifyCoalescing)
3351     MF->verify(this, "After register coalescing");
3352   return true;
3353 }
3354 
3355 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
3356    LIS->print(O, m);
3357 }
3358