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