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