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