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