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