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