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