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