Coalesce subreg-subreg copies.
[oota-llvm.git] / lib / CodeGen / RegisterCoalescer.cpp
1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "regalloc"
17 #include "RegisterCoalescer.h"
18 #include "LiveDebugVariables.h"
19 #include "RegisterClassInfo.h"
20 #include "VirtRegMap.h"
21
22 #include "llvm/Pass.h"
23 #include "llvm/Value.h"
24 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/ADT/OwningPtr.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/STLExtras.h"
47 #include <algorithm>
48 #include <cmath>
49 using namespace llvm;
50
51 STATISTIC(numJoins    , "Number of interval joins performed");
52 STATISTIC(numCrossRCs , "Number of cross class joins performed");
53 STATISTIC(numCommutes , "Number of instruction commuting performed");
54 STATISTIC(numExtends  , "Number of copies extended");
55 STATISTIC(NumReMats   , "Number of instructions re-materialized");
56 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
57 STATISTIC(numAborts   , "Number of times interval joining aborted");
58 STATISTIC(NumInflated , "Number of register classes inflated");
59
60 static cl::opt<bool>
61 EnableJoining("join-liveintervals",
62               cl::desc("Coalesce copies (default=true)"),
63               cl::init(true));
64
65 static cl::opt<bool>
66 EnablePhysicalJoin("join-physregs",
67                    cl::desc("Join physical register copies"),
68                    cl::init(false), 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     MachineFunction* MF;
78     MachineRegisterInfo* MRI;
79     const TargetMachine* TM;
80     const TargetRegisterInfo* TRI;
81     const TargetInstrInfo* TII;
82     LiveIntervals *LIS;
83     LiveDebugVariables *LDV;
84     const MachineLoopInfo* Loops;
85     AliasAnalysis *AA;
86     RegisterClassInfo RegClassInfo;
87
88     /// JoinedCopies - Keep track of copies eliminated due to coalescing.
89     ///
90     SmallPtrSet<MachineInstr*, 32> JoinedCopies;
91
92     /// ReMatCopies - Keep track of copies eliminated due to remat.
93     ///
94     SmallPtrSet<MachineInstr*, 32> ReMatCopies;
95
96     /// ReMatDefs - Keep track of definition instructions which have
97     /// been remat'ed.
98     SmallPtrSet<MachineInstr*, 8> ReMatDefs;
99
100     /// joinIntervals - join compatible live intervals
101     void joinIntervals();
102
103     /// CopyCoalesceInMBB - Coalesce copies in the specified MBB, putting
104     /// copies that cannot yet be coalesced into the "TryAgain" list.
105     void CopyCoalesceInMBB(MachineBasicBlock *MBB,
106                            std::vector<MachineInstr*> &TryAgain);
107
108     /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
109     /// which are the src/dst of the copy instruction CopyMI.  This returns
110     /// true if the copy was successfully coalesced away. If it is not
111     /// currently possible to coalesce this interval, but it may be possible if
112     /// other things get coalesced, then it returns true by reference in
113     /// 'Again'.
114     bool JoinCopy(MachineInstr *TheCopy, bool &Again);
115
116     /// JoinIntervals - Attempt to join these two intervals.  On failure, this
117     /// returns false.  The output "SrcInt" will not have been modified, so we
118     /// can use this information below to update aliases.
119     bool JoinIntervals(CoalescerPair &CP);
120
121     /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
122     /// the source value number is defined by a copy from the destination reg
123     /// see if we can merge these two destination reg valno# into a single
124     /// value number, eliminating a copy.
125     bool AdjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
126
127     /// HasOtherReachingDefs - Return true if there are definitions of IntB
128     /// other than BValNo val# that can reach uses of AValno val# of IntA.
129     bool HasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
130                               VNInfo *AValNo, VNInfo *BValNo);
131
132     /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy.
133     /// If the source value number is defined by a commutable instruction and
134     /// its other operand is coalesced to the copy dest register, see if we
135     /// can transform the copy into a noop by commuting the definition.
136     bool RemoveCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
137
138     /// ReMaterializeTrivialDef - If the source of a copy is defined by a
139     /// trivial computation, replace the copy by rematerialize the definition.
140     /// If PreserveSrcInt is true, make sure SrcInt is valid after the call.
141     bool ReMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt,
142                                  unsigned DstReg, MachineInstr *CopyMI);
143
144     /// shouldJoinPhys - Return true if a physreg copy should be joined.
145     bool shouldJoinPhys(CoalescerPair &CP);
146
147     /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
148     /// update the subregister number if it is not zero. If DstReg is a
149     /// physical register and the existing subregister number of the def / use
150     /// being updated is not zero, make sure to set it to the correct physical
151     /// subregister.
152     void UpdateRegDefsUses(const CoalescerPair &CP);
153
154     /// RemoveDeadDef - If a def of a live interval is now determined dead,
155     /// remove the val# it defines. If the live interval becomes empty, remove
156     /// it as well.
157     bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI);
158
159     /// markAsJoined - Remember that CopyMI has already been joined.
160     void markAsJoined(MachineInstr *CopyMI);
161
162     /// eliminateUndefCopy - Handle copies of undef values.
163     bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
164
165   public:
166     static char ID; // Class identification, replacement for typeinfo
167     RegisterCoalescer() : MachineFunctionPass(ID) {
168       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
169     }
170
171     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
172
173     virtual void releaseMemory();
174
175     /// runOnMachineFunction - pass entry point
176     virtual bool runOnMachineFunction(MachineFunction&);
177
178     /// print - Implement the dump method.
179     virtual void print(raw_ostream &O, const Module* = 0) const;
180   };
181 } /// end anonymous namespace
182
183 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
184
185 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
186                       "Simple Register Coalescing", false, false)
187 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
188 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
189 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
190 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
191 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
192 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
193                     "Simple Register Coalescing", false, false)
194
195 char RegisterCoalescer::ID = 0;
196
197 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
198   if (!a) return b;
199   if (!b) return a;
200   return tri.composeSubRegIndices(a, b);
201 }
202
203 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
204                         unsigned &Src, unsigned &Dst,
205                         unsigned &SrcSub, unsigned &DstSub) {
206   if (MI->isCopy()) {
207     Dst = MI->getOperand(0).getReg();
208     DstSub = MI->getOperand(0).getSubReg();
209     Src = MI->getOperand(1).getReg();
210     SrcSub = MI->getOperand(1).getSubReg();
211   } else if (MI->isSubregToReg()) {
212     Dst = MI->getOperand(0).getReg();
213     DstSub = compose(tri, MI->getOperand(0).getSubReg(),
214                      MI->getOperand(3).getImm());
215     Src = MI->getOperand(2).getReg();
216     SrcSub = MI->getOperand(2).getSubReg();
217   } else
218     return false;
219   return true;
220 }
221
222 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
223   SrcReg = DstReg = SubIdx = 0;
224   NewRC = 0;
225   Flipped = CrossClass = false;
226
227   unsigned Src, Dst, SrcSub, DstSub;
228   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
229     return false;
230   Partial = SrcSub || DstSub;
231
232   // If one register is a physreg, it must be Dst.
233   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
234     if (TargetRegisterInfo::isPhysicalRegister(Dst))
235       return false;
236     std::swap(Src, Dst);
237     std::swap(SrcSub, DstSub);
238     Flipped = true;
239   }
240
241   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
242
243   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
244     // Eliminate DstSub on a physreg.
245     if (DstSub) {
246       Dst = TRI.getSubReg(Dst, DstSub);
247       if (!Dst) return false;
248       DstSub = 0;
249     }
250
251     // Eliminate SrcSub by picking a corresponding Dst superregister.
252     if (SrcSub) {
253       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
254       if (!Dst) return false;
255       SrcSub = 0;
256     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
257       return false;
258     }
259   } else {
260     // Both registers are virtual.
261     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
262     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
263
264     // Both registers have subreg indices.
265     if (SrcSub && DstSub) {
266       unsigned SrcPre, DstPre;
267       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
268                                          SrcPre, DstPre);
269       if (!NewRC)
270         return false;
271
272       // We cannot handle the case where both Src and Dst would be a
273       // sub-register. Yet.
274       if (SrcPre && DstPre) {
275         DEBUG(dbgs() << "\tCannot handle " << NewRC->getName()
276                      << " with subregs " << TRI.getSubRegIndexName(SrcPre)
277                      << " and " << TRI.getSubRegIndexName(DstPre) << '\n');
278         return false;
279       }
280
281       // One of these will be 0, so one register is a sub-register of the other.
282       SrcSub = DstPre;
283       DstSub = SrcPre;
284     }
285
286     // There can be no SrcSub.
287     if (SrcSub) {
288       std::swap(Src, Dst);
289       std::swap(SrcRC, DstRC);
290       DstSub = SrcSub;
291       SrcSub = 0;
292       assert(!Flipped && "Unexpected flip");
293       Flipped = true;
294     }
295
296     // Find the new register class.
297     if (!NewRC) {
298       if (DstSub)
299         NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
300       else
301         NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
302     }
303     if (!NewRC)
304       return false;
305     CrossClass = NewRC != DstRC || NewRC != SrcRC;
306   }
307   // Check our invariants
308   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
309   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
310          "Cannot have a physical SubIdx");
311   SrcReg = Src;
312   DstReg = Dst;
313   SubIdx = DstSub;
314   return true;
315 }
316
317 bool CoalescerPair::flip() {
318   if (SubIdx || TargetRegisterInfo::isPhysicalRegister(DstReg))
319     return false;
320   std::swap(SrcReg, DstReg);
321   Flipped = !Flipped;
322   return true;
323 }
324
325 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
326   if (!MI)
327     return false;
328   unsigned Src, Dst, SrcSub, DstSub;
329   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
330     return false;
331
332   // Find the virtual register that is SrcReg.
333   if (Dst == SrcReg) {
334     std::swap(Src, Dst);
335     std::swap(SrcSub, DstSub);
336   } else if (Src != SrcReg) {
337     return false;
338   }
339
340   // Now check that Dst matches DstReg.
341   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
342     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
343       return false;
344     assert(!SubIdx && "Inconsistent CoalescerPair state.");
345     // DstSub could be set for a physreg from INSERT_SUBREG.
346     if (DstSub)
347       Dst = TRI.getSubReg(Dst, DstSub);
348     // Full copy of Src.
349     if (!SrcSub)
350       return DstReg == Dst;
351     // This is a partial register copy. Check that the parts match.
352     return TRI.getSubReg(DstReg, SrcSub) == Dst;
353   } else {
354     // DstReg is virtual.
355     if (DstReg != Dst)
356       return false;
357     // Registers match, do the subregisters line up?
358     return compose(TRI, SubIdx, SrcSub) == DstSub;
359   }
360 }
361
362 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
363   AU.setPreservesCFG();
364   AU.addRequired<AliasAnalysis>();
365   AU.addRequired<LiveIntervals>();
366   AU.addPreserved<LiveIntervals>();
367   AU.addRequired<LiveDebugVariables>();
368   AU.addPreserved<LiveDebugVariables>();
369   AU.addPreserved<SlotIndexes>();
370   AU.addRequired<MachineLoopInfo>();
371   AU.addPreserved<MachineLoopInfo>();
372   AU.addPreservedID(MachineDominatorsID);
373   MachineFunctionPass::getAnalysisUsage(AU);
374 }
375
376 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
377   /// Joined copies are not deleted immediately, but kept in JoinedCopies.
378   JoinedCopies.insert(CopyMI);
379
380   /// Mark all register operands of CopyMI as <undef> so they won't affect dead
381   /// code elimination.
382   for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
383        E = CopyMI->operands_end(); I != E; ++I)
384     if (I->isReg())
385       I->setIsUndef(true);
386 }
387
388 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
389 /// being the source and IntB being the dest, thus this defines a value number
390 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
391 /// see if we can merge these two pieces of B into a single value number,
392 /// eliminating a copy.  For example:
393 ///
394 ///  A3 = B0
395 ///    ...
396 ///  B1 = A3      <- this copy
397 ///
398 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
399 /// value number to be replaced with B0 (which simplifies the B liveinterval).
400 ///
401 /// This returns true if an interval was modified.
402 ///
403 bool RegisterCoalescer::AdjustCopiesBackFrom(const CoalescerPair &CP,
404                                                     MachineInstr *CopyMI) {
405   // Bail if there is no dst interval - can happen when merging physical subreg
406   // operations.
407   if (!LIS->hasInterval(CP.getDstReg()))
408     return false;
409
410   LiveInterval &IntA =
411     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
412   LiveInterval &IntB =
413     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
414   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
415
416   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
417   // the example above.
418   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
419   if (BLR == IntB.end()) return false;
420   VNInfo *BValNo = BLR->valno;
421
422   // Get the location that B is defined at.  Two options: either this value has
423   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
424   // can't process it.
425   if (BValNo->def != CopyIdx) return false;
426
427   // AValNo is the value number in A that defines the copy, A3 in the example.
428   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
429   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
430   // The live range might not exist after fun with physreg coalescing.
431   if (ALR == IntA.end()) return false;
432   VNInfo *AValNo = ALR->valno;
433
434   // If AValNo is defined as a copy from IntB, we can potentially process this.
435   // Get the instruction that defines this value number.
436   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
437   if (!CP.isCoalescable(ACopyMI))
438     return false;
439
440   // Get the LiveRange in IntB that this value number starts with.
441   LiveInterval::iterator ValLR =
442     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
443   if (ValLR == IntB.end())
444     return false;
445
446   // Make sure that the end of the live range is inside the same block as
447   // CopyMI.
448   MachineInstr *ValLREndInst =
449     LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
450   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
451     return false;
452
453   // Okay, we now know that ValLR ends in the same block that the CopyMI
454   // live-range starts.  If there are no intervening live ranges between them in
455   // IntB, we can merge them.
456   if (ValLR+1 != BLR) return false;
457
458   // If a live interval is a physical register, conservatively check if any
459   // of its aliases is overlapping the live interval of the virtual register.
460   // If so, do not coalesce.
461   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
462     for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
463       if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
464         DEBUG({
465             dbgs() << "\t\tInterfere with alias ";
466             LIS->getInterval(*AS).print(dbgs(), TRI);
467           });
468         return false;
469       }
470   }
471
472   DEBUG({
473       dbgs() << "Extending: ";
474       IntB.print(dbgs(), TRI);
475     });
476
477   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
478   // We are about to delete CopyMI, so need to remove it as the 'instruction
479   // that defines this value #'. Update the valnum with the new defining
480   // instruction #.
481   BValNo->def = FillerStart;
482
483   // Okay, we can merge them.  We need to insert a new liverange:
484   // [ValLR.end, BLR.begin) of either value number, then we merge the
485   // two value numbers.
486   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
487
488   // If the IntB live range is assigned to a physical register, and if that
489   // physreg has sub-registers, update their live intervals as well.
490   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
491     for (const uint16_t *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
492       if (!LIS->hasInterval(*SR))
493         continue;
494       LiveInterval &SRLI = LIS->getInterval(*SR);
495       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
496                               SRLI.getNextValue(FillerStart,
497                                                 LIS->getVNInfoAllocator())));
498     }
499   }
500
501   // Okay, merge "B1" into the same value number as "B0".
502   if (BValNo != ValLR->valno) {
503     // If B1 is killed by a PHI, then the merged live range must also be killed
504     // by the same PHI, as B0 and B1 can not overlap.
505     bool HasPHIKill = BValNo->hasPHIKill();
506     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
507     if (HasPHIKill)
508       ValLR->valno->setHasPHIKill(true);
509   }
510   DEBUG({
511       dbgs() << "   result = ";
512       IntB.print(dbgs(), TRI);
513       dbgs() << "\n";
514     });
515
516   // If the source instruction was killing the source register before the
517   // merge, unset the isKill marker given the live range has been extended.
518   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
519   if (UIdx != -1) {
520     ValLREndInst->getOperand(UIdx).setIsKill(false);
521   }
522
523   // Rewrite the copy. If the copy instruction was killing the destination
524   // register before the merge, find the last use and trim the live range. That
525   // will also add the isKill marker.
526   CopyMI->substituteRegister(IntA.reg, IntB.reg, CP.getSubIdx(),
527                              *TRI);
528   if (ALR->end == CopyIdx)
529     LIS->shrinkToUses(&IntA);
530
531   ++numExtends;
532   return true;
533 }
534
535 /// HasOtherReachingDefs - Return true if there are definitions of IntB
536 /// other than BValNo val# that can reach uses of AValno val# of IntA.
537 bool RegisterCoalescer::HasOtherReachingDefs(LiveInterval &IntA,
538                                                     LiveInterval &IntB,
539                                                     VNInfo *AValNo,
540                                                     VNInfo *BValNo) {
541   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
542        AI != AE; ++AI) {
543     if (AI->valno != AValNo) continue;
544     LiveInterval::Ranges::iterator BI =
545       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
546     if (BI != IntB.ranges.begin())
547       --BI;
548     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
549       if (BI->valno == BValNo)
550         continue;
551       if (BI->start <= AI->start && BI->end > AI->start)
552         return true;
553       if (BI->start > AI->start && BI->start < AI->end)
554         return true;
555     }
556   }
557   return false;
558 }
559
560 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
561 /// IntA being the source and IntB being the dest, thus this defines a value
562 /// number in IntB.  If the source value number (in IntA) is defined by a
563 /// commutable instruction and its other operand is coalesced to the copy dest
564 /// register, see if we can transform the copy into a noop by commuting the
565 /// definition. For example,
566 ///
567 ///  A3 = op A2 B0<kill>
568 ///    ...
569 ///  B1 = A3      <- this copy
570 ///    ...
571 ///     = op A3   <- more uses
572 ///
573 /// ==>
574 ///
575 ///  B2 = op B0 A2<kill>
576 ///    ...
577 ///  B1 = B2      <- now an identify copy
578 ///    ...
579 ///     = op B2   <- more uses
580 ///
581 /// This returns true if an interval was modified.
582 ///
583 bool RegisterCoalescer::RemoveCopyByCommutingDef(const CoalescerPair &CP,
584                                                         MachineInstr *CopyMI) {
585   // FIXME: For now, only eliminate the copy by commuting its def when the
586   // source register is a virtual register. We want to guard against cases
587   // where the copy is a back edge copy and commuting the def lengthen the
588   // live interval of the source register to the entire loop.
589   if (CP.isPhys() && CP.isFlipped())
590     return false;
591
592   // Bail if there is no dst interval.
593   if (!LIS->hasInterval(CP.getDstReg()))
594     return false;
595
596   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
597
598   LiveInterval &IntA =
599     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
600   LiveInterval &IntB =
601     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
602
603   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
604   // the example above.
605   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
606   if (!BValNo || BValNo->def != CopyIdx)
607     return false;
608
609   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
610
611   // AValNo is the value number in A that defines the copy, A3 in the example.
612   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
613   assert(AValNo && "COPY source not live");
614
615   // If other defs can reach uses of this def, then it's not safe to perform
616   // the optimization.
617   if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
618     return false;
619   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
620   if (!DefMI)
621     return false;
622   if (!DefMI->isCommutable())
623     return false;
624   // If DefMI is a two-address instruction then commuting it will change the
625   // destination register.
626   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
627   assert(DefIdx != -1);
628   unsigned UseOpIdx;
629   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
630     return false;
631   unsigned Op1, Op2, NewDstIdx;
632   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
633     return false;
634   if (Op1 == UseOpIdx)
635     NewDstIdx = Op2;
636   else if (Op2 == UseOpIdx)
637     NewDstIdx = Op1;
638   else
639     return false;
640
641   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
642   unsigned NewReg = NewDstMO.getReg();
643   if (NewReg != IntB.reg || !NewDstMO.isKill())
644     return false;
645
646   // Make sure there are no other definitions of IntB that would reach the
647   // uses which the new definition can reach.
648   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
649     return false;
650
651   // Abort if the aliases of IntB.reg have values that are not simply the
652   // clobbers from the superreg.
653   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
654     for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
655       if (LIS->hasInterval(*AS) &&
656           HasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
657         return false;
658
659   // If some of the uses of IntA.reg is already coalesced away, return false.
660   // It's not possible to determine whether it's safe to perform the coalescing.
661   for (MachineRegisterInfo::use_nodbg_iterator UI =
662          MRI->use_nodbg_begin(IntA.reg),
663        UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
664     MachineInstr *UseMI = &*UI;
665     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
666     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
667     if (ULR == IntA.end())
668       continue;
669     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
670       return false;
671   }
672
673   DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
674                << *DefMI);
675
676   // At this point we have decided that it is legal to do this
677   // transformation.  Start by commuting the instruction.
678   MachineBasicBlock *MBB = DefMI->getParent();
679   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
680   if (!NewMI)
681     return false;
682   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
683       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
684       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
685     return false;
686   if (NewMI != DefMI) {
687     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
688     MachineBasicBlock::iterator Pos = DefMI;
689     MBB->insert(Pos, NewMI);
690     MBB->erase(DefMI);
691   }
692   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
693   NewMI->getOperand(OpIdx).setIsKill();
694
695   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
696   // A = or A, B
697   // ...
698   // B = A
699   // ...
700   // C = A<kill>
701   // ...
702   //   = B
703
704   // Update uses of IntA of the specific Val# with IntB.
705   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
706          UE = MRI->use_end(); UI != UE;) {
707     MachineOperand &UseMO = UI.getOperand();
708     MachineInstr *UseMI = &*UI;
709     ++UI;
710     if (JoinedCopies.count(UseMI))
711       continue;
712     if (UseMI->isDebugValue()) {
713       // FIXME These don't have an instruction index.  Not clear we have enough
714       // info to decide whether to do this replacement or not.  For now do it.
715       UseMO.setReg(NewReg);
716       continue;
717     }
718     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
719     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
720     if (ULR == IntA.end() || ULR->valno != AValNo)
721       continue;
722     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
723       UseMO.substPhysReg(NewReg, *TRI);
724     else
725       UseMO.setReg(NewReg);
726     if (UseMI == CopyMI)
727       continue;
728     if (!UseMI->isCopy())
729       continue;
730     if (UseMI->getOperand(0).getReg() != IntB.reg ||
731         UseMI->getOperand(0).getSubReg())
732       continue;
733
734     // This copy will become a noop. If it's defining a new val#, merge it into
735     // BValNo.
736     SlotIndex DefIdx = UseIdx.getRegSlot();
737     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
738     if (!DVNI)
739       continue;
740     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
741     assert(DVNI->def == DefIdx);
742     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
743     markAsJoined(UseMI);
744   }
745
746   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
747   // is updated.
748   VNInfo *ValNo = BValNo;
749   ValNo->def = AValNo->def;
750   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
751        AI != AE; ++AI) {
752     if (AI->valno != AValNo) continue;
753     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
754   }
755   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
756
757   IntA.removeValNo(AValNo);
758   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
759   ++numCommutes;
760   return true;
761 }
762
763 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
764 /// computation, replace the copy by rematerialize the definition.
765 bool RegisterCoalescer::ReMaterializeTrivialDef(LiveInterval &SrcInt,
766                                                        bool preserveSrcInt,
767                                                        unsigned DstReg,
768                                                        MachineInstr *CopyMI) {
769   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
770   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
771   assert(SrcLR != SrcInt.end() && "Live range not found!");
772   VNInfo *ValNo = SrcLR->valno;
773   if (ValNo->isPHIDef() || ValNo->isUnused())
774     return false;
775   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
776   if (!DefMI)
777     return false;
778   assert(DefMI && "Defining instruction disappeared");
779   if (!DefMI->isAsCheapAsAMove())
780     return false;
781   if (!TII->isTriviallyReMaterializable(DefMI, AA))
782     return false;
783   bool SawStore = false;
784   if (!DefMI->isSafeToMove(TII, AA, SawStore))
785     return false;
786   const MCInstrDesc &MCID = DefMI->getDesc();
787   if (MCID.getNumDefs() != 1)
788     return false;
789   if (!DefMI->isImplicitDef()) {
790     // Make sure the copy destination register class fits the instruction
791     // definition register class. The mismatch can happen as a result of earlier
792     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
793     const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
794     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
795       if (MRI->getRegClass(DstReg) != RC)
796         return false;
797     } else if (!RC->contains(DstReg))
798       return false;
799   }
800
801   MachineBasicBlock *MBB = CopyMI->getParent();
802   MachineBasicBlock::iterator MII =
803     llvm::next(MachineBasicBlock::iterator(CopyMI));
804   TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
805   MachineInstr *NewMI = prior(MII);
806
807   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
808   // We need to remember these so we can add intervals once we insert
809   // NewMI into SlotIndexes.
810   SmallVector<unsigned, 4> NewMIImplDefs;
811   for (unsigned i = NewMI->getDesc().getNumOperands(),
812          e = NewMI->getNumOperands(); i != e; ++i) {
813     MachineOperand &MO = NewMI->getOperand(i);
814     if (MO.isReg()) {
815       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
816              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
817       NewMIImplDefs.push_back(MO.getReg());
818     }
819   }
820
821   // CopyMI may have implicit operands, transfer them over to the newly
822   // rematerialized instruction. And update implicit def interval valnos.
823   for (unsigned i = CopyMI->getDesc().getNumOperands(),
824          e = CopyMI->getNumOperands(); i != e; ++i) {
825     MachineOperand &MO = CopyMI->getOperand(i);
826     if (MO.isReg()) {
827       assert(MO.isImplicit() && "No explicit operands after implict operands.");
828       // Discard VReg implicit defs.
829       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
830         NewMI->addOperand(MO);
831       }
832     }
833   }
834
835   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
836
837   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
838   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
839     unsigned reg = NewMIImplDefs[i];
840     LiveInterval &li = LIS->getInterval(reg);
841     VNInfo *DeadDefVN = li.getNextValue(NewMIIdx.getRegSlot(),
842                                         LIS->getVNInfoAllocator());
843     LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
844     li.addRange(lr);
845   }
846
847   CopyMI->eraseFromParent();
848   ReMatCopies.insert(CopyMI);
849   ReMatDefs.insert(DefMI);
850   DEBUG(dbgs() << "Remat: " << *NewMI);
851   ++NumReMats;
852
853   // The source interval can become smaller because we removed a use.
854   if (preserveSrcInt)
855     LIS->shrinkToUses(&SrcInt);
856
857   return true;
858 }
859
860 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
861 /// values, it only removes local variables. When we have a copy like:
862 ///
863 ///   %vreg1 = COPY %vreg2<undef>
864 ///
865 /// We delete the copy and remove the corresponding value number from %vreg1.
866 /// Any uses of that value number are marked as <undef>.
867 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
868                                            const CoalescerPair &CP) {
869   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
870   LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
871   if (SrcInt->liveAt(Idx))
872     return false;
873   LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
874   if (DstInt->liveAt(Idx))
875     return false;
876
877   // No intervals are live-in to CopyMI - it is undef.
878   if (CP.isFlipped())
879     DstInt = SrcInt;
880   SrcInt = 0;
881
882   VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
883   assert(DeadVNI && "No value defined in DstInt");
884   DstInt->removeValNo(DeadVNI);
885
886   // Find new undef uses.
887   for (MachineRegisterInfo::reg_nodbg_iterator
888          I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
889        I != E; ++I) {
890     MachineOperand &MO = I.getOperand();
891     if (MO.isDef() || MO.isUndef())
892       continue;
893     MachineInstr *MI = MO.getParent();
894     SlotIndex Idx = LIS->getInstructionIndex(MI);
895     if (DstInt->liveAt(Idx))
896       continue;
897     MO.setIsUndef(true);
898     DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
899   }
900   return true;
901 }
902
903 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
904 /// update the subregister number if it is not zero. If DstReg is a
905 /// physical register and the existing subregister number of the def / use
906 /// being updated is not zero, make sure to set it to the correct physical
907 /// subregister.
908 void
909 RegisterCoalescer::UpdateRegDefsUses(const CoalescerPair &CP) {
910   bool DstIsPhys = CP.isPhys();
911   unsigned SrcReg = CP.getSrcReg();
912   unsigned DstReg = CP.getDstReg();
913   unsigned SubIdx = CP.getSubIdx();
914
915   // Update LiveDebugVariables.
916   LDV->renameRegister(SrcReg, DstReg, SubIdx);
917
918   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
919        MachineInstr *UseMI = I.skipInstruction();) {
920     // A PhysReg copy that won't be coalesced can perhaps be rematerialized
921     // instead.
922     if (DstIsPhys) {
923       if (UseMI->isFullCopy() &&
924           UseMI->getOperand(1).getReg() == SrcReg &&
925           UseMI->getOperand(0).getReg() != SrcReg &&
926           UseMI->getOperand(0).getReg() != DstReg &&
927           !JoinedCopies.count(UseMI) &&
928           ReMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
929                                   UseMI->getOperand(0).getReg(), UseMI))
930         continue;
931     }
932
933     SmallVector<unsigned,8> Ops;
934     bool Reads, Writes;
935     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
936
937     // Replace SrcReg with DstReg in all UseMI operands.
938     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
939       MachineOperand &MO = UseMI->getOperand(Ops[i]);
940
941       // Make sure we don't create read-modify-write defs accidentally.  We
942       // assume here that a SrcReg def cannot be joined into a live DstReg.  If
943       // RegisterCoalescer starts tracking partially live registers, we will
944       // need to check the actual LiveInterval to determine if DstReg is live
945       // here.
946       if (SubIdx && !Reads)
947         MO.setIsUndef();
948
949       if (DstIsPhys)
950         MO.substPhysReg(DstReg, *TRI);
951       else
952         MO.substVirtReg(DstReg, SubIdx, *TRI);
953     }
954
955     // This instruction is a copy that will be removed.
956     if (JoinedCopies.count(UseMI))
957       continue;
958
959     DEBUG({
960         dbgs() << "\t\tupdated: ";
961         if (!UseMI->isDebugValue())
962           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
963         dbgs() << *UseMI;
964       });
965   }
966 }
967
968 /// removeIntervalIfEmpty - Check if the live interval of a physical register
969 /// is empty, if so remove it and also remove the empty intervals of its
970 /// sub-registers. Return true if live interval is removed.
971 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
972                                   const TargetRegisterInfo *TRI) {
973   if (li.empty()) {
974     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
975       for (const uint16_t* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
976         if (!LIS->hasInterval(*SR))
977           continue;
978         LiveInterval &sli = LIS->getInterval(*SR);
979         if (sli.empty())
980           LIS->removeInterval(*SR);
981       }
982     LIS->removeInterval(li.reg);
983     return true;
984   }
985   return false;
986 }
987
988 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
989 /// the val# it defines. If the live interval becomes empty, remove it as well.
990 bool RegisterCoalescer::RemoveDeadDef(LiveInterval &li,
991                                              MachineInstr *DefMI) {
992   SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
993   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
994   if (DefIdx != MLR->valno->def)
995     return false;
996   li.removeValNo(MLR->valno);
997   return removeIntervalIfEmpty(li, LIS, TRI);
998 }
999
1000 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
1001 /// We need to be careful about coalescing a source physical register with a
1002 /// virtual register. Once the coalescing is done, it cannot be broken and these
1003 /// are not spillable! If the destination interval uses are far away, think
1004 /// twice about coalescing them!
1005 bool RegisterCoalescer::shouldJoinPhys(CoalescerPair &CP) {
1006   bool Allocatable = LIS->isAllocatable(CP.getDstReg());
1007   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1008
1009   /// Always join simple intervals that are defined by a single copy from a
1010   /// reserved register. This doesn't increase register pressure, so it is
1011   /// always beneficial.
1012   if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
1013     return true;
1014
1015   if (!EnablePhysicalJoin) {
1016     DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
1017     return false;
1018   }
1019
1020   // Only coalesce to allocatable physreg, we don't want to risk modifying
1021   // reserved registers.
1022   if (!Allocatable) {
1023     DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1024     return false;  // Not coalescable.
1025   }
1026
1027   // Don't join with physregs that have a ridiculous number of live
1028   // ranges. The data structure performance is really bad when that
1029   // happens.
1030   if (LIS->hasInterval(CP.getDstReg()) &&
1031       LIS->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1032     ++numAborts;
1033     DEBUG(dbgs()
1034           << "\tPhysical register live interval too complicated, abort!\n");
1035     return false;
1036   }
1037
1038   // FIXME: Why are we skipping this test for partial copies?
1039   //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1040   if (!CP.isPartial()) {
1041     const TargetRegisterClass *RC = MRI->getRegClass(CP.getSrcReg());
1042     unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2;
1043     unsigned Length = LIS->getApproximateInstructionCount(JoinVInt);
1044     if (Length > Threshold) {
1045       ++numAborts;
1046       DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1047       return false;
1048     }
1049   }
1050   return true;
1051 }
1052
1053
1054 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1055 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1056 /// if the copy was successfully coalesced away. If it is not currently
1057 /// possible to coalesce this interval, but it may be possible if other
1058 /// things get coalesced, then it returns true by reference in 'Again'.
1059 bool RegisterCoalescer::JoinCopy(MachineInstr *CopyMI, bool &Again) {
1060
1061   Again = false;
1062   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1063     return false; // Already done.
1064
1065   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1066
1067   CoalescerPair CP(*TII, *TRI);
1068   if (!CP.setRegisters(CopyMI)) {
1069     DEBUG(dbgs() << "\tNot coalescable.\n");
1070     return false;
1071   }
1072
1073   // If they are already joined we continue.
1074   if (CP.getSrcReg() == CP.getDstReg()) {
1075     markAsJoined(CopyMI);
1076     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1077     return false;  // Not coalescable.
1078   }
1079
1080   // Eliminate undefs.
1081   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1082     markAsJoined(CopyMI);
1083     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1084     return false;  // Not coalescable.
1085   }
1086
1087   DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1088                << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSubIdx())
1089                << "\n");
1090
1091   // Enforce policies.
1092   if (CP.isPhys()) {
1093     if (!shouldJoinPhys(CP)) {
1094       // Before giving up coalescing, if definition of source is defined by
1095       // trivial computation, try rematerializing it.
1096       if (!CP.isFlipped() &&
1097           ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1098                                   CP.getDstReg(), CopyMI))
1099         return true;
1100       return false;
1101     }
1102   } else {
1103     DEBUG({
1104       if (CP.isCrossClass())
1105         dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n";
1106     });
1107
1108     // When possible, let DstReg be the larger interval.
1109     if (!CP.getSubIdx() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1110                            LIS->getInterval(CP.getDstReg()).ranges.size())
1111       CP.flip();
1112   }
1113
1114   // Okay, attempt to join these two intervals.  On failure, this returns false.
1115   // Otherwise, if one of the intervals being joined is a physreg, this method
1116   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1117   // been modified, so we can use this information below to update aliases.
1118   if (!JoinIntervals(CP)) {
1119     // Coalescing failed.
1120
1121     // If definition of source is defined by trivial computation, try
1122     // rematerializing it.
1123     if (!CP.isFlipped() &&
1124         ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1125                                 CP.getDstReg(), CopyMI))
1126       return true;
1127
1128     // If we can eliminate the copy without merging the live ranges, do so now.
1129     if (!CP.isPartial()) {
1130       if (AdjustCopiesBackFrom(CP, CopyMI) ||
1131           RemoveCopyByCommutingDef(CP, CopyMI)) {
1132         markAsJoined(CopyMI);
1133         DEBUG(dbgs() << "\tTrivial!\n");
1134         return true;
1135       }
1136     }
1137
1138     // Otherwise, we are unable to join the intervals.
1139     DEBUG(dbgs() << "\tInterference!\n");
1140     Again = true;  // May be possible to coalesce later.
1141     return false;
1142   }
1143
1144   // Coalescing to a virtual register that is of a sub-register class of the
1145   // other. Make sure the resulting register is set to the right register class.
1146   if (CP.isCrossClass()) {
1147     ++numCrossRCs;
1148     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1149   }
1150
1151   // Remember to delete the copy instruction.
1152   markAsJoined(CopyMI);
1153
1154   UpdateRegDefsUses(CP);
1155
1156   // If we have extended the live range of a physical register, make sure we
1157   // update live-in lists as well.
1158   if (CP.isPhys()) {
1159     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1160     // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1161     // ranges for this, and they are preserved.
1162     LiveInterval &SrcInt = LIS->getInterval(CP.getSrcReg());
1163     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1164          I != E; ++I ) {
1165       LIS->findLiveInMBBs(I->start, I->end, BlockSeq);
1166       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1167         MachineBasicBlock &block = *BlockSeq[idx];
1168         if (!block.isLiveIn(CP.getDstReg()))
1169           block.addLiveIn(CP.getDstReg());
1170       }
1171       BlockSeq.clear();
1172     }
1173   }
1174
1175   // SrcReg is guaranteed to be the register whose live interval that is
1176   // being merged.
1177   LIS->removeInterval(CP.getSrcReg());
1178
1179   // Update regalloc hint.
1180   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1181
1182   DEBUG({
1183     LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1184     dbgs() << "\tJoined. Result = ";
1185     DstInt.print(dbgs(), TRI);
1186     dbgs() << "\n";
1187   });
1188
1189   ++numJoins;
1190   return true;
1191 }
1192
1193 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1194 /// compute what the resultant value numbers for each value in the input two
1195 /// ranges will be.  This is complicated by copies between the two which can
1196 /// and will commonly cause multiple value numbers to be merged into one.
1197 ///
1198 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1199 /// keeps track of the new InstDefiningValue assignment for the result
1200 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1201 /// whether a value in this or other is a copy from the opposite set.
1202 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1203 /// already been assigned.
1204 ///
1205 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1206 /// contains the value number the copy is from.
1207 ///
1208 static unsigned ComputeUltimateVN(VNInfo *VNI,
1209                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1210                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1211                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1212                                   SmallVector<int, 16> &ThisValNoAssignments,
1213                                   SmallVector<int, 16> &OtherValNoAssignments) {
1214   unsigned VN = VNI->id;
1215
1216   // If the VN has already been computed, just return it.
1217   if (ThisValNoAssignments[VN] >= 0)
1218     return ThisValNoAssignments[VN];
1219   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1220
1221   // If this val is not a copy from the other val, then it must be a new value
1222   // number in the destination.
1223   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1224   if (I == ThisFromOther.end()) {
1225     NewVNInfo.push_back(VNI);
1226     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1227   }
1228   VNInfo *OtherValNo = I->second;
1229
1230   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1231   // been computed, return it.
1232   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1233     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1234
1235   // Mark this value number as currently being computed, then ask what the
1236   // ultimate value # of the other value is.
1237   ThisValNoAssignments[VN] = -2;
1238   unsigned UltimateVN =
1239     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1240                       OtherValNoAssignments, ThisValNoAssignments);
1241   return ThisValNoAssignments[VN] = UltimateVN;
1242 }
1243
1244
1245 // Find out if we have something like
1246 // A = X
1247 // B = X
1248 // if so, we can pretend this is actually
1249 // A = X
1250 // B = A
1251 // which allows us to coalesce A and B.
1252 // VNI is the definition of B. LR is the life range of A that includes
1253 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1254 // This implies that A dominates B.
1255 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1256                                           const TargetRegisterInfo &tri,
1257                                           CoalescerPair &CP,
1258                                           VNInfo *VNI,
1259                                           LiveRange *LR,
1260                                      SmallVector<MachineInstr*, 8> &DupCopies) {
1261   // FIXME: This is very conservative. For example, we don't handle
1262   // physical registers.
1263
1264   MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1265
1266   if (!MI || !MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1267     return false;
1268
1269   unsigned Dst = MI->getOperand(0).getReg();
1270   unsigned Src = MI->getOperand(1).getReg();
1271
1272   if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1273       !TargetRegisterInfo::isVirtualRegister(Dst))
1274     return false;
1275
1276   unsigned A = CP.getDstReg();
1277   unsigned B = CP.getSrcReg();
1278
1279   if (B == Dst)
1280     std::swap(A, B);
1281   assert(Dst == A);
1282
1283   VNInfo *Other = LR->valno;
1284   const MachineInstr *OtherMI = li.getInstructionFromIndex(Other->def);
1285
1286   if (!OtherMI || !OtherMI->isFullCopy())
1287     return false;
1288
1289   unsigned OtherDst = OtherMI->getOperand(0).getReg();
1290   unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1291
1292   if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1293       !TargetRegisterInfo::isVirtualRegister(OtherDst))
1294     return false;
1295
1296   assert(OtherDst == B);
1297
1298   if (Src != OtherSrc)
1299     return false;
1300
1301   // If the copies use two different value numbers of X, we cannot merge
1302   // A and B.
1303   LiveInterval &SrcInt = li.getInterval(Src);
1304   // getVNInfoBefore returns NULL for undef copies. In this case, the
1305   // optimization is still safe.
1306   if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def))
1307     return false;
1308
1309   DupCopies.push_back(MI);
1310
1311   return true;
1312 }
1313
1314 /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1315 /// returns false.
1316 bool RegisterCoalescer::JoinIntervals(CoalescerPair &CP) {
1317   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1318   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1319
1320   // If a live interval is a physical register, check for interference with any
1321   // aliases. The interference check implemented here is a bit more conservative
1322   // than the full interfeence check below. We allow overlapping live ranges
1323   // only when one is a copy of the other.
1324   if (CP.isPhys()) {
1325     // Optimization for reserved registers like ESP.
1326     // We can only merge with a reserved physreg if RHS has a single value that
1327     // is a copy of CP.DstReg().  The live range of the reserved register will
1328     // look like a set of dead defs - we don't properly track the live range of
1329     // reserved registers.
1330     if (RegClassInfo.isReserved(CP.getDstReg())) {
1331       assert(CP.isFlipped() && RHS.containsOneValue() &&
1332              "Invalid join with reserved register");
1333       // Deny any overlapping intervals.  This depends on all the reserved
1334       // register live ranges to look like dead defs.
1335       for (const uint16_t *AS = TRI->getOverlaps(CP.getDstReg()); *AS; ++AS) {
1336         if (!LIS->hasInterval(*AS)) {
1337           // Make sure at least DstReg itself exists before attempting a join.
1338           if (*AS == CP.getDstReg())
1339             LIS->getOrCreateInterval(CP.getDstReg());
1340           continue;
1341         }
1342         if (RHS.overlaps(LIS->getInterval(*AS))) {
1343           DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\n');
1344           return false;
1345         }
1346       }
1347       // Skip any value computations, we are not adding new values to the
1348       // reserved register.  Also skip merging the live ranges, the reserved
1349       // register live range doesn't need to be accurate as long as all the
1350       // defs are there.
1351       return true;
1352     }
1353
1354     // Check if a register mask clobbers DstReg.
1355     BitVector UsableRegs;
1356     if (LIS->checkRegMaskInterference(RHS, UsableRegs) &&
1357         !UsableRegs.test(CP.getDstReg())) {
1358       DEBUG(dbgs() << "\t\tRegister mask interference.\n");
1359       return false;
1360     }
1361
1362     for (const uint16_t *AS = TRI->getAliasSet(CP.getDstReg()); *AS; ++AS){
1363       if (!LIS->hasInterval(*AS))
1364         continue;
1365       const LiveInterval &LHS = LIS->getInterval(*AS);
1366       LiveInterval::const_iterator LI = LHS.begin();
1367       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1368            RI != RE; ++RI) {
1369         LI = std::lower_bound(LI, LHS.end(), RI->start);
1370         // Does LHS have an overlapping live range starting before RI?
1371         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1372             (RI->start != RI->valno->def ||
1373              !CP.isCoalescable(LIS->getInstructionFromIndex(RI->start)))) {
1374           DEBUG({
1375             dbgs() << "\t\tInterference from alias: ";
1376             LHS.print(dbgs(), TRI);
1377             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1378           });
1379           return false;
1380         }
1381
1382         // Check that LHS ranges beginning in this range are copies.
1383         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1384           if (LI->start != LI->valno->def ||
1385               !CP.isCoalescable(LIS->getInstructionFromIndex(LI->start))) {
1386             DEBUG({
1387               dbgs() << "\t\tInterference from alias: ";
1388               LHS.print(dbgs(), TRI);
1389               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1390             });
1391             return false;
1392           }
1393         }
1394       }
1395     }
1396   }
1397
1398   // Compute the final value assignment, assuming that the live ranges can be
1399   // coalesced.
1400   SmallVector<int, 16> LHSValNoAssignments;
1401   SmallVector<int, 16> RHSValNoAssignments;
1402   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1403   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1404   SmallVector<VNInfo*, 16> NewVNInfo;
1405
1406   SmallVector<MachineInstr*, 8> DupCopies;
1407
1408   LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1409   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1410
1411   // Loop over the value numbers of the LHS, seeing if any are defined from
1412   // the RHS.
1413   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1414        i != e; ++i) {
1415     VNInfo *VNI = *i;
1416     if (VNI->isUnused() || VNI->isPHIDef())
1417       continue;
1418     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1419     assert(MI && "Missing def");
1420     if (!MI->isCopyLike())  // Src not defined by a copy?
1421       continue;
1422
1423     // Figure out the value # from the RHS.
1424     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1425     // The copy could be to an aliased physreg.
1426     if (!lr) continue;
1427
1428     // DstReg is known to be a register in the LHS interval.  If the src is
1429     // from the RHS interval, we can use its value #.
1430     if (!CP.isCoalescable(MI) &&
1431         !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1432       continue;
1433
1434     LHSValsDefinedFromRHS[VNI] = lr->valno;
1435   }
1436
1437   // Loop over the value numbers of the RHS, seeing if any are defined from
1438   // the LHS.
1439   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1440        i != e; ++i) {
1441     VNInfo *VNI = *i;
1442     if (VNI->isUnused() || VNI->isPHIDef())
1443       continue;
1444     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1445     assert(MI && "Missing def");
1446     if (!MI->isCopyLike())  // Src not defined by a copy?
1447       continue;
1448
1449     // Figure out the value # from the LHS.
1450     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1451     // The copy could be to an aliased physreg.
1452     if (!lr) continue;
1453
1454     // DstReg is known to be a register in the RHS interval.  If the src is
1455     // from the LHS interval, we can use its value #.
1456     if (!CP.isCoalescable(MI) &&
1457         !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1458         continue;
1459
1460     RHSValsDefinedFromLHS[VNI] = lr->valno;
1461   }
1462
1463   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1464   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1465   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1466
1467   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1468        i != e; ++i) {
1469     VNInfo *VNI = *i;
1470     unsigned VN = VNI->id;
1471     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1472       continue;
1473     ComputeUltimateVN(VNI, NewVNInfo,
1474                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1475                       LHSValNoAssignments, RHSValNoAssignments);
1476   }
1477   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1478        i != e; ++i) {
1479     VNInfo *VNI = *i;
1480     unsigned VN = VNI->id;
1481     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1482       continue;
1483     // If this value number isn't a copy from the LHS, it's a new number.
1484     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1485       NewVNInfo.push_back(VNI);
1486       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1487       continue;
1488     }
1489
1490     ComputeUltimateVN(VNI, NewVNInfo,
1491                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1492                       RHSValNoAssignments, LHSValNoAssignments);
1493   }
1494
1495   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1496   // interval lists to see if these intervals are coalescable.
1497   LiveInterval::const_iterator I = LHS.begin();
1498   LiveInterval::const_iterator IE = LHS.end();
1499   LiveInterval::const_iterator J = RHS.begin();
1500   LiveInterval::const_iterator JE = RHS.end();
1501
1502   // Skip ahead until the first place of potential sharing.
1503   if (I != IE && J != JE) {
1504     if (I->start < J->start) {
1505       I = std::upper_bound(I, IE, J->start);
1506       if (I != LHS.begin()) --I;
1507     } else if (J->start < I->start) {
1508       J = std::upper_bound(J, JE, I->start);
1509       if (J != RHS.begin()) --J;
1510     }
1511   }
1512
1513   while (I != IE && J != JE) {
1514     // Determine if these two live ranges overlap.
1515     bool Overlaps;
1516     if (I->start < J->start) {
1517       Overlaps = I->end > J->start;
1518     } else {
1519       Overlaps = J->end > I->start;
1520     }
1521
1522     // If so, check value # info to determine if they are really different.
1523     if (Overlaps) {
1524       // If the live range overlap will map to the same value number in the
1525       // result liverange, we can still coalesce them.  If not, we can't.
1526       if (LHSValNoAssignments[I->valno->id] !=
1527           RHSValNoAssignments[J->valno->id])
1528         return false;
1529     }
1530
1531     if (I->end < J->end)
1532       ++I;
1533     else
1534       ++J;
1535   }
1536
1537   // Update kill info. Some live ranges are extended due to copy coalescing.
1538   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1539          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1540     VNInfo *VNI = I->first;
1541     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1542     if (VNI->hasPHIKill())
1543       NewVNInfo[LHSValID]->setHasPHIKill(true);
1544   }
1545
1546   // Update kill info. Some live ranges are extended due to copy coalescing.
1547   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1548          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1549     VNInfo *VNI = I->first;
1550     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1551     if (VNI->hasPHIKill())
1552       NewVNInfo[RHSValID]->setHasPHIKill(true);
1553   }
1554
1555   if (LHSValNoAssignments.empty())
1556     LHSValNoAssignments.push_back(-1);
1557   if (RHSValNoAssignments.empty())
1558     RHSValNoAssignments.push_back(-1);
1559
1560   SmallVector<unsigned, 8> SourceRegisters;
1561   for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1562          E = DupCopies.end(); I != E; ++I) {
1563     MachineInstr *MI = *I;
1564
1565     // We have pretended that the assignment to B in
1566     // A = X
1567     // B = X
1568     // was actually a copy from A. Now that we decided to coalesce A and B,
1569     // transform the code into
1570     // A = X
1571     // X = X
1572     // and mark the X as coalesced to keep the illusion.
1573     unsigned Src = MI->getOperand(1).getReg();
1574     SourceRegisters.push_back(Src);
1575     MI->getOperand(0).substVirtReg(Src, 0, *TRI);
1576
1577     markAsJoined(MI);
1578   }
1579
1580   // If B = X was the last use of X in a liverange, we have to shrink it now
1581   // that B = X is gone.
1582   for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1583          E = SourceRegisters.end(); I != E; ++I) {
1584     LIS->shrinkToUses(&LIS->getInterval(*I));
1585   }
1586
1587   // If we get here, we know that we can coalesce the live ranges.  Ask the
1588   // intervals to coalesce themselves now.
1589   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1590            MRI);
1591   return true;
1592 }
1593
1594 namespace {
1595   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1596   // depth of the basic block (the unsigned), and then on the MBB number.
1597   struct DepthMBBCompare {
1598     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1599     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1600       // Deeper loops first
1601       if (LHS.first != RHS.first)
1602         return LHS.first > RHS.first;
1603
1604       // Prefer blocks that are more connected in the CFG. This takes care of
1605       // the most difficult copies first while intervals are short.
1606       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1607       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1608       if (cl != cr)
1609         return cl > cr;
1610
1611       // As a last resort, sort by block number.
1612       return LHS.second->getNumber() < RHS.second->getNumber();
1613     }
1614   };
1615 }
1616
1617 void RegisterCoalescer::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1618                                             std::vector<MachineInstr*> &TryAgain) {
1619   DEBUG(dbgs() << MBB->getName() << ":\n");
1620
1621   SmallVector<MachineInstr*, 8> VirtCopies;
1622   SmallVector<MachineInstr*, 8> PhysCopies;
1623   SmallVector<MachineInstr*, 8> ImpDefCopies;
1624   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1625        MII != E;) {
1626     MachineInstr *Inst = MII++;
1627
1628     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1629     unsigned SrcReg, DstReg;
1630     if (Inst->isCopy()) {
1631       DstReg = Inst->getOperand(0).getReg();
1632       SrcReg = Inst->getOperand(1).getReg();
1633     } else if (Inst->isSubregToReg()) {
1634       DstReg = Inst->getOperand(0).getReg();
1635       SrcReg = Inst->getOperand(2).getReg();
1636     } else
1637       continue;
1638
1639     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1640     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1641     if (LIS->hasInterval(SrcReg) && LIS->getInterval(SrcReg).empty())
1642       ImpDefCopies.push_back(Inst);
1643     else if (SrcIsPhys || DstIsPhys)
1644       PhysCopies.push_back(Inst);
1645     else
1646       VirtCopies.push_back(Inst);
1647   }
1648
1649   // Try coalescing implicit copies and insert_subreg <undef> first,
1650   // followed by copies to / from physical registers, then finally copies
1651   // from virtual registers to virtual registers.
1652   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1653     MachineInstr *TheCopy = ImpDefCopies[i];
1654     bool Again = false;
1655     if (!JoinCopy(TheCopy, Again))
1656       if (Again)
1657         TryAgain.push_back(TheCopy);
1658   }
1659   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1660     MachineInstr *TheCopy = PhysCopies[i];
1661     bool Again = false;
1662     if (!JoinCopy(TheCopy, Again))
1663       if (Again)
1664         TryAgain.push_back(TheCopy);
1665   }
1666   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1667     MachineInstr *TheCopy = VirtCopies[i];
1668     bool Again = false;
1669     if (!JoinCopy(TheCopy, Again))
1670       if (Again)
1671         TryAgain.push_back(TheCopy);
1672   }
1673 }
1674
1675 void RegisterCoalescer::joinIntervals() {
1676   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1677
1678   std::vector<MachineInstr*> TryAgainList;
1679   if (Loops->empty()) {
1680     // If there are no loops in the function, join intervals in function order.
1681     for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1682          I != E; ++I)
1683       CopyCoalesceInMBB(I, TryAgainList);
1684   } else {
1685     // Otherwise, join intervals in inner loops before other intervals.
1686     // Unfortunately we can't just iterate over loop hierarchy here because
1687     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1688
1689     // Join intervals in the function prolog first. We want to join physical
1690     // registers with virtual registers before the intervals got too long.
1691     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1692     for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1693       MachineBasicBlock *MBB = I;
1694       MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1695     }
1696
1697     // Sort by loop depth.
1698     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1699
1700     // Finally, join intervals in loop nest order.
1701     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1702       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1703   }
1704
1705   // Joining intervals can allow other intervals to be joined.  Iteratively join
1706   // until we make no progress.
1707   bool ProgressMade = true;
1708   while (ProgressMade) {
1709     ProgressMade = false;
1710
1711     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1712       MachineInstr *&TheCopy = TryAgainList[i];
1713       if (!TheCopy)
1714         continue;
1715
1716       bool Again = false;
1717       bool Success = JoinCopy(TheCopy, Again);
1718       if (Success || !Again) {
1719         TheCopy= 0;   // Mark this one as done.
1720         ProgressMade = true;
1721       }
1722     }
1723   }
1724 }
1725
1726 void RegisterCoalescer::releaseMemory() {
1727   JoinedCopies.clear();
1728   ReMatCopies.clear();
1729   ReMatDefs.clear();
1730 }
1731
1732 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1733   MF = &fn;
1734   MRI = &fn.getRegInfo();
1735   TM = &fn.getTarget();
1736   TRI = TM->getRegisterInfo();
1737   TII = TM->getInstrInfo();
1738   LIS = &getAnalysis<LiveIntervals>();
1739   LDV = &getAnalysis<LiveDebugVariables>();
1740   AA = &getAnalysis<AliasAnalysis>();
1741   Loops = &getAnalysis<MachineLoopInfo>();
1742
1743   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1744                << "********** Function: "
1745                << ((Value*)MF->getFunction())->getName() << '\n');
1746
1747   if (VerifyCoalescing)
1748     MF->verify(this, "Before register coalescing");
1749
1750   RegClassInfo.runOnMachineFunction(fn);
1751
1752   // Join (coalesce) intervals if requested.
1753   if (EnableJoining) {
1754     joinIntervals();
1755     DEBUG({
1756         dbgs() << "********** INTERVALS POST JOINING **********\n";
1757         for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1758              I != E; ++I){
1759           I->second->print(dbgs(), TRI);
1760           dbgs() << "\n";
1761         }
1762       });
1763   }
1764
1765   // Perform a final pass over the instructions and compute spill weights
1766   // and remove identity moves.
1767   SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1768   for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1769        mbbi != mbbe; ++mbbi) {
1770     MachineBasicBlock* mbb = mbbi;
1771     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1772          mii != mie; ) {
1773       MachineInstr *MI = mii;
1774       if (JoinedCopies.count(MI)) {
1775         // Delete all coalesced copies.
1776         bool DoDelete = true;
1777         assert(MI->isCopyLike() && "Unrecognized copy instruction");
1778         unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1779         unsigned DstReg = MI->getOperand(0).getReg();
1780
1781         // Collect candidates for register class inflation.
1782         if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1783             RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1784           InflateRegs.push_back(SrcReg);
1785         if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1786             RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1787           InflateRegs.push_back(DstReg);
1788
1789         if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1790             MI->getNumOperands() > 2)
1791           // Do not delete extract_subreg, insert_subreg of physical
1792           // registers unless the definition is dead. e.g.
1793           // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1794           // or else the scavenger may complain. LowerSubregs will
1795           // delete them later.
1796           DoDelete = false;
1797
1798         if (MI->allDefsAreDead()) {
1799           if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1800               LIS->hasInterval(SrcReg))
1801             LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1802           DoDelete = true;
1803         }
1804         if (!DoDelete) {
1805           // We need the instruction to adjust liveness, so make it a KILL.
1806           if (MI->isSubregToReg()) {
1807             MI->RemoveOperand(3);
1808             MI->RemoveOperand(1);
1809           }
1810           MI->setDesc(TII->get(TargetOpcode::KILL));
1811           mii = llvm::next(mii);
1812         } else {
1813           LIS->RemoveMachineInstrFromMaps(MI);
1814           mii = mbbi->erase(mii);
1815           ++numPeep;
1816         }
1817         continue;
1818       }
1819
1820       // Now check if this is a remat'ed def instruction which is now dead.
1821       if (ReMatDefs.count(MI)) {
1822         bool isDead = true;
1823         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1824           const MachineOperand &MO = MI->getOperand(i);
1825           if (!MO.isReg())
1826             continue;
1827           unsigned Reg = MO.getReg();
1828           if (!Reg)
1829             continue;
1830           DeadDefs.push_back(Reg);
1831           if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1832             // Remat may also enable register class inflation.
1833             if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1834               InflateRegs.push_back(Reg);
1835           }
1836           if (MO.isDead())
1837             continue;
1838           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1839               !MRI->use_nodbg_empty(Reg)) {
1840             isDead = false;
1841             break;
1842           }
1843         }
1844         if (isDead) {
1845           while (!DeadDefs.empty()) {
1846             unsigned DeadDef = DeadDefs.back();
1847             DeadDefs.pop_back();
1848             RemoveDeadDef(LIS->getInterval(DeadDef), MI);
1849           }
1850           LIS->RemoveMachineInstrFromMaps(mii);
1851           mii = mbbi->erase(mii);
1852           continue;
1853         } else
1854           DeadDefs.clear();
1855       }
1856
1857       ++mii;
1858
1859       // Check for now unnecessary kill flags.
1860       if (LIS->isNotInMIMap(MI)) continue;
1861       SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1862       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1863         MachineOperand &MO = MI->getOperand(i);
1864         if (!MO.isReg() || !MO.isKill()) continue;
1865         unsigned reg = MO.getReg();
1866         if (!reg || !LIS->hasInterval(reg)) continue;
1867         if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1868           MO.setIsKill(false);
1869           continue;
1870         }
1871         // When leaving a kill flag on a physreg, check if any subregs should
1872         // remain alive.
1873         if (!TargetRegisterInfo::isPhysicalRegister(reg))
1874           continue;
1875         for (const uint16_t *SR = TRI->getSubRegisters(reg);
1876              unsigned S = *SR; ++SR)
1877           if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1878             MI->addRegisterDefined(S, TRI);
1879       }
1880     }
1881   }
1882
1883   // After deleting a lot of copies, register classes may be less constrained.
1884   // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1885   // DPR inflation.
1886   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1887   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1888                     InflateRegs.end());
1889   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1890   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1891     unsigned Reg = InflateRegs[i];
1892     if (MRI->reg_nodbg_empty(Reg))
1893       continue;
1894     if (MRI->recomputeRegClass(Reg, *TM)) {
1895       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1896                    << MRI->getRegClass(Reg)->getName() << '\n');
1897       ++NumInflated;
1898     }
1899   }
1900
1901   DEBUG(dump());
1902   DEBUG(LDV->dump());
1903   if (VerifyCoalescing)
1904     MF->verify(this, "After register coalescing");
1905   return true;
1906 }
1907
1908 /// print - Implement the dump method.
1909 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
1910    LIS->print(O, m);
1911 }