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