Cross-class joining is winning.
[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 DisableCrossClassJoin("disable-cross-class-join",
67                cl::desc("Avoid coalescing cross register class copies"),
68                cl::init(false), cl::Hidden);
69
70 static cl::opt<bool>
71 EnablePhysicalJoin("join-physregs",
72                    cl::desc("Join physical register copies"),
73                    cl::init(false), cl::Hidden);
74
75 static cl::opt<bool>
76 VerifyCoalescing("verify-coalescing",
77          cl::desc("Verify machine instrs before and after register coalescing"),
78          cl::Hidden);
79
80 namespace {
81   class RegisterCoalescer : public MachineFunctionPass {
82     MachineFunction* MF;
83     MachineRegisterInfo* MRI;
84     const TargetMachine* TM;
85     const TargetRegisterInfo* TRI;
86     const TargetInstrInfo* TII;
87     LiveIntervals *LIS;
88     LiveDebugVariables *LDV;
89     const MachineLoopInfo* Loops;
90     AliasAnalysis *AA;
91     RegisterClassInfo RegClassInfo;
92
93     /// JoinedCopies - Keep track of copies eliminated due to coalescing.
94     ///
95     SmallPtrSet<MachineInstr*, 32> JoinedCopies;
96
97     /// ReMatCopies - Keep track of copies eliminated due to remat.
98     ///
99     SmallPtrSet<MachineInstr*, 32> ReMatCopies;
100
101     /// ReMatDefs - Keep track of definition instructions which have
102     /// been remat'ed.
103     SmallPtrSet<MachineInstr*, 8> ReMatDefs;
104
105     /// joinIntervals - join compatible live intervals
106     void joinIntervals();
107
108     /// CopyCoalesceInMBB - Coalesce copies in the specified MBB, putting
109     /// copies that cannot yet be coalesced into the "TryAgain" list.
110     void CopyCoalesceInMBB(MachineBasicBlock *MBB,
111                            std::vector<MachineInstr*> &TryAgain);
112
113     /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
114     /// which are the src/dst of the copy instruction CopyMI.  This returns
115     /// true if the copy was successfully coalesced away. If it is not
116     /// currently possible to coalesce this interval, but it may be possible if
117     /// other things get coalesced, then it returns true by reference in
118     /// 'Again'.
119     bool JoinCopy(MachineInstr *TheCopy, bool &Again);
120
121     /// JoinIntervals - Attempt to join these two intervals.  On failure, this
122     /// returns false.  The output "SrcInt" will not have been modified, so we
123     /// can use this information below to update aliases.
124     bool JoinIntervals(CoalescerPair &CP);
125
126     /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
127     /// the source value number is defined by a copy from the destination reg
128     /// see if we can merge these two destination reg valno# into a single
129     /// value number, eliminating a copy.
130     bool AdjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
131
132     /// HasOtherReachingDefs - Return true if there are definitions of IntB
133     /// other than BValNo val# that can reach uses of AValno val# of IntA.
134     bool HasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
135                               VNInfo *AValNo, VNInfo *BValNo);
136
137     /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy.
138     /// If the source value number is defined by a commutable instruction and
139     /// its other operand is coalesced to the copy dest register, see if we
140     /// can transform the copy into a noop by commuting the definition.
141     bool RemoveCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
142
143     /// ReMaterializeTrivialDef - If the source of a copy is defined by a
144     /// trivial computation, replace the copy by rematerialize the definition.
145     /// If PreserveSrcInt is true, make sure SrcInt is valid after the call.
146     bool ReMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt,
147                                  unsigned DstReg, MachineInstr *CopyMI);
148
149     /// shouldJoinPhys - Return true if a physreg copy should be joined.
150     bool shouldJoinPhys(CoalescerPair &CP);
151
152     /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
153     /// update the subregister number if it is not zero. If DstReg is a
154     /// physical register and the existing subregister number of the def / use
155     /// being updated is not zero, make sure to set it to the correct physical
156     /// subregister.
157     void UpdateRegDefsUses(const CoalescerPair &CP);
158
159     /// RemoveDeadDef - If a def of a live interval is now determined dead,
160     /// remove the val# it defines. If the live interval becomes empty, remove
161     /// it as well.
162     bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI);
163
164     /// markAsJoined - Remember that CopyMI has already been joined.
165     void markAsJoined(MachineInstr *CopyMI);
166
167     /// eliminateUndefCopy - Handle copies of undef values.
168     bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
169
170   public:
171     static char ID; // Class identification, replacement for typeinfo
172     RegisterCoalescer() : MachineFunctionPass(ID) {
173       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
174     }
175
176     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
177
178     virtual void releaseMemory();
179
180     /// runOnMachineFunction - pass entry point
181     virtual bool runOnMachineFunction(MachineFunction&);
182
183     /// print - Implement the dump method.
184     virtual void print(raw_ostream &O, const Module* = 0) const;
185   };
186 } /// end anonymous namespace
187
188 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
189
190 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
191                       "Simple Register Coalescing", false, false)
192 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
193 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
194 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
195 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
196 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
197 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
198                     "Simple Register Coalescing", false, false)
199
200 char RegisterCoalescer::ID = 0;
201
202 static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
203   if (!a) return b;
204   if (!b) return a;
205   return tri.composeSubRegIndices(a, b);
206 }
207
208 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
209                         unsigned &Src, unsigned &Dst,
210                         unsigned &SrcSub, unsigned &DstSub) {
211   if (MI->isCopy()) {
212     Dst = MI->getOperand(0).getReg();
213     DstSub = MI->getOperand(0).getSubReg();
214     Src = MI->getOperand(1).getReg();
215     SrcSub = MI->getOperand(1).getSubReg();
216   } else if (MI->isSubregToReg()) {
217     Dst = MI->getOperand(0).getReg();
218     DstSub = compose(tri, MI->getOperand(0).getSubReg(),
219                      MI->getOperand(3).getImm());
220     Src = MI->getOperand(2).getReg();
221     SrcSub = MI->getOperand(2).getSubReg();
222   } else
223     return false;
224   return true;
225 }
226
227 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
228   SrcReg = DstReg = SubIdx = 0;
229   NewRC = 0;
230   Flipped = CrossClass = false;
231
232   unsigned Src, Dst, SrcSub, DstSub;
233   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
234     return false;
235   Partial = SrcSub || DstSub;
236
237   // If one register is a physreg, it must be Dst.
238   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
239     if (TargetRegisterInfo::isPhysicalRegister(Dst))
240       return false;
241     std::swap(Src, Dst);
242     std::swap(SrcSub, DstSub);
243     Flipped = true;
244   }
245
246   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
247
248   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
249     // Eliminate DstSub on a physreg.
250     if (DstSub) {
251       Dst = TRI.getSubReg(Dst, DstSub);
252       if (!Dst) return false;
253       DstSub = 0;
254     }
255
256     // Eliminate SrcSub by picking a corresponding Dst superregister.
257     if (SrcSub) {
258       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
259       if (!Dst) return false;
260       SrcSub = 0;
261     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
262       return false;
263     }
264   } else {
265     // Both registers are virtual.
266
267     // Both registers have subreg indices.
268     if (SrcSub && DstSub) {
269       // For now we only handle the case of identical indices in commensurate
270       // registers: Dreg:ssub_1 + Dreg:ssub_1 -> Dreg
271       // FIXME: Handle Qreg:ssub_3 + Dreg:ssub_1 as QReg:dsub_1 + Dreg.
272       if (SrcSub != DstSub)
273         return false;
274       const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
275       const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
276       if (!TRI.getCommonSubClass(DstRC, SrcRC))
277         return false;
278       SrcSub = DstSub = 0;
279     }
280
281     // There can be no SrcSub.
282     if (SrcSub) {
283       std::swap(Src, Dst);
284       DstSub = SrcSub;
285       SrcSub = 0;
286       assert(!Flipped && "Unexpected flip");
287       Flipped = true;
288     }
289
290     // Find the new register class.
291     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
292     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
293     if (DstSub)
294       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
295     else
296       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
297     if (!NewRC)
298       return false;
299     CrossClass = NewRC != DstRC || NewRC != SrcRC;
300   }
301   // Check our invariants
302   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
303   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
304          "Cannot have a physical SubIdx");
305   SrcReg = Src;
306   DstReg = Dst;
307   SubIdx = DstSub;
308   return true;
309 }
310
311 bool CoalescerPair::flip() {
312   if (SubIdx || TargetRegisterInfo::isPhysicalRegister(DstReg))
313     return false;
314   std::swap(SrcReg, DstReg);
315   Flipped = !Flipped;
316   return true;
317 }
318
319 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
320   if (!MI)
321     return false;
322   unsigned Src, Dst, SrcSub, DstSub;
323   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
324     return false;
325
326   // Find the virtual register that is SrcReg.
327   if (Dst == SrcReg) {
328     std::swap(Src, Dst);
329     std::swap(SrcSub, DstSub);
330   } else if (Src != SrcReg) {
331     return false;
332   }
333
334   // Now check that Dst matches DstReg.
335   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
336     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
337       return false;
338     assert(!SubIdx && "Inconsistent CoalescerPair state.");
339     // DstSub could be set for a physreg from INSERT_SUBREG.
340     if (DstSub)
341       Dst = TRI.getSubReg(Dst, DstSub);
342     // Full copy of Src.
343     if (!SrcSub)
344       return DstReg == Dst;
345     // This is a partial register copy. Check that the parts match.
346     return TRI.getSubReg(DstReg, SrcSub) == Dst;
347   } else {
348     // DstReg is virtual.
349     if (DstReg != Dst)
350       return false;
351     // Registers match, do the subregisters line up?
352     return compose(TRI, SubIdx, SrcSub) == DstSub;
353   }
354 }
355
356 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
357   AU.setPreservesCFG();
358   AU.addRequired<AliasAnalysis>();
359   AU.addRequired<LiveIntervals>();
360   AU.addPreserved<LiveIntervals>();
361   AU.addRequired<LiveDebugVariables>();
362   AU.addPreserved<LiveDebugVariables>();
363   AU.addPreserved<SlotIndexes>();
364   AU.addRequired<MachineLoopInfo>();
365   AU.addPreserved<MachineLoopInfo>();
366   AU.addPreservedID(MachineDominatorsID);
367   MachineFunctionPass::getAnalysisUsage(AU);
368 }
369
370 void RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
371   /// Joined copies are not deleted immediately, but kept in JoinedCopies.
372   JoinedCopies.insert(CopyMI);
373
374   /// Mark all register operands of CopyMI as <undef> so they won't affect dead
375   /// code elimination.
376   for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
377        E = CopyMI->operands_end(); I != E; ++I)
378     if (I->isReg())
379       I->setIsUndef(true);
380 }
381
382 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
383 /// being the source and IntB being the dest, thus this defines a value number
384 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
385 /// see if we can merge these two pieces of B into a single value number,
386 /// eliminating a copy.  For example:
387 ///
388 ///  A3 = B0
389 ///    ...
390 ///  B1 = A3      <- this copy
391 ///
392 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
393 /// value number to be replaced with B0 (which simplifies the B liveinterval).
394 ///
395 /// This returns true if an interval was modified.
396 ///
397 bool RegisterCoalescer::AdjustCopiesBackFrom(const CoalescerPair &CP,
398                                                     MachineInstr *CopyMI) {
399   // Bail if there is no dst interval - can happen when merging physical subreg
400   // operations.
401   if (!LIS->hasInterval(CP.getDstReg()))
402     return false;
403
404   LiveInterval &IntA =
405     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
406   LiveInterval &IntB =
407     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
408   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
409
410   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
411   // the example above.
412   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
413   if (BLR == IntB.end()) return false;
414   VNInfo *BValNo = BLR->valno;
415
416   // Get the location that B is defined at.  Two options: either this value has
417   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
418   // can't process it.
419   if (BValNo->def != CopyIdx) return false;
420
421   // AValNo is the value number in A that defines the copy, A3 in the example.
422   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
423   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
424   // The live range might not exist after fun with physreg coalescing.
425   if (ALR == IntA.end()) return false;
426   VNInfo *AValNo = ALR->valno;
427
428   // If AValNo is defined as a copy from IntB, we can potentially process this.
429   // Get the instruction that defines this value number.
430   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
431   if (!CP.isCoalescable(ACopyMI))
432     return false;
433
434   // Get the LiveRange in IntB that this value number starts with.
435   LiveInterval::iterator ValLR =
436     IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
437   if (ValLR == IntB.end())
438     return false;
439
440   // Make sure that the end of the live range is inside the same block as
441   // CopyMI.
442   MachineInstr *ValLREndInst =
443     LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
444   if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
445     return false;
446
447   // Okay, we now know that ValLR ends in the same block that the CopyMI
448   // live-range starts.  If there are no intervening live ranges between them in
449   // IntB, we can merge them.
450   if (ValLR+1 != BLR) return false;
451
452   // If a live interval is a physical register, conservatively check if any
453   // of its aliases is overlapping the live interval of the virtual register.
454   // If so, do not coalesce.
455   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
456     for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
457       if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
458         DEBUG({
459             dbgs() << "\t\tInterfere with alias ";
460             LIS->getInterval(*AS).print(dbgs(), TRI);
461           });
462         return false;
463       }
464   }
465
466   DEBUG({
467       dbgs() << "Extending: ";
468       IntB.print(dbgs(), TRI);
469     });
470
471   SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
472   // We are about to delete CopyMI, so need to remove it as the 'instruction
473   // that defines this value #'. Update the valnum with the new defining
474   // instruction #.
475   BValNo->def = FillerStart;
476
477   // Okay, we can merge them.  We need to insert a new liverange:
478   // [ValLR.end, BLR.begin) of either value number, then we merge the
479   // two value numbers.
480   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
481
482   // If the IntB live range is assigned to a physical register, and if that
483   // physreg has sub-registers, update their live intervals as well.
484   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
485     for (const uint16_t *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
486       if (!LIS->hasInterval(*SR))
487         continue;
488       LiveInterval &SRLI = LIS->getInterval(*SR);
489       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
490                               SRLI.getNextValue(FillerStart,
491                                                 LIS->getVNInfoAllocator())));
492     }
493   }
494
495   // Okay, merge "B1" into the same value number as "B0".
496   if (BValNo != ValLR->valno) {
497     // If B1 is killed by a PHI, then the merged live range must also be killed
498     // by the same PHI, as B0 and B1 can not overlap.
499     bool HasPHIKill = BValNo->hasPHIKill();
500     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
501     if (HasPHIKill)
502       ValLR->valno->setHasPHIKill(true);
503   }
504   DEBUG({
505       dbgs() << "   result = ";
506       IntB.print(dbgs(), TRI);
507       dbgs() << "\n";
508     });
509
510   // If the source instruction was killing the source register before the
511   // merge, unset the isKill marker given the live range has been extended.
512   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
513   if (UIdx != -1) {
514     ValLREndInst->getOperand(UIdx).setIsKill(false);
515   }
516
517   // Rewrite the copy. If the copy instruction was killing the destination
518   // register before the merge, find the last use and trim the live range. That
519   // will also add the isKill marker.
520   CopyMI->substituteRegister(IntA.reg, IntB.reg, CP.getSubIdx(),
521                              *TRI);
522   if (ALR->end == CopyIdx)
523     LIS->shrinkToUses(&IntA);
524
525   ++numExtends;
526   return true;
527 }
528
529 /// HasOtherReachingDefs - Return true if there are definitions of IntB
530 /// other than BValNo val# that can reach uses of AValno val# of IntA.
531 bool RegisterCoalescer::HasOtherReachingDefs(LiveInterval &IntA,
532                                                     LiveInterval &IntB,
533                                                     VNInfo *AValNo,
534                                                     VNInfo *BValNo) {
535   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
536        AI != AE; ++AI) {
537     if (AI->valno != AValNo) continue;
538     LiveInterval::Ranges::iterator BI =
539       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
540     if (BI != IntB.ranges.begin())
541       --BI;
542     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
543       if (BI->valno == BValNo)
544         continue;
545       if (BI->start <= AI->start && BI->end > AI->start)
546         return true;
547       if (BI->start > AI->start && BI->start < AI->end)
548         return true;
549     }
550   }
551   return false;
552 }
553
554 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with
555 /// IntA being the source and IntB being the dest, thus this defines a value
556 /// number in IntB.  If the source value number (in IntA) is defined by a
557 /// commutable instruction and its other operand is coalesced to the copy dest
558 /// register, see if we can transform the copy into a noop by commuting the
559 /// definition. For example,
560 ///
561 ///  A3 = op A2 B0<kill>
562 ///    ...
563 ///  B1 = A3      <- this copy
564 ///    ...
565 ///     = op A3   <- more uses
566 ///
567 /// ==>
568 ///
569 ///  B2 = op B0 A2<kill>
570 ///    ...
571 ///  B1 = B2      <- now an identify copy
572 ///    ...
573 ///     = op B2   <- more uses
574 ///
575 /// This returns true if an interval was modified.
576 ///
577 bool RegisterCoalescer::RemoveCopyByCommutingDef(const CoalescerPair &CP,
578                                                         MachineInstr *CopyMI) {
579   // FIXME: For now, only eliminate the copy by commuting its def when the
580   // source register is a virtual register. We want to guard against cases
581   // where the copy is a back edge copy and commuting the def lengthen the
582   // live interval of the source register to the entire loop.
583   if (CP.isPhys() && CP.isFlipped())
584     return false;
585
586   // Bail if there is no dst interval.
587   if (!LIS->hasInterval(CP.getDstReg()))
588     return false;
589
590   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
591
592   LiveInterval &IntA =
593     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
594   LiveInterval &IntB =
595     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
596
597   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
598   // the example above.
599   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
600   if (!BValNo || BValNo->def != CopyIdx)
601     return false;
602
603   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
604
605   // AValNo is the value number in A that defines the copy, A3 in the example.
606   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
607   assert(AValNo && "COPY source not live");
608
609   // If other defs can reach uses of this def, then it's not safe to perform
610   // the optimization.
611   if (AValNo->isPHIDef() || AValNo->isUnused() || AValNo->hasPHIKill())
612     return false;
613   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
614   if (!DefMI)
615     return false;
616   if (!DefMI->isCommutable())
617     return false;
618   // If DefMI is a two-address instruction then commuting it will change the
619   // destination register.
620   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
621   assert(DefIdx != -1);
622   unsigned UseOpIdx;
623   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
624     return false;
625   unsigned Op1, Op2, NewDstIdx;
626   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
627     return false;
628   if (Op1 == UseOpIdx)
629     NewDstIdx = Op2;
630   else if (Op2 == UseOpIdx)
631     NewDstIdx = Op1;
632   else
633     return false;
634
635   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
636   unsigned NewReg = NewDstMO.getReg();
637   if (NewReg != IntB.reg || !NewDstMO.isKill())
638     return false;
639
640   // Make sure there are no other definitions of IntB that would reach the
641   // uses which the new definition can reach.
642   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
643     return false;
644
645   // Abort if the aliases of IntB.reg have values that are not simply the
646   // clobbers from the superreg.
647   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
648     for (const uint16_t *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
649       if (LIS->hasInterval(*AS) &&
650           HasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
651         return false;
652
653   // If some of the uses of IntA.reg is already coalesced away, return false.
654   // It's not possible to determine whether it's safe to perform the coalescing.
655   for (MachineRegisterInfo::use_nodbg_iterator UI =
656          MRI->use_nodbg_begin(IntA.reg),
657        UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
658     MachineInstr *UseMI = &*UI;
659     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
660     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
661     if (ULR == IntA.end())
662       continue;
663     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
664       return false;
665   }
666
667   DEBUG(dbgs() << "\tRemoveCopyByCommutingDef: " << AValNo->def << '\t'
668                << *DefMI);
669
670   // At this point we have decided that it is legal to do this
671   // transformation.  Start by commuting the instruction.
672   MachineBasicBlock *MBB = DefMI->getParent();
673   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
674   if (!NewMI)
675     return false;
676   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
677       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
678       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
679     return false;
680   if (NewMI != DefMI) {
681     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
682     MachineBasicBlock::iterator Pos = DefMI;
683     MBB->insert(Pos, NewMI);
684     MBB->erase(DefMI);
685   }
686   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
687   NewMI->getOperand(OpIdx).setIsKill();
688
689   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
690   // A = or A, B
691   // ...
692   // B = A
693   // ...
694   // C = A<kill>
695   // ...
696   //   = B
697
698   // Update uses of IntA of the specific Val# with IntB.
699   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
700          UE = MRI->use_end(); UI != UE;) {
701     MachineOperand &UseMO = UI.getOperand();
702     MachineInstr *UseMI = &*UI;
703     ++UI;
704     if (JoinedCopies.count(UseMI))
705       continue;
706     if (UseMI->isDebugValue()) {
707       // FIXME These don't have an instruction index.  Not clear we have enough
708       // info to decide whether to do this replacement or not.  For now do it.
709       UseMO.setReg(NewReg);
710       continue;
711     }
712     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
713     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
714     if (ULR == IntA.end() || ULR->valno != AValNo)
715       continue;
716     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
717       UseMO.substPhysReg(NewReg, *TRI);
718     else
719       UseMO.setReg(NewReg);
720     if (UseMI == CopyMI)
721       continue;
722     if (!UseMI->isCopy())
723       continue;
724     if (UseMI->getOperand(0).getReg() != IntB.reg ||
725         UseMI->getOperand(0).getSubReg())
726       continue;
727
728     // This copy will become a noop. If it's defining a new val#, merge it into
729     // BValNo.
730     SlotIndex DefIdx = UseIdx.getRegSlot();
731     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
732     if (!DVNI)
733       continue;
734     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
735     assert(DVNI->def == DefIdx);
736     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
737     markAsJoined(UseMI);
738   }
739
740   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
741   // is updated.
742   VNInfo *ValNo = BValNo;
743   ValNo->def = AValNo->def;
744   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
745        AI != AE; ++AI) {
746     if (AI->valno != AValNo) continue;
747     IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
748   }
749   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
750
751   IntA.removeValNo(AValNo);
752   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
753   ++numCommutes;
754   return true;
755 }
756
757 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
758 /// computation, replace the copy by rematerialize the definition.
759 bool RegisterCoalescer::ReMaterializeTrivialDef(LiveInterval &SrcInt,
760                                                        bool preserveSrcInt,
761                                                        unsigned DstReg,
762                                                        MachineInstr *CopyMI) {
763   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
764   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
765   assert(SrcLR != SrcInt.end() && "Live range not found!");
766   VNInfo *ValNo = SrcLR->valno;
767   if (ValNo->isPHIDef() || ValNo->isUnused())
768     return false;
769   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
770   if (!DefMI)
771     return false;
772   assert(DefMI && "Defining instruction disappeared");
773   if (!DefMI->isAsCheapAsAMove())
774     return false;
775   if (!TII->isTriviallyReMaterializable(DefMI, AA))
776     return false;
777   bool SawStore = false;
778   if (!DefMI->isSafeToMove(TII, AA, SawStore))
779     return false;
780   const MCInstrDesc &MCID = DefMI->getDesc();
781   if (MCID.getNumDefs() != 1)
782     return false;
783   if (!DefMI->isImplicitDef()) {
784     // Make sure the copy destination register class fits the instruction
785     // definition register class. The mismatch can happen as a result of earlier
786     // extract_subreg, insert_subreg, subreg_to_reg coalescing.
787     const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI);
788     if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
789       if (MRI->getRegClass(DstReg) != RC)
790         return false;
791     } else if (!RC->contains(DstReg))
792       return false;
793   }
794
795   MachineBasicBlock *MBB = CopyMI->getParent();
796   MachineBasicBlock::iterator MII =
797     llvm::next(MachineBasicBlock::iterator(CopyMI));
798   TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
799   MachineInstr *NewMI = prior(MII);
800
801   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
802   // We need to remember these so we can add intervals once we insert
803   // NewMI into SlotIndexes.
804   SmallVector<unsigned, 4> NewMIImplDefs;
805   for (unsigned i = NewMI->getDesc().getNumOperands(),
806          e = NewMI->getNumOperands(); i != e; ++i) {
807     MachineOperand &MO = NewMI->getOperand(i);
808     if (MO.isReg()) {
809       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
810              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
811       NewMIImplDefs.push_back(MO.getReg());
812     }
813   }
814
815   // CopyMI may have implicit operands, transfer them over to the newly
816   // rematerialized instruction. And update implicit def interval valnos.
817   for (unsigned i = CopyMI->getDesc().getNumOperands(),
818          e = CopyMI->getNumOperands(); i != e; ++i) {
819     MachineOperand &MO = CopyMI->getOperand(i);
820     if (MO.isReg()) {
821       assert(MO.isImplicit() && "No explicit operands after implict operands.");
822       // Discard VReg implicit defs.
823       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
824         NewMI->addOperand(MO);
825       }
826     }
827   }
828
829   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
830
831   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
832   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
833     unsigned reg = NewMIImplDefs[i];
834     LiveInterval &li = LIS->getInterval(reg);
835     VNInfo *DeadDefVN = li.getNextValue(NewMIIdx.getRegSlot(),
836                                         LIS->getVNInfoAllocator());
837     LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
838     li.addRange(lr);
839   }
840
841   CopyMI->eraseFromParent();
842   ReMatCopies.insert(CopyMI);
843   ReMatDefs.insert(DefMI);
844   DEBUG(dbgs() << "Remat: " << *NewMI);
845   ++NumReMats;
846
847   // The source interval can become smaller because we removed a use.
848   if (preserveSrcInt)
849     LIS->shrinkToUses(&SrcInt);
850
851   return true;
852 }
853
854 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
855 /// values, it only removes local variables. When we have a copy like:
856 ///
857 ///   %vreg1 = COPY %vreg2<undef>
858 ///
859 /// We delete the copy and remove the corresponding value number from %vreg1.
860 /// Any uses of that value number are marked as <undef>.
861 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
862                                            const CoalescerPair &CP) {
863   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
864   LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
865   if (SrcInt->liveAt(Idx))
866     return false;
867   LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
868   if (DstInt->liveAt(Idx))
869     return false;
870
871   // No intervals are live-in to CopyMI - it is undef.
872   if (CP.isFlipped())
873     DstInt = SrcInt;
874   SrcInt = 0;
875
876   VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
877   assert(DeadVNI && "No value defined in DstInt");
878   DstInt->removeValNo(DeadVNI);
879
880   // Find new undef uses.
881   for (MachineRegisterInfo::reg_nodbg_iterator
882          I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
883        I != E; ++I) {
884     MachineOperand &MO = I.getOperand();
885     if (MO.isDef() || MO.isUndef())
886       continue;
887     MachineInstr *MI = MO.getParent();
888     SlotIndex Idx = LIS->getInstructionIndex(MI);
889     if (DstInt->liveAt(Idx))
890       continue;
891     MO.setIsUndef(true);
892     DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
893   }
894   return true;
895 }
896
897 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
898 /// update the subregister number if it is not zero. If DstReg is a
899 /// physical register and the existing subregister number of the def / use
900 /// being updated is not zero, make sure to set it to the correct physical
901 /// subregister.
902 void
903 RegisterCoalescer::UpdateRegDefsUses(const CoalescerPair &CP) {
904   bool DstIsPhys = CP.isPhys();
905   unsigned SrcReg = CP.getSrcReg();
906   unsigned DstReg = CP.getDstReg();
907   unsigned SubIdx = CP.getSubIdx();
908
909   // Update LiveDebugVariables.
910   LDV->renameRegister(SrcReg, DstReg, SubIdx);
911
912   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
913        MachineInstr *UseMI = I.skipInstruction();) {
914     // A PhysReg copy that won't be coalesced can perhaps be rematerialized
915     // instead.
916     if (DstIsPhys) {
917       if (UseMI->isFullCopy() &&
918           UseMI->getOperand(1).getReg() == SrcReg &&
919           UseMI->getOperand(0).getReg() != SrcReg &&
920           UseMI->getOperand(0).getReg() != DstReg &&
921           !JoinedCopies.count(UseMI) &&
922           ReMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
923                                   UseMI->getOperand(0).getReg(), UseMI))
924         continue;
925     }
926
927     SmallVector<unsigned,8> Ops;
928     bool Reads, Writes;
929     tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
930
931     // Replace SrcReg with DstReg in all UseMI operands.
932     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
933       MachineOperand &MO = UseMI->getOperand(Ops[i]);
934
935       // Make sure we don't create read-modify-write defs accidentally.  We
936       // assume here that a SrcReg def cannot be joined into a live DstReg.  If
937       // RegisterCoalescer starts tracking partially live registers, we will
938       // need to check the actual LiveInterval to determine if DstReg is live
939       // here.
940       if (SubIdx && !Reads)
941         MO.setIsUndef();
942
943       if (DstIsPhys)
944         MO.substPhysReg(DstReg, *TRI);
945       else
946         MO.substVirtReg(DstReg, SubIdx, *TRI);
947     }
948
949     // This instruction is a copy that will be removed.
950     if (JoinedCopies.count(UseMI))
951       continue;
952
953     DEBUG({
954         dbgs() << "\t\tupdated: ";
955         if (!UseMI->isDebugValue())
956           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
957         dbgs() << *UseMI;
958       });
959   }
960 }
961
962 /// removeIntervalIfEmpty - Check if the live interval of a physical register
963 /// is empty, if so remove it and also remove the empty intervals of its
964 /// sub-registers. Return true if live interval is removed.
965 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
966                                   const TargetRegisterInfo *TRI) {
967   if (li.empty()) {
968     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
969       for (const uint16_t* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
970         if (!LIS->hasInterval(*SR))
971           continue;
972         LiveInterval &sli = LIS->getInterval(*SR);
973         if (sli.empty())
974           LIS->removeInterval(*SR);
975       }
976     LIS->removeInterval(li.reg);
977     return true;
978   }
979   return false;
980 }
981
982 /// RemoveDeadDef - If a def of a live interval is now determined dead, remove
983 /// the val# it defines. If the live interval becomes empty, remove it as well.
984 bool RegisterCoalescer::RemoveDeadDef(LiveInterval &li,
985                                              MachineInstr *DefMI) {
986   SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
987   LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
988   if (DefIdx != MLR->valno->def)
989     return false;
990   li.removeValNo(MLR->valno);
991   return removeIntervalIfEmpty(li, LIS, TRI);
992 }
993
994 /// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
995 /// We need to be careful about coalescing a source physical register with a
996 /// virtual register. Once the coalescing is done, it cannot be broken and these
997 /// are not spillable! If the destination interval uses are far away, think
998 /// twice about coalescing them!
999 bool RegisterCoalescer::shouldJoinPhys(CoalescerPair &CP) {
1000   bool Allocatable = LIS->isAllocatable(CP.getDstReg());
1001   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1002
1003   /// Always join simple intervals that are defined by a single copy from a
1004   /// reserved register. This doesn't increase register pressure, so it is
1005   /// always beneficial.
1006   if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
1007     return true;
1008
1009   if (!EnablePhysicalJoin) {
1010     DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
1011     return false;
1012   }
1013
1014   // Only coalesce to allocatable physreg, we don't want to risk modifying
1015   // reserved registers.
1016   if (!Allocatable) {
1017     DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1018     return false;  // Not coalescable.
1019   }
1020
1021   // Don't join with physregs that have a ridiculous number of live
1022   // ranges. The data structure performance is really bad when that
1023   // happens.
1024   if (LIS->hasInterval(CP.getDstReg()) &&
1025       LIS->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1026     ++numAborts;
1027     DEBUG(dbgs()
1028           << "\tPhysical register live interval too complicated, abort!\n");
1029     return false;
1030   }
1031
1032   // FIXME: Why are we skipping this test for partial copies?
1033   //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1034   if (!CP.isPartial()) {
1035     const TargetRegisterClass *RC = MRI->getRegClass(CP.getSrcReg());
1036     unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2;
1037     unsigned Length = LIS->getApproximateInstructionCount(JoinVInt);
1038     if (Length > Threshold) {
1039       ++numAborts;
1040       DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1041       return false;
1042     }
1043   }
1044   return true;
1045 }
1046
1047
1048 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1049 /// which are the src/dst of the copy instruction CopyMI.  This returns true
1050 /// if the copy was successfully coalesced away. If it is not currently
1051 /// possible to coalesce this interval, but it may be possible if other
1052 /// things get coalesced, then it returns true by reference in 'Again'.
1053 bool RegisterCoalescer::JoinCopy(MachineInstr *CopyMI, bool &Again) {
1054
1055   Again = false;
1056   if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1057     return false; // Already done.
1058
1059   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1060
1061   CoalescerPair CP(*TII, *TRI);
1062   if (!CP.setRegisters(CopyMI)) {
1063     DEBUG(dbgs() << "\tNot coalescable.\n");
1064     return false;
1065   }
1066
1067   // If they are already joined we continue.
1068   if (CP.getSrcReg() == CP.getDstReg()) {
1069     markAsJoined(CopyMI);
1070     DEBUG(dbgs() << "\tCopy already coalesced.\n");
1071     return false;  // Not coalescable.
1072   }
1073
1074   // Eliminate undefs.
1075   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1076     markAsJoined(CopyMI);
1077     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1078     return false;  // Not coalescable.
1079   }
1080
1081   DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1082                << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSubIdx())
1083                << "\n");
1084
1085   // Enforce policies.
1086   if (CP.isPhys()) {
1087     if (!shouldJoinPhys(CP)) {
1088       // Before giving up coalescing, if definition of source is defined by
1089       // trivial computation, try rematerializing it.
1090       if (!CP.isFlipped() &&
1091           ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1092                                   CP.getDstReg(), CopyMI))
1093         return true;
1094       return false;
1095     }
1096   } else {
1097     // Avoid constraining virtual register regclass too much.
1098     if (CP.isCrossClass()) {
1099       DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
1100       if (DisableCrossClassJoin) {
1101         DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1102         return false;
1103       }
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 RegisterCoalescer::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1616                                             std::vector<MachineInstr*> &TryAgain) {
1617   DEBUG(dbgs() << MBB->getName() << ":\n");
1618
1619   SmallVector<MachineInstr*, 8> VirtCopies;
1620   SmallVector<MachineInstr*, 8> PhysCopies;
1621   SmallVector<MachineInstr*, 8> ImpDefCopies;
1622   for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1623        MII != E;) {
1624     MachineInstr *Inst = MII++;
1625
1626     // If this isn't a copy nor a extract_subreg, we can't join intervals.
1627     unsigned SrcReg, DstReg;
1628     if (Inst->isCopy()) {
1629       DstReg = Inst->getOperand(0).getReg();
1630       SrcReg = Inst->getOperand(1).getReg();
1631     } else if (Inst->isSubregToReg()) {
1632       DstReg = Inst->getOperand(0).getReg();
1633       SrcReg = Inst->getOperand(2).getReg();
1634     } else
1635       continue;
1636
1637     bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1638     bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1639     if (LIS->hasInterval(SrcReg) && LIS->getInterval(SrcReg).empty())
1640       ImpDefCopies.push_back(Inst);
1641     else if (SrcIsPhys || DstIsPhys)
1642       PhysCopies.push_back(Inst);
1643     else
1644       VirtCopies.push_back(Inst);
1645   }
1646
1647   // Try coalescing implicit copies and insert_subreg <undef> first,
1648   // followed by copies to / from physical registers, then finally copies
1649   // from virtual registers to virtual registers.
1650   for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1651     MachineInstr *TheCopy = ImpDefCopies[i];
1652     bool Again = false;
1653     if (!JoinCopy(TheCopy, Again))
1654       if (Again)
1655         TryAgain.push_back(TheCopy);
1656   }
1657   for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1658     MachineInstr *TheCopy = PhysCopies[i];
1659     bool Again = false;
1660     if (!JoinCopy(TheCopy, Again))
1661       if (Again)
1662         TryAgain.push_back(TheCopy);
1663   }
1664   for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1665     MachineInstr *TheCopy = VirtCopies[i];
1666     bool Again = false;
1667     if (!JoinCopy(TheCopy, Again))
1668       if (Again)
1669         TryAgain.push_back(TheCopy);
1670   }
1671 }
1672
1673 void RegisterCoalescer::joinIntervals() {
1674   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1675
1676   std::vector<MachineInstr*> TryAgainList;
1677   if (Loops->empty()) {
1678     // If there are no loops in the function, join intervals in function order.
1679     for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1680          I != E; ++I)
1681       CopyCoalesceInMBB(I, TryAgainList);
1682   } else {
1683     // Otherwise, join intervals in inner loops before other intervals.
1684     // Unfortunately we can't just iterate over loop hierarchy here because
1685     // there may be more MBB's than BB's.  Collect MBB's for sorting.
1686
1687     // Join intervals in the function prolog first. We want to join physical
1688     // registers with virtual registers before the intervals got too long.
1689     std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1690     for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1691       MachineBasicBlock *MBB = I;
1692       MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1693     }
1694
1695     // Sort by loop depth.
1696     std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1697
1698     // Finally, join intervals in loop nest order.
1699     for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1700       CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1701   }
1702
1703   // Joining intervals can allow other intervals to be joined.  Iteratively join
1704   // until we make no progress.
1705   bool ProgressMade = true;
1706   while (ProgressMade) {
1707     ProgressMade = false;
1708
1709     for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1710       MachineInstr *&TheCopy = TryAgainList[i];
1711       if (!TheCopy)
1712         continue;
1713
1714       bool Again = false;
1715       bool Success = JoinCopy(TheCopy, Again);
1716       if (Success || !Again) {
1717         TheCopy= 0;   // Mark this one as done.
1718         ProgressMade = true;
1719       }
1720     }
1721   }
1722 }
1723
1724 void RegisterCoalescer::releaseMemory() {
1725   JoinedCopies.clear();
1726   ReMatCopies.clear();
1727   ReMatDefs.clear();
1728 }
1729
1730 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1731   MF = &fn;
1732   MRI = &fn.getRegInfo();
1733   TM = &fn.getTarget();
1734   TRI = TM->getRegisterInfo();
1735   TII = TM->getInstrInfo();
1736   LIS = &getAnalysis<LiveIntervals>();
1737   LDV = &getAnalysis<LiveDebugVariables>();
1738   AA = &getAnalysis<AliasAnalysis>();
1739   Loops = &getAnalysis<MachineLoopInfo>();
1740
1741   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1742                << "********** Function: "
1743                << ((Value*)MF->getFunction())->getName() << '\n');
1744
1745   if (VerifyCoalescing)
1746     MF->verify(this, "Before register coalescing");
1747
1748   RegClassInfo.runOnMachineFunction(fn);
1749
1750   // Join (coalesce) intervals if requested.
1751   if (EnableJoining) {
1752     joinIntervals();
1753     DEBUG({
1754         dbgs() << "********** INTERVALS POST JOINING **********\n";
1755         for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1756              I != E; ++I){
1757           I->second->print(dbgs(), TRI);
1758           dbgs() << "\n";
1759         }
1760       });
1761   }
1762
1763   // Perform a final pass over the instructions and compute spill weights
1764   // and remove identity moves.
1765   SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1766   for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1767        mbbi != mbbe; ++mbbi) {
1768     MachineBasicBlock* mbb = mbbi;
1769     for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1770          mii != mie; ) {
1771       MachineInstr *MI = mii;
1772       if (JoinedCopies.count(MI)) {
1773         // Delete all coalesced copies.
1774         bool DoDelete = true;
1775         assert(MI->isCopyLike() && "Unrecognized copy instruction");
1776         unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1777         unsigned DstReg = MI->getOperand(0).getReg();
1778
1779         // Collect candidates for register class inflation.
1780         if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1781             RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1782           InflateRegs.push_back(SrcReg);
1783         if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1784             RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1785           InflateRegs.push_back(DstReg);
1786
1787         if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1788             MI->getNumOperands() > 2)
1789           // Do not delete extract_subreg, insert_subreg of physical
1790           // registers unless the definition is dead. e.g.
1791           // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1792           // or else the scavenger may complain. LowerSubregs will
1793           // delete them later.
1794           DoDelete = false;
1795
1796         if (MI->allDefsAreDead()) {
1797           if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1798               LIS->hasInterval(SrcReg))
1799             LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1800           DoDelete = true;
1801         }
1802         if (!DoDelete) {
1803           // We need the instruction to adjust liveness, so make it a KILL.
1804           if (MI->isSubregToReg()) {
1805             MI->RemoveOperand(3);
1806             MI->RemoveOperand(1);
1807           }
1808           MI->setDesc(TII->get(TargetOpcode::KILL));
1809           mii = llvm::next(mii);
1810         } else {
1811           LIS->RemoveMachineInstrFromMaps(MI);
1812           mii = mbbi->erase(mii);
1813           ++numPeep;
1814         }
1815         continue;
1816       }
1817
1818       // Now check if this is a remat'ed def instruction which is now dead.
1819       if (ReMatDefs.count(MI)) {
1820         bool isDead = true;
1821         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1822           const MachineOperand &MO = MI->getOperand(i);
1823           if (!MO.isReg())
1824             continue;
1825           unsigned Reg = MO.getReg();
1826           if (!Reg)
1827             continue;
1828           DeadDefs.push_back(Reg);
1829           if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1830             // Remat may also enable register class inflation.
1831             if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1832               InflateRegs.push_back(Reg);
1833           }
1834           if (MO.isDead())
1835             continue;
1836           if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1837               !MRI->use_nodbg_empty(Reg)) {
1838             isDead = false;
1839             break;
1840           }
1841         }
1842         if (isDead) {
1843           while (!DeadDefs.empty()) {
1844             unsigned DeadDef = DeadDefs.back();
1845             DeadDefs.pop_back();
1846             RemoveDeadDef(LIS->getInterval(DeadDef), MI);
1847           }
1848           LIS->RemoveMachineInstrFromMaps(mii);
1849           mii = mbbi->erase(mii);
1850           continue;
1851         } else
1852           DeadDefs.clear();
1853       }
1854
1855       ++mii;
1856
1857       // Check for now unnecessary kill flags.
1858       if (LIS->isNotInMIMap(MI)) continue;
1859       SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1860       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1861         MachineOperand &MO = MI->getOperand(i);
1862         if (!MO.isReg() || !MO.isKill()) continue;
1863         unsigned reg = MO.getReg();
1864         if (!reg || !LIS->hasInterval(reg)) continue;
1865         if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1866           MO.setIsKill(false);
1867           continue;
1868         }
1869         // When leaving a kill flag on a physreg, check if any subregs should
1870         // remain alive.
1871         if (!TargetRegisterInfo::isPhysicalRegister(reg))
1872           continue;
1873         for (const uint16_t *SR = TRI->getSubRegisters(reg);
1874              unsigned S = *SR; ++SR)
1875           if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1876             MI->addRegisterDefined(S, TRI);
1877       }
1878     }
1879   }
1880
1881   // After deleting a lot of copies, register classes may be less constrained.
1882   // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1883   // DPR inflation.
1884   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1885   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1886                     InflateRegs.end());
1887   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1888   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1889     unsigned Reg = InflateRegs[i];
1890     if (MRI->reg_nodbg_empty(Reg))
1891       continue;
1892     if (MRI->recomputeRegClass(Reg, *TM)) {
1893       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1894                    << MRI->getRegClass(Reg)->getName() << '\n');
1895       ++NumInflated;
1896     }
1897   }
1898
1899   DEBUG(dump());
1900   DEBUG(LDV->dump());
1901   if (VerifyCoalescing)
1902     MF->verify(this, "After register coalescing");
1903   return true;
1904 }
1905
1906 /// print - Implement the dump method.
1907 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
1908    LIS->print(O, m);
1909 }