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