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