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