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