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