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