RegisterCoalescer.cpp revision 0ab7103e06ee1da7bde5b196a68be77ab49a005d
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 "VirtRegMap.h"
20
21#include "llvm/Pass.h"
22#include "llvm/Value.h"
23#include "llvm/ADT/OwningPtr.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Analysis/AliasAnalysis.h"
28#include "llvm/CodeGen/LiveIntervalAnalysis.h"
29#include "llvm/CodeGen/LiveIntervalAnalysis.h"
30#include "llvm/CodeGen/LiveRangeEdit.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineInstr.h"
33#include "llvm/CodeGen/MachineInstr.h"
34#include "llvm/CodeGen/MachineLoopInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/Passes.h"
38#include "llvm/CodeGen/RegisterClassInfo.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/Target/TargetInstrInfo.h"
44#include "llvm/Target/TargetInstrInfo.h"
45#include "llvm/Target/TargetMachine.h"
46#include "llvm/Target/TargetOptions.h"
47#include "llvm/Target/TargetRegisterInfo.h"
48#include <algorithm>
49#include <cmath>
50using namespace llvm;
51
52STATISTIC(numJoins    , "Number of interval joins performed");
53STATISTIC(numCrossRCs , "Number of cross class joins performed");
54STATISTIC(numCommutes , "Number of instruction commuting performed");
55STATISTIC(numExtends  , "Number of copies extended");
56STATISTIC(NumReMats   , "Number of instructions re-materialized");
57STATISTIC(NumInflated , "Number of register classes inflated");
58
59static cl::opt<bool>
60EnableJoining("join-liveintervals",
61              cl::desc("Coalesce copies (default=true)"),
62              cl::init(true));
63
64static cl::opt<bool>
65VerifyCoalescing("verify-coalescing",
66         cl::desc("Verify machine instrs before and after register coalescing"),
67         cl::Hidden);
68
69namespace {
70  class RegisterCoalescer : public MachineFunctionPass,
71                            private LiveRangeEdit::Delegate {
72    MachineFunction* MF;
73    MachineRegisterInfo* MRI;
74    const TargetMachine* TM;
75    const TargetRegisterInfo* TRI;
76    const TargetInstrInfo* TII;
77    LiveIntervals *LIS;
78    LiveDebugVariables *LDV;
79    const MachineLoopInfo* Loops;
80    AliasAnalysis *AA;
81    RegisterClassInfo RegClassInfo;
82
83    /// WorkList - Copy instructions yet to be coalesced.
84    SmallVector<MachineInstr*, 8> WorkList;
85
86    /// ErasedInstrs - Set of instruction pointers that have been erased, and
87    /// that may be present in WorkList.
88    SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
89
90    /// Dead instructions that are about to be deleted.
91    SmallVector<MachineInstr*, 8> DeadDefs;
92
93    /// Virtual registers to be considered for register class inflation.
94    SmallVector<unsigned, 8> InflateRegs;
95
96    /// Recursively eliminate dead defs in DeadDefs.
97    void eliminateDeadDefs();
98
99    /// LiveRangeEdit callback.
100    void LRE_WillEraseInstruction(MachineInstr *MI);
101
102    /// joinAllIntervals - join compatible live intervals
103    void joinAllIntervals();
104
105    /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
106    /// copies that cannot yet be coalesced into WorkList.
107    void copyCoalesceInMBB(MachineBasicBlock *MBB);
108
109    /// copyCoalesceWorkList - Try to coalesce all copies in WorkList after
110    /// position From. Return true if any progress was made.
111    bool copyCoalesceWorkList(unsigned From = 0);
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    /// Attempt joining with a reserved physreg.
127    bool joinReservedPhysReg(CoalescerPair &CP);
128
129    /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
130    /// the source value number is defined by a copy from the destination reg
131    /// see if we can merge these two destination reg valno# into a single
132    /// value number, eliminating a copy.
133    bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
134
135    /// hasOtherReachingDefs - Return true if there are definitions of IntB
136    /// other than BValNo val# that can reach uses of AValno val# of IntA.
137    bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
138                              VNInfo *AValNo, VNInfo *BValNo);
139
140    /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
141    /// If the source value number is defined by a commutable instruction and
142    /// its other operand is coalesced to the copy dest register, see if we
143    /// can transform the copy into a noop by commuting the definition.
144    bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
145
146    /// reMaterializeTrivialDef - If the source of a copy is defined by a
147    /// trivial computation, replace the copy by rematerialize the definition.
148    bool reMaterializeTrivialDef(LiveInterval &SrcInt, unsigned DstReg,
149                                 MachineInstr *CopyMI);
150
151    /// canJoinPhys - Return true if a physreg copy should be joined.
152    bool canJoinPhys(CoalescerPair &CP);
153
154    /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
155    /// update the subregister number if it is not zero. If DstReg is a
156    /// physical register and the existing subregister number of the def / use
157    /// being updated is not zero, make sure to set it to the correct physical
158    /// subregister.
159    void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
160
161    /// eliminateUndefCopy - Handle copies of undef values.
162    bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
163
164  public:
165    static char ID; // Class identification, replacement for typeinfo
166    RegisterCoalescer() : MachineFunctionPass(ID) {
167      initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
168    }
169
170    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
171
172    virtual void releaseMemory();
173
174    /// runOnMachineFunction - pass entry point
175    virtual bool runOnMachineFunction(MachineFunction&);
176
177    /// print - Implement the dump method.
178    virtual void print(raw_ostream &O, const Module* = 0) const;
179  };
180} /// end anonymous namespace
181
182char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
183
184INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
185                      "Simple Register Coalescing", false, false)
186INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
187INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
188INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
189INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
190INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
191INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
192                    "Simple Register Coalescing", false, false)
193
194char RegisterCoalescer::ID = 0;
195
196static unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
197  if (!a) return b;
198  if (!b) return a;
199  return tri.composeSubRegIndices(a, b);
200}
201
202static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
203                        unsigned &Src, unsigned &Dst,
204                        unsigned &SrcSub, unsigned &DstSub) {
205  if (MI->isCopy()) {
206    Dst = MI->getOperand(0).getReg();
207    DstSub = MI->getOperand(0).getSubReg();
208    Src = MI->getOperand(1).getReg();
209    SrcSub = MI->getOperand(1).getSubReg();
210  } else if (MI->isSubregToReg()) {
211    Dst = MI->getOperand(0).getReg();
212    DstSub = compose(tri, MI->getOperand(0).getSubReg(),
213                     MI->getOperand(3).getImm());
214    Src = MI->getOperand(2).getReg();
215    SrcSub = MI->getOperand(2).getSubReg();
216  } else
217    return false;
218  return true;
219}
220
221bool CoalescerPair::setRegisters(const MachineInstr *MI) {
222  SrcReg = DstReg = 0;
223  SrcIdx = DstIdx = 0;
224  NewRC = 0;
225  Flipped = CrossClass = false;
226
227  unsigned Src, Dst, SrcSub, DstSub;
228  if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
229    return false;
230  Partial = SrcSub || DstSub;
231
232  // If one register is a physreg, it must be Dst.
233  if (TargetRegisterInfo::isPhysicalRegister(Src)) {
234    if (TargetRegisterInfo::isPhysicalRegister(Dst))
235      return false;
236    std::swap(Src, Dst);
237    std::swap(SrcSub, DstSub);
238    Flipped = true;
239  }
240
241  const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
242
243  if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
244    // Eliminate DstSub on a physreg.
245    if (DstSub) {
246      Dst = TRI.getSubReg(Dst, DstSub);
247      if (!Dst) return false;
248      DstSub = 0;
249    }
250
251    // Eliminate SrcSub by picking a corresponding Dst superregister.
252    if (SrcSub) {
253      Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
254      if (!Dst) return false;
255      SrcSub = 0;
256    } else if (!MRI.getRegClass(Src)->contains(Dst)) {
257      return false;
258    }
259  } else {
260    // Both registers are virtual.
261    const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
262    const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
263
264    // Both registers have subreg indices.
265    if (SrcSub && DstSub) {
266      // Copies between different sub-registers are never coalescable.
267      if (Src == Dst && SrcSub != DstSub)
268        return false;
269
270      NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
271                                         SrcIdx, DstIdx);
272      if (!NewRC)
273        return false;
274    } else if (DstSub) {
275      // SrcReg will be merged with a sub-register of DstReg.
276      SrcIdx = DstSub;
277      NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
278    } else if (SrcSub) {
279      // DstReg will be merged with a sub-register of SrcReg.
280      DstIdx = SrcSub;
281      NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
282    } else {
283      // This is a straight copy without sub-registers.
284      NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
285    }
286
287    // The combined constraint may be impossible to satisfy.
288    if (!NewRC)
289      return false;
290
291    // Prefer SrcReg to be a sub-register of DstReg.
292    // FIXME: Coalescer should support subregs symmetrically.
293    if (DstIdx && !SrcIdx) {
294      std::swap(Src, Dst);
295      std::swap(SrcIdx, DstIdx);
296      Flipped = !Flipped;
297    }
298
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  return true;
308}
309
310bool CoalescerPair::flip() {
311  if (TargetRegisterInfo::isPhysicalRegister(DstReg))
312    return false;
313  std::swap(SrcReg, DstReg);
314  std::swap(SrcIdx, DstIdx);
315  Flipped = !Flipped;
316  return true;
317}
318
319bool 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(!DstIdx && !SrcIdx && "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, SrcIdx, SrcSub) == compose(TRI, DstIdx, DstSub);
353  }
354}
355
356void 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
370void RegisterCoalescer::eliminateDeadDefs() {
371  SmallVector<LiveInterval*, 8> NewRegs;
372  LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
373}
374
375// Callback from eliminateDeadDefs().
376void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
377  // MI may be in WorkList. Make sure we don't visit it.
378  ErasedInstrs.insert(MI);
379}
380
381/// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
382/// being the source and IntB being the dest, thus this defines a value number
383/// in IntB.  If the source value number (in IntA) is defined by a copy from B,
384/// see if we can merge these two pieces of B into a single value number,
385/// eliminating a copy.  For example:
386///
387///  A3 = B0
388///    ...
389///  B1 = A3      <- this copy
390///
391/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
392/// value number to be replaced with B0 (which simplifies the B liveinterval).
393///
394/// This returns true if an interval was modified.
395///
396bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
397                                             MachineInstr *CopyMI) {
398  assert(!CP.isPartial() && "This doesn't work for partial copies.");
399  assert(!CP.isPhys() && "This doesn't work for physreg copies.");
400
401  LiveInterval &IntA =
402    LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
403  LiveInterval &IntB =
404    LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
405  SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
406
407  // BValNo is a value number in B that is defined by a copy from A.  'B3' in
408  // the example above.
409  LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
410  if (BLR == IntB.end()) return false;
411  VNInfo *BValNo = BLR->valno;
412
413  // Get the location that B is defined at.  Two options: either this value has
414  // an unknown definition point or it is defined at CopyIdx.  If unknown, we
415  // can't process it.
416  if (BValNo->def != CopyIdx) return false;
417
418  // AValNo is the value number in A that defines the copy, A3 in the example.
419  SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
420  LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
421  // The live range might not exist after fun with physreg coalescing.
422  if (ALR == IntA.end()) return false;
423  VNInfo *AValNo = ALR->valno;
424
425  // If AValNo is defined as a copy from IntB, we can potentially process this.
426  // Get the instruction that defines this value number.
427  MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
428  if (!CP.isCoalescable(ACopyMI))
429    return false;
430
431  // Get the LiveRange in IntB that this value number starts with.
432  LiveInterval::iterator ValLR =
433    IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
434  if (ValLR == IntB.end())
435    return false;
436
437  // Make sure that the end of the live range is inside the same block as
438  // CopyMI.
439  MachineInstr *ValLREndInst =
440    LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
441  if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
442    return false;
443
444  // Okay, we now know that ValLR ends in the same block that the CopyMI
445  // live-range starts.  If there are no intervening live ranges between them in
446  // IntB, we can merge them.
447  if (ValLR+1 != BLR) return false;
448
449  DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
450
451  SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
452  // We are about to delete CopyMI, so need to remove it as the 'instruction
453  // that defines this value #'. Update the valnum with the new defining
454  // instruction #.
455  BValNo->def = FillerStart;
456
457  // Okay, we can merge them.  We need to insert a new liverange:
458  // [ValLR.end, BLR.begin) of either value number, then we merge the
459  // two value numbers.
460  IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
461
462  // Okay, merge "B1" into the same value number as "B0".
463  if (BValNo != ValLR->valno) {
464    // If B1 is killed by a PHI, then the merged live range must also be killed
465    // by the same PHI, as B0 and B1 can not overlap.
466    bool HasPHIKill = BValNo->hasPHIKill();
467    IntB.MergeValueNumberInto(BValNo, ValLR->valno);
468    if (HasPHIKill)
469      ValLR->valno->setHasPHIKill(true);
470  }
471  DEBUG(dbgs() << "   result = " << IntB << '\n');
472
473  // If the source instruction was killing the source register before the
474  // merge, unset the isKill marker given the live range has been extended.
475  int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
476  if (UIdx != -1) {
477    ValLREndInst->getOperand(UIdx).setIsKill(false);
478  }
479
480  // Rewrite the copy. If the copy instruction was killing the destination
481  // register before the merge, find the last use and trim the live range. That
482  // will also add the isKill marker.
483  CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
484  if (ALR->end == CopyIdx)
485    LIS->shrinkToUses(&IntA);
486
487  ++numExtends;
488  return true;
489}
490
491/// hasOtherReachingDefs - Return true if there are definitions of IntB
492/// other than BValNo val# that can reach uses of AValno val# of IntA.
493bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
494                                             LiveInterval &IntB,
495                                             VNInfo *AValNo,
496                                             VNInfo *BValNo) {
497  // If AValNo has PHI kills, conservatively assume that IntB defs can reach
498  // the PHI values.
499  if (LIS->hasPHIKill(IntA, AValNo))
500    return true;
501
502  for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
503       AI != AE; ++AI) {
504    if (AI->valno != AValNo) continue;
505    LiveInterval::Ranges::iterator BI =
506      std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
507    if (BI != IntB.ranges.begin())
508      --BI;
509    for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
510      if (BI->valno == BValNo)
511        continue;
512      if (BI->start <= AI->start && BI->end > AI->start)
513        return true;
514      if (BI->start > AI->start && BI->start < AI->end)
515        return true;
516    }
517  }
518  return false;
519}
520
521/// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
522/// IntA being the source and IntB being the dest, thus this defines a value
523/// number in IntB.  If the source value number (in IntA) is defined by a
524/// commutable instruction and its other operand is coalesced to the copy dest
525/// register, see if we can transform the copy into a noop by commuting the
526/// definition. For example,
527///
528///  A3 = op A2 B0<kill>
529///    ...
530///  B1 = A3      <- this copy
531///    ...
532///     = op A3   <- more uses
533///
534/// ==>
535///
536///  B2 = op B0 A2<kill>
537///    ...
538///  B1 = B2      <- now an identify copy
539///    ...
540///     = op B2   <- more uses
541///
542/// This returns true if an interval was modified.
543///
544bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
545                                                 MachineInstr *CopyMI) {
546  assert (!CP.isPhys());
547
548  SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
549
550  LiveInterval &IntA =
551    LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
552  LiveInterval &IntB =
553    LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
554
555  // BValNo is a value number in B that is defined by a copy from A. 'B3' in
556  // the example above.
557  VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
558  if (!BValNo || BValNo->def != CopyIdx)
559    return false;
560
561  assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
562
563  // AValNo is the value number in A that defines the copy, A3 in the example.
564  VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
565  assert(AValNo && "COPY source not live");
566  if (AValNo->isPHIDef() || AValNo->isUnused())
567    return false;
568  MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
569  if (!DefMI)
570    return false;
571  if (!DefMI->isCommutable())
572    return false;
573  // If DefMI is a two-address instruction then commuting it will change the
574  // destination register.
575  int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
576  assert(DefIdx != -1);
577  unsigned UseOpIdx;
578  if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
579    return false;
580  unsigned Op1, Op2, NewDstIdx;
581  if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
582    return false;
583  if (Op1 == UseOpIdx)
584    NewDstIdx = Op2;
585  else if (Op2 == UseOpIdx)
586    NewDstIdx = Op1;
587  else
588    return false;
589
590  MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
591  unsigned NewReg = NewDstMO.getReg();
592  if (NewReg != IntB.reg || !NewDstMO.isKill())
593    return false;
594
595  // Make sure there are no other definitions of IntB that would reach the
596  // uses which the new definition can reach.
597  if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
598    return false;
599
600  // If some of the uses of IntA.reg is already coalesced away, return false.
601  // It's not possible to determine whether it's safe to perform the coalescing.
602  for (MachineRegisterInfo::use_nodbg_iterator UI =
603         MRI->use_nodbg_begin(IntA.reg),
604       UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
605    MachineInstr *UseMI = &*UI;
606    SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
607    LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
608    if (ULR == IntA.end() || ULR->valno != AValNo)
609      continue;
610    // If this use is tied to a def, we can't rewrite the register.
611    if (UseMI->isRegTiedToDefOperand(UI.getOperandNo()))
612      return false;
613  }
614
615  DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
616               << *DefMI);
617
618  // At this point we have decided that it is legal to do this
619  // transformation.  Start by commuting the instruction.
620  MachineBasicBlock *MBB = DefMI->getParent();
621  MachineInstr *NewMI = TII->commuteInstruction(DefMI);
622  if (!NewMI)
623    return false;
624  if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
625      TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
626      !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
627    return false;
628  if (NewMI != DefMI) {
629    LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
630    MachineBasicBlock::iterator Pos = DefMI;
631    MBB->insert(Pos, NewMI);
632    MBB->erase(DefMI);
633  }
634  unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
635  NewMI->getOperand(OpIdx).setIsKill();
636
637  // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
638  // A = or A, B
639  // ...
640  // B = A
641  // ...
642  // C = A<kill>
643  // ...
644  //   = B
645
646  // Update uses of IntA of the specific Val# with IntB.
647  for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
648         UE = MRI->use_end(); UI != UE;) {
649    MachineOperand &UseMO = UI.getOperand();
650    MachineInstr *UseMI = &*UI;
651    ++UI;
652    if (UseMI->isDebugValue()) {
653      // FIXME These don't have an instruction index.  Not clear we have enough
654      // info to decide whether to do this replacement or not.  For now do it.
655      UseMO.setReg(NewReg);
656      continue;
657    }
658    SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
659    LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
660    if (ULR == IntA.end() || ULR->valno != AValNo)
661      continue;
662    // Kill flags are no longer accurate. They are recomputed after RA.
663    UseMO.setIsKill(false);
664    if (TargetRegisterInfo::isPhysicalRegister(NewReg))
665      UseMO.substPhysReg(NewReg, *TRI);
666    else
667      UseMO.setReg(NewReg);
668    if (UseMI == CopyMI)
669      continue;
670    if (!UseMI->isCopy())
671      continue;
672    if (UseMI->getOperand(0).getReg() != IntB.reg ||
673        UseMI->getOperand(0).getSubReg())
674      continue;
675
676    // This copy will become a noop. If it's defining a new val#, merge it into
677    // BValNo.
678    SlotIndex DefIdx = UseIdx.getRegSlot();
679    VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
680    if (!DVNI)
681      continue;
682    DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
683    assert(DVNI->def == DefIdx);
684    BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
685    ErasedInstrs.insert(UseMI);
686    LIS->RemoveMachineInstrFromMaps(UseMI);
687    UseMI->eraseFromParent();
688  }
689
690  // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
691  // is updated.
692  VNInfo *ValNo = BValNo;
693  ValNo->def = AValNo->def;
694  for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
695       AI != AE; ++AI) {
696    if (AI->valno != AValNo) continue;
697    IntB.addRange(LiveRange(AI->start, AI->end, ValNo));
698  }
699  DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
700
701  IntA.removeValNo(AValNo);
702  DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
703  ++numCommutes;
704  return true;
705}
706
707/// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
708/// computation, replace the copy by rematerialize the definition.
709bool RegisterCoalescer::reMaterializeTrivialDef(LiveInterval &SrcInt,
710                                                unsigned DstReg,
711                                                MachineInstr *CopyMI) {
712  SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
713  LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
714  assert(SrcLR != SrcInt.end() && "Live range not found!");
715  VNInfo *ValNo = SrcLR->valno;
716  if (ValNo->isPHIDef() || ValNo->isUnused())
717    return false;
718  MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
719  if (!DefMI)
720    return false;
721  assert(DefMI && "Defining instruction disappeared");
722  if (!DefMI->isAsCheapAsAMove())
723    return false;
724  if (!TII->isTriviallyReMaterializable(DefMI, AA))
725    return false;
726  bool SawStore = false;
727  if (!DefMI->isSafeToMove(TII, AA, SawStore))
728    return false;
729  const MCInstrDesc &MCID = DefMI->getDesc();
730  if (MCID.getNumDefs() != 1)
731    return false;
732  if (!DefMI->isImplicitDef()) {
733    // Make sure the copy destination register class fits the instruction
734    // definition register class. The mismatch can happen as a result of earlier
735    // extract_subreg, insert_subreg, subreg_to_reg coalescing.
736    const TargetRegisterClass *RC = TII->getRegClass(MCID, 0, TRI, *MF);
737    if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
738      if (MRI->getRegClass(DstReg) != RC)
739        return false;
740    } else if (!RC->contains(DstReg))
741      return false;
742  }
743
744  MachineBasicBlock *MBB = CopyMI->getParent();
745  MachineBasicBlock::iterator MII =
746    llvm::next(MachineBasicBlock::iterator(CopyMI));
747  TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
748  MachineInstr *NewMI = prior(MII);
749
750  // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
751  // We need to remember these so we can add intervals once we insert
752  // NewMI into SlotIndexes.
753  SmallVector<unsigned, 4> NewMIImplDefs;
754  for (unsigned i = NewMI->getDesc().getNumOperands(),
755         e = NewMI->getNumOperands(); i != e; ++i) {
756    MachineOperand &MO = NewMI->getOperand(i);
757    if (MO.isReg()) {
758      assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
759             TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
760      NewMIImplDefs.push_back(MO.getReg());
761    }
762  }
763
764  // CopyMI may have implicit operands, transfer them over to the newly
765  // rematerialized instruction. And update implicit def interval valnos.
766  for (unsigned i = CopyMI->getDesc().getNumOperands(),
767         e = CopyMI->getNumOperands(); i != e; ++i) {
768    MachineOperand &MO = CopyMI->getOperand(i);
769    if (MO.isReg()) {
770      assert(MO.isImplicit() && "No explicit operands after implict operands.");
771      // Discard VReg implicit defs.
772      if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
773        NewMI->addOperand(MO);
774      }
775    }
776  }
777
778  LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
779
780  SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
781  for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
782    unsigned Reg = NewMIImplDefs[i];
783    for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
784      if (LiveInterval *LI = LIS->getCachedRegUnit(*Units))
785        LI->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
786  }
787
788  CopyMI->eraseFromParent();
789  ErasedInstrs.insert(CopyMI);
790  DEBUG(dbgs() << "Remat: " << *NewMI);
791  ++NumReMats;
792
793  // The source interval can become smaller because we removed a use.
794  LIS->shrinkToUses(&SrcInt, &DeadDefs);
795  if (!DeadDefs.empty())
796    eliminateDeadDefs();
797
798  return true;
799}
800
801/// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
802/// values, it only removes local variables. When we have a copy like:
803///
804///   %vreg1 = COPY %vreg2<undef>
805///
806/// We delete the copy and remove the corresponding value number from %vreg1.
807/// Any uses of that value number are marked as <undef>.
808bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
809                                           const CoalescerPair &CP) {
810  SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
811  LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
812  if (SrcInt->liveAt(Idx))
813    return false;
814  LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
815  if (DstInt->liveAt(Idx))
816    return false;
817
818  // No intervals are live-in to CopyMI - it is undef.
819  if (CP.isFlipped())
820    DstInt = SrcInt;
821  SrcInt = 0;
822
823  VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
824  assert(DeadVNI && "No value defined in DstInt");
825  DstInt->removeValNo(DeadVNI);
826
827  // Find new undef uses.
828  for (MachineRegisterInfo::reg_nodbg_iterator
829         I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
830       I != E; ++I) {
831    MachineOperand &MO = I.getOperand();
832    if (MO.isDef() || MO.isUndef())
833      continue;
834    MachineInstr *MI = MO.getParent();
835    SlotIndex Idx = LIS->getInstructionIndex(MI);
836    if (DstInt->liveAt(Idx))
837      continue;
838    MO.setIsUndef(true);
839    DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
840  }
841  return true;
842}
843
844/// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
845/// update the subregister number if it is not zero. If DstReg is a
846/// physical register and the existing subregister number of the def / use
847/// being updated is not zero, make sure to set it to the correct physical
848/// subregister.
849void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
850                                          unsigned DstReg,
851                                          unsigned SubIdx) {
852  bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
853  LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
854
855  // Update LiveDebugVariables.
856  LDV->renameRegister(SrcReg, DstReg, SubIdx);
857
858  for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
859       MachineInstr *UseMI = I.skipInstruction();) {
860    SmallVector<unsigned,8> Ops;
861    bool Reads, Writes;
862    tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
863
864    // If SrcReg wasn't read, it may still be the case that DstReg is live-in
865    // because SrcReg is a sub-register.
866    if (DstInt && !Reads && SubIdx)
867      Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
868
869    // Replace SrcReg with DstReg in all UseMI operands.
870    for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
871      MachineOperand &MO = UseMI->getOperand(Ops[i]);
872
873      // Adjust <undef> flags in case of sub-register joins. We don't want to
874      // turn a full def into a read-modify-write sub-register def and vice
875      // versa.
876      if (SubIdx && MO.isDef())
877        MO.setIsUndef(!Reads);
878
879      if (DstIsPhys)
880        MO.substPhysReg(DstReg, *TRI);
881      else
882        MO.substVirtReg(DstReg, SubIdx, *TRI);
883    }
884
885    DEBUG({
886        dbgs() << "\t\tupdated: ";
887        if (!UseMI->isDebugValue())
888          dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
889        dbgs() << *UseMI;
890      });
891  }
892}
893
894/// canJoinPhys - Return true if a copy involving a physreg should be joined.
895bool RegisterCoalescer::canJoinPhys(CoalescerPair &CP) {
896  /// Always join simple intervals that are defined by a single copy from a
897  /// reserved register. This doesn't increase register pressure, so it is
898  /// always beneficial.
899  if (!RegClassInfo.isReserved(CP.getDstReg())) {
900    DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
901    return false;
902  }
903
904  LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
905  if (CP.isFlipped() && JoinVInt.containsOneValue())
906    return true;
907
908  DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
909  return false;
910}
911
912/// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
913/// which are the src/dst of the copy instruction CopyMI.  This returns true
914/// if the copy was successfully coalesced away. If it is not currently
915/// possible to coalesce this interval, but it may be possible if other
916/// things get coalesced, then it returns true by reference in 'Again'.
917bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
918
919  Again = false;
920  DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
921
922  CoalescerPair CP(*TRI);
923  if (!CP.setRegisters(CopyMI)) {
924    DEBUG(dbgs() << "\tNot coalescable.\n");
925    return false;
926  }
927
928  // Dead code elimination. This really should be handled by MachineDCE, but
929  // sometimes dead copies slip through, and we can't generate invalid live
930  // ranges.
931  if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
932    DEBUG(dbgs() << "\tCopy is dead.\n");
933    DeadDefs.push_back(CopyMI);
934    eliminateDeadDefs();
935    return true;
936  }
937
938  // Eliminate undefs.
939  if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
940    DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
941    LIS->RemoveMachineInstrFromMaps(CopyMI);
942    CopyMI->eraseFromParent();
943    return false;  // Not coalescable.
944  }
945
946  // Coalesced copies are normally removed immediately, but transformations
947  // like removeCopyByCommutingDef() can inadvertently create identity copies.
948  // When that happens, just join the values and remove the copy.
949  if (CP.getSrcReg() == CP.getDstReg()) {
950    LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
951    DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
952    LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(CopyMI));
953    if (VNInfo *DefVNI = LRQ.valueDefined()) {
954      VNInfo *ReadVNI = LRQ.valueIn();
955      assert(ReadVNI && "No value before copy and no <undef> flag.");
956      assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
957      LI.MergeValueNumberInto(DefVNI, ReadVNI);
958      DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
959    }
960    LIS->RemoveMachineInstrFromMaps(CopyMI);
961    CopyMI->eraseFromParent();
962    return true;
963  }
964
965  // Enforce policies.
966  if (CP.isPhys()) {
967    DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
968                 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
969                 << '\n');
970    if (!canJoinPhys(CP)) {
971      // Before giving up coalescing, if definition of source is defined by
972      // trivial computation, try rematerializing it.
973      if (!CP.isFlipped() &&
974          reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
975                                  CP.getDstReg(), CopyMI))
976        return true;
977      return false;
978    }
979  } else {
980    DEBUG({
981      dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
982             << " with ";
983      if (CP.getDstIdx() && CP.getSrcIdx())
984        dbgs() << PrintReg(CP.getDstReg()) << " in "
985               << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
986               << PrintReg(CP.getSrcReg()) << " in "
987               << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
988      else
989        dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
990               << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
991    });
992
993    // When possible, let DstReg be the larger interval.
994    if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
995                           LIS->getInterval(CP.getDstReg()).ranges.size())
996      CP.flip();
997  }
998
999  // Okay, attempt to join these two intervals.  On failure, this returns false.
1000  // Otherwise, if one of the intervals being joined is a physreg, this method
1001  // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1002  // been modified, so we can use this information below to update aliases.
1003  if (!joinIntervals(CP)) {
1004    // Coalescing failed.
1005
1006    // If definition of source is defined by trivial computation, try
1007    // rematerializing it.
1008    if (!CP.isFlipped() &&
1009        reMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()),
1010                                CP.getDstReg(), CopyMI))
1011      return true;
1012
1013    // If we can eliminate the copy without merging the live ranges, do so now.
1014    if (!CP.isPartial() && !CP.isPhys()) {
1015      if (adjustCopiesBackFrom(CP, CopyMI) ||
1016          removeCopyByCommutingDef(CP, CopyMI)) {
1017        LIS->RemoveMachineInstrFromMaps(CopyMI);
1018        CopyMI->eraseFromParent();
1019        DEBUG(dbgs() << "\tTrivial!\n");
1020        return true;
1021      }
1022    }
1023
1024    // Otherwise, we are unable to join the intervals.
1025    DEBUG(dbgs() << "\tInterference!\n");
1026    Again = true;  // May be possible to coalesce later.
1027    return false;
1028  }
1029
1030  // Coalescing to a virtual register that is of a sub-register class of the
1031  // other. Make sure the resulting register is set to the right register class.
1032  if (CP.isCrossClass()) {
1033    ++numCrossRCs;
1034    MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1035  }
1036
1037  // Removing sub-register copies can ease the register class constraints.
1038  // Make sure we attempt to inflate the register class of DstReg.
1039  if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1040    InflateRegs.push_back(CP.getDstReg());
1041
1042  // CopyMI has been erased by joinIntervals at this point. Remove it from
1043  // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1044  // to the work list. This keeps ErasedInstrs from growing needlessly.
1045  ErasedInstrs.erase(CopyMI);
1046
1047  // Rewrite all SrcReg operands to DstReg.
1048  // Also update DstReg operands to include DstIdx if it is set.
1049  if (CP.getDstIdx())
1050    updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1051  updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1052
1053  // SrcReg is guaranteed to be the register whose live interval that is
1054  // being merged.
1055  LIS->removeInterval(CP.getSrcReg());
1056
1057  // Update regalloc hint.
1058  TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1059
1060  DEBUG({
1061    dbgs() << "\tJoined. Result = " << PrintReg(CP.getDstReg(), TRI);
1062    if (!CP.isPhys())
1063      dbgs() << LIS->getInterval(CP.getDstReg());
1064     dbgs() << '\n';
1065  });
1066
1067  ++numJoins;
1068  return true;
1069}
1070
1071/// Attempt joining with a reserved physreg.
1072bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1073  assert(CP.isPhys() && "Must be a physreg copy");
1074  assert(RegClassInfo.isReserved(CP.getDstReg()) && "Not a reserved register");
1075  LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1076  DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1077               << '\n');
1078
1079  assert(CP.isFlipped() && RHS.containsOneValue() &&
1080         "Invalid join with reserved register");
1081
1082  // Optimization for reserved registers like ESP. We can only merge with a
1083  // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1084  // The live range of the reserved register will look like a set of dead defs
1085  // - we don't properly track the live range of reserved registers.
1086
1087  // Deny any overlapping intervals.  This depends on all the reserved
1088  // register live ranges to look like dead defs.
1089  for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1090    if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1091      DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1092      return false;
1093    }
1094
1095  // Skip any value computations, we are not adding new values to the
1096  // reserved register.  Also skip merging the live ranges, the reserved
1097  // register live range doesn't need to be accurate as long as all the
1098  // defs are there.
1099
1100  // We don't track kills for reserved registers.
1101  MRI->clearKillFlags(CP.getSrcReg());
1102
1103  return true;
1104}
1105
1106/// ComputeUltimateVN - Assuming we are going to join two live intervals,
1107/// compute what the resultant value numbers for each value in the input two
1108/// ranges will be.  This is complicated by copies between the two which can
1109/// and will commonly cause multiple value numbers to be merged into one.
1110///
1111/// VN is the value number that we're trying to resolve.  InstDefiningValue
1112/// keeps track of the new InstDefiningValue assignment for the result
1113/// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1114/// whether a value in this or other is a copy from the opposite set.
1115/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1116/// already been assigned.
1117///
1118/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1119/// contains the value number the copy is from.
1120///
1121static unsigned ComputeUltimateVN(VNInfo *VNI,
1122                                  SmallVector<VNInfo*, 16> &NewVNInfo,
1123                                  DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1124                                  DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1125                                  SmallVector<int, 16> &ThisValNoAssignments,
1126                                  SmallVector<int, 16> &OtherValNoAssignments) {
1127  unsigned VN = VNI->id;
1128
1129  // If the VN has already been computed, just return it.
1130  if (ThisValNoAssignments[VN] >= 0)
1131    return ThisValNoAssignments[VN];
1132  assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1133
1134  // If this val is not a copy from the other val, then it must be a new value
1135  // number in the destination.
1136  DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1137  if (I == ThisFromOther.end()) {
1138    NewVNInfo.push_back(VNI);
1139    return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1140  }
1141  VNInfo *OtherValNo = I->second;
1142
1143  // Otherwise, this *is* a copy from the RHS.  If the other side has already
1144  // been computed, return it.
1145  if (OtherValNoAssignments[OtherValNo->id] >= 0)
1146    return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1147
1148  // Mark this value number as currently being computed, then ask what the
1149  // ultimate value # of the other value is.
1150  ThisValNoAssignments[VN] = -2;
1151  unsigned UltimateVN =
1152    ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1153                      OtherValNoAssignments, ThisValNoAssignments);
1154  return ThisValNoAssignments[VN] = UltimateVN;
1155}
1156
1157
1158// Find out if we have something like
1159// A = X
1160// B = X
1161// if so, we can pretend this is actually
1162// A = X
1163// B = A
1164// which allows us to coalesce A and B.
1165// VNI is the definition of B. LR is the life range of A that includes
1166// the slot just before B. If we return true, we add "B = X" to DupCopies.
1167// This implies that A dominates B.
1168static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1169                                          const TargetRegisterInfo &tri,
1170                                          CoalescerPair &CP,
1171                                          VNInfo *VNI,
1172                                          VNInfo *OtherVNI,
1173                                     SmallVector<MachineInstr*, 8> &DupCopies) {
1174  // FIXME: This is very conservative. For example, we don't handle
1175  // physical registers.
1176
1177  MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1178
1179  if (!MI || CP.isPartial() || CP.isPhys())
1180    return false;
1181
1182  unsigned A = CP.getDstReg();
1183  if (!TargetRegisterInfo::isVirtualRegister(A))
1184    return false;
1185
1186  unsigned B = CP.getSrcReg();
1187  if (!TargetRegisterInfo::isVirtualRegister(B))
1188    return false;
1189
1190  MachineInstr *OtherMI = li.getInstructionFromIndex(OtherVNI->def);
1191  if (!OtherMI)
1192    return false;
1193
1194  if (MI->isImplicitDef()) {
1195    DupCopies.push_back(MI);
1196    return true;
1197  } else {
1198    if (!MI->isFullCopy())
1199      return false;
1200    unsigned Src = MI->getOperand(1).getReg();
1201    if (!TargetRegisterInfo::isVirtualRegister(Src))
1202      return false;
1203    if (!OtherMI->isFullCopy())
1204      return false;
1205    unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1206    if (!TargetRegisterInfo::isVirtualRegister(OtherSrc))
1207      return false;
1208
1209    if (Src != OtherSrc)
1210      return false;
1211
1212    // If the copies use two different value numbers of X, we cannot merge
1213    // A and B.
1214    LiveInterval &SrcInt = li.getInterval(Src);
1215    // getVNInfoBefore returns NULL for undef copies. In this case, the
1216    // optimization is still safe.
1217    if (SrcInt.getVNInfoBefore(OtherVNI->def) !=
1218        SrcInt.getVNInfoBefore(VNI->def))
1219      return false;
1220
1221    DupCopies.push_back(MI);
1222    return true;
1223  }
1224}
1225
1226/// joinIntervals - Attempt to join these two intervals.  On failure, this
1227/// returns false.
1228bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
1229  // Handle physreg joins separately.
1230  if (CP.isPhys())
1231    return joinReservedPhysReg(CP);
1232
1233  LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1234  DEBUG(dbgs() << "\t\tRHS = " << PrintReg(CP.getSrcReg()) << ' ' << RHS
1235               << '\n');
1236
1237  // Compute the final value assignment, assuming that the live ranges can be
1238  // coalesced.
1239  SmallVector<int, 16> LHSValNoAssignments;
1240  SmallVector<int, 16> RHSValNoAssignments;
1241  DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1242  DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1243  SmallVector<VNInfo*, 16> NewVNInfo;
1244
1245  SmallVector<MachineInstr*, 8> DupCopies;
1246  SmallVector<MachineInstr*, 8> DeadCopies;
1247
1248  LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1249  DEBUG(dbgs() << "\t\tLHS = " << PrintReg(CP.getDstReg(), TRI) << ' ' << LHS
1250               << '\n');
1251
1252  // Loop over the value numbers of the LHS, seeing if any are defined from
1253  // the RHS.
1254  for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1255       i != e; ++i) {
1256    VNInfo *VNI = *i;
1257    if (VNI->isUnused() || VNI->isPHIDef())
1258      continue;
1259    MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1260    assert(MI && "Missing def");
1261    if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1262      continue;
1263
1264    // Figure out the value # from the RHS.
1265    VNInfo *OtherVNI = RHS.getVNInfoBefore(VNI->def);
1266    // The copy could be to an aliased physreg.
1267    if (!OtherVNI)
1268      continue;
1269
1270    // DstReg is known to be a register in the LHS interval.  If the src is
1271    // from the RHS interval, we can use its value #.
1272    if (CP.isCoalescable(MI))
1273      DeadCopies.push_back(MI);
1274    else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1275                                            DupCopies))
1276      continue;
1277
1278    LHSValsDefinedFromRHS[VNI] = OtherVNI;
1279  }
1280
1281  // Loop over the value numbers of the RHS, seeing if any are defined from
1282  // the LHS.
1283  for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1284       i != e; ++i) {
1285    VNInfo *VNI = *i;
1286    if (VNI->isUnused() || VNI->isPHIDef())
1287      continue;
1288    MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1289    assert(MI && "Missing def");
1290    if (!MI->isCopyLike() && !MI->isImplicitDef()) // Src not defined by a copy?
1291      continue;
1292
1293    // Figure out the value # from the LHS.
1294    VNInfo *OtherVNI = LHS.getVNInfoBefore(VNI->def);
1295    // The copy could be to an aliased physreg.
1296    if (!OtherVNI)
1297      continue;
1298
1299    // DstReg is known to be a register in the RHS interval.  If the src is
1300    // from the LHS interval, we can use its value #.
1301    if (CP.isCoalescable(MI))
1302      DeadCopies.push_back(MI);
1303    else if (!RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, OtherVNI,
1304                                            DupCopies))
1305        continue;
1306
1307    RHSValsDefinedFromLHS[VNI] = OtherVNI;
1308  }
1309
1310  LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1311  RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1312  NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1313
1314  for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1315       i != e; ++i) {
1316    VNInfo *VNI = *i;
1317    unsigned VN = VNI->id;
1318    if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1319      continue;
1320    ComputeUltimateVN(VNI, NewVNInfo,
1321                      LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1322                      LHSValNoAssignments, RHSValNoAssignments);
1323  }
1324  for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1325       i != e; ++i) {
1326    VNInfo *VNI = *i;
1327    unsigned VN = VNI->id;
1328    if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1329      continue;
1330    // If this value number isn't a copy from the LHS, it's a new number.
1331    if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1332      NewVNInfo.push_back(VNI);
1333      RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1334      continue;
1335    }
1336
1337    ComputeUltimateVN(VNI, NewVNInfo,
1338                      RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1339                      RHSValNoAssignments, LHSValNoAssignments);
1340  }
1341
1342  // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1343  // interval lists to see if these intervals are coalescable.
1344  LiveInterval::const_iterator I = LHS.begin();
1345  LiveInterval::const_iterator IE = LHS.end();
1346  LiveInterval::const_iterator J = RHS.begin();
1347  LiveInterval::const_iterator JE = RHS.end();
1348
1349  // Collect interval end points that will no longer be kills.
1350  SmallVector<MachineInstr*, 8> LHSOldKills;
1351  SmallVector<MachineInstr*, 8> RHSOldKills;
1352
1353  // Skip ahead until the first place of potential sharing.
1354  if (I != IE && J != JE) {
1355    if (I->start < J->start) {
1356      I = std::upper_bound(I, IE, J->start);
1357      if (I != LHS.begin()) --I;
1358    } else if (J->start < I->start) {
1359      J = std::upper_bound(J, JE, I->start);
1360      if (J != RHS.begin()) --J;
1361    }
1362  }
1363
1364  while (I != IE && J != JE) {
1365    // Determine if these two live ranges overlap.
1366    // If so, check value # info to determine if they are really different.
1367    if (I->end > J->start && J->end > I->start) {
1368      // If the live range overlap will map to the same value number in the
1369      // result liverange, we can still coalesce them.  If not, we can't.
1370      if (LHSValNoAssignments[I->valno->id] !=
1371          RHSValNoAssignments[J->valno->id])
1372        return false;
1373
1374      // Extended live ranges should no longer be killed.
1375      if (!I->end.isBlock() && I->end < J->end)
1376        if (MachineInstr *MI = LIS->getInstructionFromIndex(I->end))
1377          LHSOldKills.push_back(MI);
1378      if (!J->end.isBlock() && J->end < I->end)
1379        if (MachineInstr *MI = LIS->getInstructionFromIndex(J->end))
1380          RHSOldKills.push_back(MI);
1381    }
1382
1383    if (I->end < J->end)
1384      ++I;
1385    else
1386      ++J;
1387  }
1388
1389  // Update kill info. Some live ranges are extended due to copy coalescing.
1390  for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1391         E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1392    VNInfo *VNI = I->first;
1393    unsigned LHSValID = LHSValNoAssignments[VNI->id];
1394    if (VNI->hasPHIKill())
1395      NewVNInfo[LHSValID]->setHasPHIKill(true);
1396  }
1397
1398  // Update kill info. Some live ranges are extended due to copy coalescing.
1399  for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1400         E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1401    VNInfo *VNI = I->first;
1402    unsigned RHSValID = RHSValNoAssignments[VNI->id];
1403    if (VNI->hasPHIKill())
1404      NewVNInfo[RHSValID]->setHasPHIKill(true);
1405  }
1406
1407  // Clear kill flags where live ranges are extended.
1408  while (!LHSOldKills.empty())
1409    LHSOldKills.pop_back_val()->clearRegisterKills(LHS.reg, TRI);
1410  while (!RHSOldKills.empty())
1411    RHSOldKills.pop_back_val()->clearRegisterKills(RHS.reg, TRI);
1412
1413  if (LHSValNoAssignments.empty())
1414    LHSValNoAssignments.push_back(-1);
1415  if (RHSValNoAssignments.empty())
1416    RHSValNoAssignments.push_back(-1);
1417
1418  // Now erase all the redundant copies.
1419  for (unsigned i = 0, e = DeadCopies.size(); i != e; ++i) {
1420    MachineInstr *MI = DeadCopies[i];
1421    if (!ErasedInstrs.insert(MI))
1422      continue;
1423    DEBUG(dbgs() << "\t\terased:\t" << LIS->getInstructionIndex(MI)
1424                 << '\t' << *MI);
1425    LIS->RemoveMachineInstrFromMaps(MI);
1426    MI->eraseFromParent();
1427  }
1428
1429  SmallVector<unsigned, 8> SourceRegisters;
1430  for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1431         E = DupCopies.end(); I != E; ++I) {
1432    MachineInstr *MI = *I;
1433    if (!ErasedInstrs.insert(MI))
1434      continue;
1435
1436    // If MI is a copy, then we have pretended that the assignment to B in
1437    // A = X
1438    // B = X
1439    // was actually a copy from A. Now that we decided to coalesce A and B,
1440    // transform the code into
1441    // A = X
1442    // In the case of the implicit_def, we just have to remove it.
1443    if (!MI->isImplicitDef()) {
1444      unsigned Src = MI->getOperand(1).getReg();
1445      SourceRegisters.push_back(Src);
1446    }
1447    LIS->RemoveMachineInstrFromMaps(MI);
1448    MI->eraseFromParent();
1449  }
1450
1451  // If B = X was the last use of X in a liverange, we have to shrink it now
1452  // that B = X is gone.
1453  for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1454         E = SourceRegisters.end(); I != E; ++I) {
1455    LIS->shrinkToUses(&LIS->getInterval(*I));
1456  }
1457
1458  // If we get here, we know that we can coalesce the live ranges.  Ask the
1459  // intervals to coalesce themselves now.
1460  LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1461           MRI);
1462  return true;
1463}
1464
1465namespace {
1466  // DepthMBBCompare - Comparison predicate that sort first based on the loop
1467  // depth of the basic block (the unsigned), and then on the MBB number.
1468  struct DepthMBBCompare {
1469    typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1470    bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1471      // Deeper loops first
1472      if (LHS.first != RHS.first)
1473        return LHS.first > RHS.first;
1474
1475      // Prefer blocks that are more connected in the CFG. This takes care of
1476      // the most difficult copies first while intervals are short.
1477      unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1478      unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1479      if (cl != cr)
1480        return cl > cr;
1481
1482      // As a last resort, sort by block number.
1483      return LHS.second->getNumber() < RHS.second->getNumber();
1484    }
1485  };
1486}
1487
1488// Try joining WorkList copies starting from index From.
1489// Null out any successful joins.
1490bool RegisterCoalescer::copyCoalesceWorkList(unsigned From) {
1491  assert(From <= WorkList.size() && "Out of range");
1492  bool Progress = false;
1493  for (unsigned i = From, e = WorkList.size(); i != e; ++i) {
1494    if (!WorkList[i])
1495      continue;
1496    // Skip instruction pointers that have already been erased, for example by
1497    // dead code elimination.
1498    if (ErasedInstrs.erase(WorkList[i])) {
1499      WorkList[i] = 0;
1500      continue;
1501    }
1502    bool Again = false;
1503    bool Success = joinCopy(WorkList[i], Again);
1504    Progress |= Success;
1505    if (Success || !Again)
1506      WorkList[i] = 0;
1507  }
1508  return Progress;
1509}
1510
1511void
1512RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
1513  DEBUG(dbgs() << MBB->getName() << ":\n");
1514
1515  // Collect all copy-like instructions in MBB. Don't start coalescing anything
1516  // yet, it might invalidate the iterator.
1517  const unsigned PrevSize = WorkList.size();
1518  for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1519       MII != E; ++MII)
1520    if (MII->isCopyLike())
1521      WorkList.push_back(MII);
1522
1523  // Try coalescing the collected copies immediately, and remove the nulls.
1524  // This prevents the WorkList from getting too large since most copies are
1525  // joinable on the first attempt.
1526  if (copyCoalesceWorkList(PrevSize))
1527    WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
1528                               (MachineInstr*)0), WorkList.end());
1529}
1530
1531void RegisterCoalescer::joinAllIntervals() {
1532  DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1533  assert(WorkList.empty() && "Old data still around.");
1534
1535  if (Loops->empty()) {
1536    // If there are no loops in the function, join intervals in function order.
1537    for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1538         I != E; ++I)
1539      copyCoalesceInMBB(I);
1540  } else {
1541    // Otherwise, join intervals in inner loops before other intervals.
1542    // Unfortunately we can't just iterate over loop hierarchy here because
1543    // there may be more MBB's than BB's.  Collect MBB's for sorting.
1544
1545    // Join intervals in the function prolog first. We want to join physical
1546    // registers with virtual registers before the intervals got too long.
1547    std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1548    for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1549      MachineBasicBlock *MBB = I;
1550      MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1551    }
1552
1553    // Sort by loop depth.
1554    std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1555
1556    // Finally, join intervals in loop nest order.
1557    for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1558      copyCoalesceInMBB(MBBs[i].second);
1559  }
1560
1561  // Joining intervals can allow other intervals to be joined.  Iteratively join
1562  // until we make no progress.
1563  while (copyCoalesceWorkList())
1564    /* empty */ ;
1565}
1566
1567void RegisterCoalescer::releaseMemory() {
1568  ErasedInstrs.clear();
1569  WorkList.clear();
1570  DeadDefs.clear();
1571  InflateRegs.clear();
1572}
1573
1574bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1575  MF = &fn;
1576  MRI = &fn.getRegInfo();
1577  TM = &fn.getTarget();
1578  TRI = TM->getRegisterInfo();
1579  TII = TM->getInstrInfo();
1580  LIS = &getAnalysis<LiveIntervals>();
1581  LDV = &getAnalysis<LiveDebugVariables>();
1582  AA = &getAnalysis<AliasAnalysis>();
1583  Loops = &getAnalysis<MachineLoopInfo>();
1584
1585  DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1586               << "********** Function: "
1587               << ((Value*)MF->getFunction())->getName() << '\n');
1588
1589  if (VerifyCoalescing)
1590    MF->verify(this, "Before register coalescing");
1591
1592  RegClassInfo.runOnMachineFunction(fn);
1593
1594  // Join (coalesce) intervals if requested.
1595  if (EnableJoining)
1596    joinAllIntervals();
1597
1598  // After deleting a lot of copies, register classes may be less constrained.
1599  // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
1600  // DPR inflation.
1601  array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1602  InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1603                    InflateRegs.end());
1604  DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1605  for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1606    unsigned Reg = InflateRegs[i];
1607    if (MRI->reg_nodbg_empty(Reg))
1608      continue;
1609    if (MRI->recomputeRegClass(Reg, *TM)) {
1610      DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1611                   << MRI->getRegClass(Reg)->getName() << '\n');
1612      ++NumInflated;
1613    }
1614  }
1615
1616  DEBUG(dump());
1617  DEBUG(LDV->dump());
1618  if (VerifyCoalescing)
1619    MF->verify(this, "After register coalescing");
1620  return true;
1621}
1622
1623/// print - Implement the dump method.
1624void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
1625   LIS->print(O, m);
1626}
1627