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