Naming convention and whitespace. No functional change.
[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     /// joinAllIntervals - join compatible live intervals
101     void joinAllIntervals();
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 RegisterCoalescer::updateRegDefsUses(const CoalescerPair &CP) {
909   bool DstIsPhys = CP.isPhys();
910   unsigned SrcReg = CP.getSrcReg();
911   unsigned DstReg = CP.getDstReg();
912   unsigned SubIdx = CP.getSubIdx();
913
914   // Update LiveDebugVariables.
915   LDV->renameRegister(SrcReg, DstReg, SubIdx);
916
917   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
918        MachineInstr *UseMI = I.skipInstruction();) {
919     // A PhysReg copy that won't be coalesced can perhaps be rematerialized
920     // instead.
921     if (DstIsPhys) {
922       if (UseMI->isFullCopy() &&
923           UseMI->getOperand(1).getReg() == SrcReg &&
924           UseMI->getOperand(0).getReg() != SrcReg &&
925           UseMI->getOperand(0).getReg() != DstReg &&
926           !JoinedCopies.count(UseMI) &&
927           reMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
928                                   UseMI->getOperand(0).getReg(), UseMI))
929         continue;
930     }
931
932     SmallVector<unsigned,8> Ops;
933     bool Reads, Writes;
934     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
935
936     // Replace SrcReg with DstReg in all UseMI operands.
937     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
938       MachineOperand &MO = UseMI->getOperand(Ops[i]);
939
940       // Make sure we don't create read-modify-write defs accidentally.  We
941       // assume here that a SrcReg def cannot be joined into a live DstReg.  If
942       // RegisterCoalescer starts tracking partially live registers, we will
943       // need to check the actual LiveInterval to determine if DstReg is live
944       // here.
945       if (SubIdx && !Reads)
946         MO.setIsUndef();
947
948       if (DstIsPhys)
949         MO.substPhysReg(DstReg, *TRI);
950       else
951         MO.substVirtReg(DstReg, SubIdx, *TRI);
952     }
953
954     // This instruction is a copy that will be removed.
955     if (JoinedCopies.count(UseMI))
956       continue;
957
958     DEBUG({
959         dbgs() << "\t\tupdated: ";
960         if (!UseMI->isDebugValue())
961           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
962         dbgs() << *UseMI;
963       });
964   }
965 }
966
967 /// removeIntervalIfEmpty - Check if the live interval of a physical register
968 /// is empty, if so remove it and also remove the empty intervals of its
969 /// sub-registers. Return true if live interval is removed.
970 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
971                                   const TargetRegisterInfo *TRI) {
972   if (li.empty()) {
973     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
974       for (const uint16_t* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
975         if (!LIS->hasInterval(*SR))
976           continue;
977         LiveInterval &sli = LIS->getInterval(*SR);
978         if (sli.empty())
979           LIS->removeInterval(*SR);
980       }
981     LIS->removeInterval(li.reg);
982     return true;
983   }
984   return false;
985 }
986
987 /// removeDeadDef - If a def of a live interval is now determined dead, remove
988 /// the val# it defines. If the live interval becomes empty, remove it as well.
989 bool RegisterCoalescer::removeDeadDef(LiveInterval &li, MachineInstr *DefMI) {
990   SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
991   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
992   if (DefIdx != MLR->valno->def)
993     return false;
994   li.removeValNo(MLR->valno);
995   return removeIntervalIfEmpty(li, LIS, TRI);
996 }
997
998 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
999 /// We need to be careful about coalescing a source physical register with a
1000 /// virtual register. Once the coalescing is done, it cannot be broken and these
1001 /// are not spillable! If the destination interval uses are far away, think
1002 /// twice about coalescing them!
1003 bool RegisterCoalescer::shouldJoinPhys(CoalescerPair &CP) {
1004   bool Allocatable = LIS->isAllocatable(CP.getDstReg());
1005   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1006
1007   /// Always join simple intervals that are defined by a single copy from a
1008   /// reserved register. This doesn't increase register pressure, so it is
1009   /// always beneficial.
1010   if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
1011     return true;
1012
1013   if (!EnablePhysicalJoin) {
1014     DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
1015     return false;
1016   }
1017
1018   // Only coalesce to allocatable physreg, we don't want to risk modifying
1019   // reserved registers.
1020   if (!Allocatable) {
1021     DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1022     return false;  // Not coalescable.
1023   }
1024
1025   // Don't join with physregs that have a ridiculous number of live
1026   // ranges. The data structure performance is really bad when that
1027   // happens.
1028   if (LIS->hasInterval(CP.getDstReg()) &&
1029       LIS->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1030     ++numAborts;
1031     DEBUG(dbgs()
1032           << "\tPhysical register live interval too complicated, abort!\n");
1033     return false;
1034   }
1035
1036   // FIXME: Why are we skipping this test for partial copies?
1037   //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1038   if (!CP.isPartial()) {
1039     const TargetRegisterClass *RC = MRI->getRegClass(CP.getSrcReg());
1040     unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2;
1041     unsigned Length = LIS->getApproximateInstructionCount(JoinVInt);
1042     if (Length > Threshold) {
1043       ++numAborts;
1044       DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1045       return false;
1046     }
1047   }
1048   return true;
1049 }
1050
1051
1052 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1053 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1054 /// if the copy was successfully coalesced away. If it is not currently
1055 /// possible to coalesce this interval, but it may be possible if other
1056 /// things get coalesced, then it returns true by reference in 'Again'.
1057 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1058
1059   Again = false;
1060   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1061     return false; // Already done.
1062
1063   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1064
1065   CoalescerPair CP(*TII, *TRI);
1066   if (!CP.setRegisters(CopyMI)) {
1067     DEBUG(dbgs() << "\tNot coalescable.\n");
1068     return false;
1069   }
1070
1071   // If they are already joined we continue.
1072   if (CP.getSrcReg() == CP.getDstReg()) {
1073     markAsJoined(CopyMI);
1074     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1075     return false;  // Not coalescable.
1076   }
1077
1078   // Eliminate undefs.
1079   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1080     markAsJoined(CopyMI);
1081     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1082     return false;  // Not coalescable.
1083   }
1084
1085   DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1086                << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSubIdx())
1087                << "\n");
1088
1089   // Enforce policies.
1090   if (CP.isPhys()) {
1091     if (!shouldJoinPhys(CP)) {
1092       // Before giving up coalescing, if definition of source is defined by
1093       // trivial computation, try rematerializing it.
1094       if (!CP.isFlipped() &&
1095           reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1096                                   CP.getDstReg(), CopyMI))
1097         return true;
1098       return false;
1099     }
1100   } else {
1101     DEBUG({
1102       if (CP.isCrossClass())
1103         dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n";
1104     });
1105
1106     // When possible, let DstReg be the larger interval.
1107     if (!CP.getSubIdx() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1108                            LIS->getInterval(CP.getDstReg()).ranges.size())
1109       CP.flip();
1110   }
1111
1112   // Okay, attempt to join these two intervals.  On failure, this returns false.
1113   // Otherwise, if one of the intervals being joined is a physreg, this method
1114   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1115   // been modified, so we can use this information below to update aliases.
1116   if (!joinIntervals(CP)) {
1117     // Coalescing failed.
1118
1119     // If definition of source is defined by trivial computation, try
1120     // rematerializing it.
1121     if (!CP.isFlipped() &&
1122         reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1123                                 CP.getDstReg(), CopyMI))
1124       return true;
1125
1126     // If we can eliminate the copy without merging the live ranges, do so now.
1127     if (!CP.isPartial()) {
1128       if (adjustCopiesBackFrom(CP, CopyMI) ||
1129           removeCopyByCommutingDef(CP, CopyMI)) {
1130         markAsJoined(CopyMI);
1131         DEBUG(dbgs() << "\tTrivial!\n");
1132         return true;
1133       }
1134     }
1135
1136     // Otherwise, we are unable to join the intervals.
1137     DEBUG(dbgs() << "\tInterference!\n");
1138     Again = true;  // May be possible to coalesce later.
1139     return false;
1140   }
1141
1142   // Coalescing to a virtual register that is of a sub-register class of the
1143   // other. Make sure the resulting register is set to the right register class.
1144   if (CP.isCrossClass()) {
1145     ++numCrossRCs;
1146     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1147   }
1148
1149   // Remember to delete the copy instruction.
1150   markAsJoined(CopyMI);
1151
1152   updateRegDefsUses(CP);
1153
1154   // If we have extended the live range of a physical register, make sure we
1155   // update live-in lists as well.
1156   if (CP.isPhys()) {
1157     SmallVector<MachineBasicBlock*, 16> BlockSeq;
1158     // joinIntervals invalidates the VNInfos in SrcInt, but we only need the
1159     // ranges for this, and they are preserved.
1160     LiveInterval &SrcInt = LIS->getInterval(CP.getSrcReg());
1161     for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1162          I != E; ++I ) {
1163       LIS->findLiveInMBBs(I->start, I->end, BlockSeq);
1164       for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1165         MachineBasicBlock &block = *BlockSeq[idx];
1166         if (!block.isLiveIn(CP.getDstReg()))
1167           block.addLiveIn(CP.getDstReg());
1168       }
1169       BlockSeq.clear();
1170     }
1171   }
1172
1173   // SrcReg is guaranteed to be the register whose live interval that is
1174   // being merged.
1175   LIS->removeInterval(CP.getSrcReg());
1176
1177   // Update regalloc hint.
1178   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1179
1180   DEBUG({
1181     LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1182     dbgs() << "\tJoined. Result = ";
1183     DstInt.print(dbgs(), TRI);
1184     dbgs() << "\n";
1185   });
1186
1187   ++numJoins;
1188   return true;
1189 }
1190
1191 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1192 /// compute what the resultant value numbers for each value in the input two
1193 /// ranges will be.  This is complicated by copies between the two which can
1194 /// and will commonly cause multiple value numbers to be merged into one.
1195 ///
1196 /// VN is the value number that we're trying to resolve.  InstDefiningValue
1197 /// keeps track of the new InstDefiningValue assignment for the result
1198 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1199 /// whether a value in this or other is a copy from the opposite set.
1200 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1201 /// already been assigned.
1202 ///
1203 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1204 /// contains the value number the copy is from.
1205 ///
1206 static unsigned ComputeUltimateVN(VNInfo *VNI,
1207                                   SmallVector<VNInfo*, 16> &NewVNInfo,
1208                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1209                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1210                                   SmallVector<int, 16> &ThisValNoAssignments,
1211                                   SmallVector<int, 16> &OtherValNoAssignments) {
1212   unsigned VN = VNI->id;
1213
1214   // If the VN has already been computed, just return it.
1215   if (ThisValNoAssignments[VN] >= 0)
1216     return ThisValNoAssignments[VN];
1217   assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1218
1219   // If this val is not a copy from the other val, then it must be a new value
1220   // number in the destination.
1221   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1222   if (I == ThisFromOther.end()) {
1223     NewVNInfo.push_back(VNI);
1224     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1225   }
1226   VNInfo *OtherValNo = I->second;
1227
1228   // Otherwise, this *is* a copy from the RHS.  If the other side has already
1229   // been computed, return it.
1230   if (OtherValNoAssignments[OtherValNo->id] >= 0)
1231     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1232
1233   // Mark this value number as currently being computed, then ask what the
1234   // ultimate value # of the other value is.
1235   ThisValNoAssignments[VN] = -2;
1236   unsigned UltimateVN =
1237     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1238                       OtherValNoAssignments, ThisValNoAssignments);
1239   return ThisValNoAssignments[VN] = UltimateVN;
1240 }
1241
1242
1243 // Find out if we have something like
1244 // A = X
1245 // B = X
1246 // if so, we can pretend this is actually
1247 // A = X
1248 // B = A
1249 // which allows us to coalesce A and B.
1250 // VNI is the definition of B. LR is the life range of A that includes
1251 // the slot just before B. If we return true, we add "B = X" to DupCopies.
1252 // This implies that A dominates B.
1253 static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1254                                           const TargetRegisterInfo &tri,
1255                                           CoalescerPair &CP,
1256                                           VNInfo *VNI,
1257                                           LiveRange *LR,
1258                                      SmallVector<MachineInstr*, 8> &DupCopies) {
1259   // FIXME: This is very conservative. For example, we don't handle
1260   // physical registers.
1261
1262   MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1263
1264   if (!MI || !MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1265     return false;
1266
1267   unsigned Dst = MI->getOperand(0).getReg();
1268   unsigned Src = MI->getOperand(1).getReg();
1269
1270   if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1271       !TargetRegisterInfo::isVirtualRegister(Dst))
1272     return false;
1273
1274   unsigned A = CP.getDstReg();
1275   unsigned B = CP.getSrcReg();
1276
1277   if (B == Dst)
1278     std::swap(A, B);
1279   assert(Dst == A);
1280
1281   VNInfo *Other = LR->valno;
1282   const MachineInstr *OtherMI = li.getInstructionFromIndex(Other->def);
1283
1284   if (!OtherMI || !OtherMI->isFullCopy())
1285     return false;
1286
1287   unsigned OtherDst = OtherMI->getOperand(0).getReg();
1288   unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1289
1290   if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1291       !TargetRegisterInfo::isVirtualRegister(OtherDst))
1292     return false;
1293
1294   assert(OtherDst == B);
1295
1296   if (Src != OtherSrc)
1297     return false;
1298
1299   // If the copies use two different value numbers of X, we cannot merge
1300   // A and B.
1301   LiveInterval &SrcInt = li.getInterval(Src);
1302   // getVNInfoBefore returns NULL for undef copies. In this case, the
1303   // optimization is still safe.
1304   if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def))
1305     return false;
1306
1307   DupCopies.push_back(MI);
1308
1309   return true;
1310 }
1311
1312 /// joinIntervals - Attempt to join these two intervals.  On failure, this
1313 /// returns false.
1314 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1315   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1316   DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1317
1318   // If a live interval is a physical register, check for interference with any
1319   // aliases. The interference check implemented here is a bit more conservative
1320   // than the full interfeence check below. We allow overlapping live ranges
1321   // only when one is a copy of the other.
1322   if (CP.isPhys()) {
1323     // Optimization for reserved registers like ESP.
1324     // We can only merge with a reserved physreg if RHS has a single value that
1325     // is a copy of CP.DstReg().  The live range of the reserved register will
1326     // look like a set of dead defs - we don't properly track the live range of
1327     // reserved registers.
1328     if (RegClassInfo.isReserved(CP.getDstReg())) {
1329       assert(CP.isFlipped() && RHS.containsOneValue() &&
1330              "Invalid join with reserved register");
1331       // Deny any overlapping intervals.  This depends on all the reserved
1332       // register live ranges to look like dead defs.
1333       for (const uint16_t *AS = TRI->getOverlaps(CP.getDstReg()); *AS; ++AS) {
1334         if (!LIS->hasInterval(*AS)) {
1335           // Make sure at least DstReg itself exists before attempting a join.
1336           if (*AS == CP.getDstReg())
1337             LIS->getOrCreateInterval(CP.getDstReg());
1338           continue;
1339         }
1340         if (RHS.overlaps(LIS->getInterval(*AS))) {
1341           DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\n');
1342           return false;
1343         }
1344       }
1345       // Skip any value computations, we are not adding new values to the
1346       // reserved register.  Also skip merging the live ranges, the reserved
1347       // register live range doesn't need to be accurate as long as all the
1348       // defs are there.
1349       return true;
1350     }
1351
1352     // Check if a register mask clobbers DstReg.
1353     BitVector UsableRegs;
1354     if (LIS->checkRegMaskInterference(RHS, UsableRegs) &&
1355         !UsableRegs.test(CP.getDstReg())) {
1356       DEBUG(dbgs() << "\t\tRegister mask interference.\n");
1357       return false;
1358     }
1359
1360     for (const uint16_t *AS = TRI->getAliasSet(CP.getDstReg()); *AS; ++AS){
1361       if (!LIS->hasInterval(*AS))
1362         continue;
1363       const LiveInterval &LHS = LIS->getInterval(*AS);
1364       LiveInterval::const_iterator LI = LHS.begin();
1365       for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1366            RI != RE; ++RI) {
1367         LI = std::lower_bound(LI, LHS.end(), RI->start);
1368         // Does LHS have an overlapping live range starting before RI?
1369         if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1370             (RI->start != RI->valno->def ||
1371              !CP.isCoalescable(LIS->getInstructionFromIndex(RI->start)))) {
1372           DEBUG({
1373             dbgs() << "\t\tInterference from alias: ";
1374             LHS.print(dbgs(), TRI);
1375             dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1376           });
1377           return false;
1378         }
1379
1380         // Check that LHS ranges beginning in this range are copies.
1381         for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1382           if (LI->start != LI->valno->def ||
1383               !CP.isCoalescable(LIS->getInstructionFromIndex(LI->start))) {
1384             DEBUG({
1385               dbgs() << "\t\tInterference from alias: ";
1386               LHS.print(dbgs(), TRI);
1387               dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1388             });
1389             return false;
1390           }
1391         }
1392       }
1393     }
1394   }
1395
1396   // Compute the final value assignment, assuming that the live ranges can be
1397   // coalesced.
1398   SmallVector<int, 16> LHSValNoAssignments;
1399   SmallVector<int, 16> RHSValNoAssignments;
1400   DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1401   DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1402   SmallVector<VNInfo*, 16> NewVNInfo;
1403
1404   SmallVector<MachineInstr*, 8> DupCopies;
1405
1406   LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1407   DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1408
1409   // Loop over the value numbers of the LHS, seeing if any are defined from
1410   // the RHS.
1411   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1412        i != e; ++i) {
1413     VNInfo *VNI = *i;
1414     if (VNI->isUnused() || VNI->isPHIDef())
1415       continue;
1416     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1417     assert(MI && "Missing def");
1418     if (!MI->isCopyLike())  // Src not defined by a copy?
1419       continue;
1420
1421     // Figure out the value # from the RHS.
1422     LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1423     // The copy could be to an aliased physreg.
1424     if (!lr) continue;
1425
1426     // DstReg is known to be a register in the LHS interval.  If the src is
1427     // from the RHS interval, we can use its value #.
1428     if (!CP.isCoalescable(MI) &&
1429         !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1430       continue;
1431
1432     LHSValsDefinedFromRHS[VNI] = lr->valno;
1433   }
1434
1435   // Loop over the value numbers of the RHS, seeing if any are defined from
1436   // the LHS.
1437   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1438        i != e; ++i) {
1439     VNInfo *VNI = *i;
1440     if (VNI->isUnused() || VNI->isPHIDef())
1441       continue;
1442     MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1443     assert(MI && "Missing def");
1444     if (!MI->isCopyLike())  // Src not defined by a copy?
1445       continue;
1446
1447     // Figure out the value # from the LHS.
1448     LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1449     // The copy could be to an aliased physreg.
1450     if (!lr) continue;
1451
1452     // DstReg is known to be a register in the RHS interval.  If the src is
1453     // from the LHS interval, we can use its value #.
1454     if (!CP.isCoalescable(MI) &&
1455         !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1456         continue;
1457
1458     RHSValsDefinedFromLHS[VNI] = lr->valno;
1459   }
1460
1461   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1462   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1463   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1464
1465   for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1466        i != e; ++i) {
1467     VNInfo *VNI = *i;
1468     unsigned VN = VNI->id;
1469     if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1470       continue;
1471     ComputeUltimateVN(VNI, NewVNInfo,
1472                       LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1473                       LHSValNoAssignments, RHSValNoAssignments);
1474   }
1475   for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1476        i != e; ++i) {
1477     VNInfo *VNI = *i;
1478     unsigned VN = VNI->id;
1479     if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1480       continue;
1481     // If this value number isn't a copy from the LHS, it's a new number.
1482     if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1483       NewVNInfo.push_back(VNI);
1484       RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1485       continue;
1486     }
1487
1488     ComputeUltimateVN(VNI, NewVNInfo,
1489                       RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1490                       RHSValNoAssignments, LHSValNoAssignments);
1491   }
1492
1493   // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1494   // interval lists to see if these intervals are coalescable.
1495   LiveInterval::const_iterator I = LHS.begin();
1496   LiveInterval::const_iterator IE = LHS.end();
1497   LiveInterval::const_iterator J = RHS.begin();
1498   LiveInterval::const_iterator JE = RHS.end();
1499
1500   // Skip ahead until the first place of potential sharing.
1501   if (I != IE && J != JE) {
1502     if (I->start < J->start) {
1503       I = std::upper_bound(I, IE, J->start);
1504       if (I != LHS.begin()) --I;
1505     } else if (J->start < I->start) {
1506       J = std::upper_bound(J, JE, I->start);
1507       if (J != RHS.begin()) --J;
1508     }
1509   }
1510
1511   while (I != IE && J != JE) {
1512     // Determine if these two live ranges overlap.
1513     bool Overlaps;
1514     if (I->start < J->start) {
1515       Overlaps = I->end > J->start;
1516     } else {
1517       Overlaps = J->end > I->start;
1518     }
1519
1520     // If so, check value # info to determine if they are really different.
1521     if (Overlaps) {
1522       // If the live range overlap will map to the same value number in the
1523       // result liverange, we can still coalesce them.  If not, we can't.
1524       if (LHSValNoAssignments[I->valno->id] !=
1525           RHSValNoAssignments[J->valno->id])
1526         return false;
1527     }
1528
1529     if (I->end < J->end)
1530       ++I;
1531     else
1532       ++J;
1533   }
1534
1535   // Update kill info. Some live ranges are extended due to copy coalescing.
1536   for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1537          E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1538     VNInfo *VNI = I->first;
1539     unsigned LHSValID = LHSValNoAssignments[VNI->id];
1540     if (VNI->hasPHIKill())
1541       NewVNInfo[LHSValID]->setHasPHIKill(true);
1542   }
1543
1544   // Update kill info. Some live ranges are extended due to copy coalescing.
1545   for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1546          E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1547     VNInfo *VNI = I->first;
1548     unsigned RHSValID = RHSValNoAssignments[VNI->id];
1549     if (VNI->hasPHIKill())
1550       NewVNInfo[RHSValID]->setHasPHIKill(true);
1551   }
1552
1553   if (LHSValNoAssignments.empty())
1554     LHSValNoAssignments.push_back(-1);
1555   if (RHSValNoAssignments.empty())
1556     RHSValNoAssignments.push_back(-1);
1557
1558   SmallVector<unsigned, 8> SourceRegisters;
1559   for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1560          E = DupCopies.end(); I != E; ++I) {
1561     MachineInstr *MI = *I;
1562
1563     // We have pretended that the assignment to B in
1564     // A = X
1565     // B = X
1566     // was actually a copy from A. Now that we decided to coalesce A and B,
1567     // transform the code into
1568     // A = X
1569     // X = X
1570     // and mark the X as coalesced to keep the illusion.
1571     unsigned Src = MI->getOperand(1).getReg();
1572     SourceRegisters.push_back(Src);
1573     MI->getOperand(0).substVirtReg(Src, 0, *TRI);
1574
1575     markAsJoined(MI);
1576   }
1577
1578   // If B = X was the last use of X in a liverange, we have to shrink it now
1579   // that B = X is gone.
1580   for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1581          E = SourceRegisters.end(); I != E; ++I) {
1582     LIS->shrinkToUses(&LIS->getInterval(*I));
1583   }
1584
1585   // If we get here, we know that we can coalesce the live ranges.  Ask the
1586   // intervals to coalesce themselves now.
1587   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1588            MRI);
1589   return true;
1590 }
1591
1592 namespace {
1593   // DepthMBBCompare - Comparison predicate that sort first based on the loop
1594   // depth of the basic block (the unsigned), and then on the MBB number.
1595   struct DepthMBBCompare {
1596     typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1597     bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1598       // Deeper loops first
1599       if (LHS.first != RHS.first)
1600         return LHS.first > RHS.first;
1601
1602       // Prefer blocks that are more connected in the CFG. This takes care of
1603       // the most difficult copies first while intervals are short.
1604       unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1605       unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1606       if (cl != cr)
1607         return cl > cr;
1608
1609       // As a last resort, sort by block number.
1610       return LHS.second->getNumber() < RHS.second->getNumber();
1611     }
1612   };
1613 }
1614
1615 void
1616 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB,
1617                                      std::vector<MachineInstr*> &TryAgain) {
1618   DEBUG(dbgs() << MBB->getName() << ":\n");
1619
1620   SmallVector<MachineInstr*, 8> VirtCopies;
1621   SmallVector<MachineInstr*, 8> PhysCopies;
1622   SmallVector<MachineInstr*, 8> ImpDefCopies;
1623   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1624        MII != E;) {
1625     MachineInstr *Inst = MII++;
1626
1627     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1628     unsigned SrcReg, DstReg;
1629     if (Inst->isCopy()) {
1630       DstReg = Inst->getOperand(0).getReg();
1631       SrcReg = Inst->getOperand(1).getReg();
1632     } else if (Inst->isSubregToReg()) {
1633       DstReg = Inst->getOperand(0).getReg();
1634       SrcReg = Inst->getOperand(2).getReg();
1635     } else
1636       continue;
1637
1638     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1639     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1640     if (LIS->hasInterval(SrcReg) && LIS->getInterval(SrcReg).empty())
1641       ImpDefCopies.push_back(Inst);
1642     else if (SrcIsPhys || DstIsPhys)
1643       PhysCopies.push_back(Inst);
1644     else
1645       VirtCopies.push_back(Inst);
1646   }
1647
1648   // Try coalescing implicit copies and insert_subreg <undef> first,
1649   // followed by copies to / from physical registers, then finally copies
1650   // from virtual registers to virtual registers.
1651   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1652     MachineInstr *TheCopy = ImpDefCopies[i];
1653     bool Again = false;
1654     if (!joinCopy(TheCopy, Again))
1655       if (Again)
1656         TryAgain.push_back(TheCopy);
1657   }
1658   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1659     MachineInstr *TheCopy = PhysCopies[i];
1660     bool Again = false;
1661     if (!joinCopy(TheCopy, Again))
1662       if (Again)
1663         TryAgain.push_back(TheCopy);
1664   }
1665   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1666     MachineInstr *TheCopy = VirtCopies[i];
1667     bool Again = false;
1668     if (!joinCopy(TheCopy, Again))
1669       if (Again)
1670         TryAgain.push_back(TheCopy);
1671   }
1672 }
1673
1674 void RegisterCoalescer::joinAllIntervals() {
1675   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1676
1677   std::vector<MachineInstr*> TryAgainList;
1678   if (Loops->empty()) {
1679     // If there are no loops in the function, join intervals in function order.
1680     for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1681          I != E; ++I)
1682       copyCoalesceInMBB(I, TryAgainList);
1683   } else {
1684     // Otherwise, join intervals in inner loops before other intervals.
1685     // Unfortunately we can't just iterate over loop hierarchy here because
1686     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1687
1688     // Join intervals in the function prolog first. We want to join physical
1689     // registers with virtual registers before the intervals got too long.
1690     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1691     for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1692       MachineBasicBlock *MBB = I;
1693       MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1694     }
1695
1696     // Sort by loop depth.
1697     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1698
1699     // Finally, join intervals in loop nest order.
1700     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1701       copyCoalesceInMBB(MBBs[i].second, TryAgainList);
1702   }
1703
1704   // Joining intervals can allow other intervals to be joined.  Iteratively join
1705   // until we make no progress.
1706   bool ProgressMade = true;
1707   while (ProgressMade) {
1708     ProgressMade = false;
1709
1710     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1711       MachineInstr *&TheCopy = TryAgainList[i];
1712       if (!TheCopy)
1713         continue;
1714
1715       bool Again = false;
1716       bool Success = joinCopy(TheCopy, Again);
1717       if (Success || !Again) {
1718         TheCopy= 0;   // Mark this one as done.
1719         ProgressMade = true;
1720       }
1721     }
1722   }
1723 }
1724
1725 void RegisterCoalescer::releaseMemory() {
1726   JoinedCopies.clear();
1727   ReMatCopies.clear();
1728   ReMatDefs.clear();
1729 }
1730
1731 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1732   MF = &fn;
1733   MRI = &fn.getRegInfo();
1734   TM = &fn.getTarget();
1735   TRI = TM->getRegisterInfo();
1736   TII = TM->getInstrInfo();
1737   LIS = &getAnalysis<LiveIntervals>();
1738   LDV = &getAnalysis<LiveDebugVariables>();
1739   AA = &getAnalysis<AliasAnalysis>();
1740   Loops = &getAnalysis<MachineLoopInfo>();
1741
1742   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1743                << "********** Function: "
1744                << ((Value*)MF->getFunction())->getName() << '\n');
1745
1746   if (VerifyCoalescing)
1747     MF->verify(this, "Before register coalescing");
1748
1749   RegClassInfo.runOnMachineFunction(fn);
1750
1751   // Join (coalesce) intervals if requested.
1752   if (EnableJoining) {
1753     joinAllIntervals();
1754     DEBUG({
1755         dbgs() << "********** INTERVALS POST JOINING **********\n";
1756         for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1757              I != E; ++I){
1758           I->second->print(dbgs(), TRI);
1759           dbgs() << "\n";
1760         }
1761       });
1762   }
1763
1764   // Perform a final pass over the instructions and compute spill weights
1765   // and remove identity moves.
1766   SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1767   for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1768        mbbi != mbbe; ++mbbi) {
1769     MachineBasicBlock* mbb = mbbi;
1770     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1771          mii != mie; ) {
1772       MachineInstr *MI = mii;
1773       if (JoinedCopies.count(MI)) {
1774         // Delete all coalesced copies.
1775         bool DoDelete = true;
1776         assert(MI->isCopyLike() && "Unrecognized copy instruction");
1777         unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1778         unsigned DstReg = MI->getOperand(0).getReg();
1779
1780         // Collect candidates for register class inflation.
1781         if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1782             RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1783           InflateRegs.push_back(SrcReg);
1784         if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1785             RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1786           InflateRegs.push_back(DstReg);
1787
1788         if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1789             MI->getNumOperands() > 2)
1790           // Do not delete extract_subreg, insert_subreg of physical
1791           // registers unless the definition is dead. e.g.
1792           // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1793           // or else the scavenger may complain. LowerSubregs will
1794           // delete them later.
1795           DoDelete = false;
1796
1797         if (MI->allDefsAreDead()) {
1798           if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1799               LIS->hasInterval(SrcReg))
1800             LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1801           DoDelete = true;
1802         }
1803         if (!DoDelete) {
1804           // We need the instruction to adjust liveness, so make it a KILL.
1805           if (MI->isSubregToReg()) {
1806             MI->RemoveOperand(3);
1807             MI->RemoveOperand(1);
1808           }
1809           MI->setDesc(TII->get(TargetOpcode::KILL));
1810           mii = llvm::next(mii);
1811         } else {
1812           LIS->RemoveMachineInstrFromMaps(MI);
1813           mii = mbbi->erase(mii);
1814           ++numPeep;
1815         }
1816         continue;
1817       }
1818
1819       // Now check if this is a remat'ed def instruction which is now dead.
1820       if (ReMatDefs.count(MI)) {
1821         bool isDead = true;
1822         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1823           const MachineOperand &MO = MI->getOperand(i);
1824           if (!MO.isReg())
1825             continue;
1826           unsigned Reg = MO.getReg();
1827           if (!Reg)
1828             continue;
1829           DeadDefs.push_back(Reg);
1830           if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1831             // Remat may also enable register class inflation.
1832             if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1833               InflateRegs.push_back(Reg);
1834           }
1835           if (MO.isDead())
1836             continue;
1837           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1838               !MRI->use_nodbg_empty(Reg)) {
1839             isDead = false;
1840             break;
1841           }
1842         }
1843         if (isDead) {
1844           while (!DeadDefs.empty()) {
1845             unsigned DeadDef = DeadDefs.back();
1846             DeadDefs.pop_back();
1847             removeDeadDef(LIS->getInterval(DeadDef), MI);
1848           }
1849           LIS->RemoveMachineInstrFromMaps(mii);
1850           mii = mbbi->erase(mii);
1851           continue;
1852         } else
1853           DeadDefs.clear();
1854       }
1855
1856       ++mii;
1857
1858       // Check for now unnecessary kill flags.
1859       if (LIS->isNotInMIMap(MI)) continue;
1860       SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1861       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1862         MachineOperand &MO = MI->getOperand(i);
1863         if (!MO.isReg() || !MO.isKill()) continue;
1864         unsigned reg = MO.getReg();
1865         if (!reg || !LIS->hasInterval(reg)) continue;
1866         if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1867           MO.setIsKill(false);
1868           continue;
1869         }
1870         // When leaving a kill flag on a physreg, check if any subregs should
1871         // remain alive.
1872         if (!TargetRegisterInfo::isPhysicalRegister(reg))
1873           continue;
1874         for (const uint16_t *SR = TRI->getSubRegisters(reg);
1875              unsigned S = *SR; ++SR)
1876           if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1877             MI->addRegisterDefined(S, TRI);
1878       }
1879     }
1880   }
1881
1882   // After deleting a lot of copies, register classes may be less constrained.
1883   // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1884   // DPR inflation.
1885   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1886   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1887                     InflateRegs.end());
1888   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1889   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1890     unsigned Reg = InflateRegs[i];
1891     if (MRI->reg_nodbg_empty(Reg))
1892       continue;
1893     if (MRI->recomputeRegClass(Reg, *TM)) {
1894       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1895                    << MRI->getRegClass(Reg)->getName() << '\n');
1896       ++NumInflated;
1897     }
1898   }
1899
1900   DEBUG(dump());
1901   DEBUG(LDV->dump());
1902   if (VerifyCoalescing)
1903     MF->verify(this, "After register coalescing");
1904   return true;
1905 }
1906
1907 /// print - Implement the dump method.
1908 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
1909    LIS->print(O, m);
1910 }