RegisterCoalescer.cpp revision 3ed4dee530984b7087dd3bbf4cfd8a3f1947c8e0
13c827367444ee418f129b2c238299f49d3264554Jarkko Poyry//===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
23c827367444ee418f129b2c238299f49d3264554Jarkko Poyry//
33c827367444ee418f129b2c238299f49d3264554Jarkko Poyry//                     The LLVM Compiler Infrastructure
43c827367444ee418f129b2c238299f49d3264554Jarkko Poyry//
53c827367444ee418f129b2c238299f49d3264554Jarkko Poyry// This file is distributed under the University of Illinois Open Source
63c827367444ee418f129b2c238299f49d3264554Jarkko Poyry// License. See LICENSE.TXT for details.
73c827367444ee418f129b2c238299f49d3264554Jarkko Poyry//
83c827367444ee418f129b2c238299f49d3264554Jarkko Poyry//===----------------------------------------------------------------------===//
93c827367444ee418f129b2c238299f49d3264554Jarkko Poyry//
103c827367444ee418f129b2c238299f49d3264554Jarkko Poyry// This file implements the generic RegisterCoalescer interface which
113c827367444ee418f129b2c238299f49d3264554Jarkko Poyry// is used as the common interface used by all clients and
123c827367444ee418f129b2c238299f49d3264554Jarkko Poyry// implementations of register coalescing.
133c827367444ee418f129b2c238299f49d3264554Jarkko Poyry//
143c827367444ee418f129b2c238299f49d3264554Jarkko Poyry//===----------------------------------------------------------------------===//
153c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
163c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#define DEBUG_TYPE "regalloc"
173c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "RegisterCoalescer.h"
183c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "LiveDebugVariables.h"
193c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "RegisterClassInfo.h"
203c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "VirtRegMap.h"
213c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
223c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Pass.h"
233c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Value.h"
243c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/CodeGen/LiveIntervalAnalysis.h"
253c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/CodeGen/MachineInstr.h"
263c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/CodeGen/MachineRegisterInfo.h"
273c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Target/TargetInstrInfo.h"
283c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Target/TargetRegisterInfo.h"
293c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/CodeGen/LiveIntervalAnalysis.h"
303c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Analysis/AliasAnalysis.h"
313c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/CodeGen/MachineFrameInfo.h"
323c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/CodeGen/MachineInstr.h"
333c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/CodeGen/MachineLoopInfo.h"
343c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/CodeGen/MachineRegisterInfo.h"
353c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/CodeGen/Passes.h"
363c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Target/TargetInstrInfo.h"
373c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Target/TargetMachine.h"
383c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Target/TargetOptions.h"
393c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Support/CommandLine.h"
403c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Support/Debug.h"
413c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Support/ErrorHandling.h"
423c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/Support/raw_ostream.h"
433c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/ADT/OwningPtr.h"
443c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/ADT/SmallSet.h"
453c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/ADT/Statistic.h"
463c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include "llvm/ADT/STLExtras.h"
473c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include <algorithm>
483c827367444ee418f129b2c238299f49d3264554Jarkko Poyry#include <cmath>
493c827367444ee418f129b2c238299f49d3264554Jarkko Poyryusing namespace llvm;
503c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
513c827367444ee418f129b2c238299f49d3264554Jarkko PoyrySTATISTIC(numJoins    , "Number of interval joins performed");
523c827367444ee418f129b2c238299f49d3264554Jarkko PoyrySTATISTIC(numCrossRCs , "Number of cross class joins performed");
533c827367444ee418f129b2c238299f49d3264554Jarkko PoyrySTATISTIC(numCommutes , "Number of instruction commuting performed");
543c827367444ee418f129b2c238299f49d3264554Jarkko PoyrySTATISTIC(numExtends  , "Number of copies extended");
553c827367444ee418f129b2c238299f49d3264554Jarkko PoyrySTATISTIC(NumReMats   , "Number of instructions re-materialized");
563c827367444ee418f129b2c238299f49d3264554Jarkko PoyrySTATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
573c827367444ee418f129b2c238299f49d3264554Jarkko PoyrySTATISTIC(numAborts   , "Number of times interval joining aborted");
583c827367444ee418f129b2c238299f49d3264554Jarkko PoyrySTATISTIC(NumInflated , "Number of register classes inflated");
593c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
603c827367444ee418f129b2c238299f49d3264554Jarkko Poyrystatic cl::opt<bool>
613c827367444ee418f129b2c238299f49d3264554Jarkko PoyryEnableJoining("join-liveintervals",
623c827367444ee418f129b2c238299f49d3264554Jarkko Poyry              cl::desc("Coalesce copies (default=true)"),
633c827367444ee418f129b2c238299f49d3264554Jarkko Poyry              cl::init(true));
643c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
653c827367444ee418f129b2c238299f49d3264554Jarkko Poyrystatic cl::opt<bool>
663c827367444ee418f129b2c238299f49d3264554Jarkko PoyryDisableCrossClassJoin("disable-cross-class-join",
673c827367444ee418f129b2c238299f49d3264554Jarkko Poyry               cl::desc("Avoid coalescing cross register class copies"),
683c827367444ee418f129b2c238299f49d3264554Jarkko Poyry               cl::init(false), cl::Hidden);
693c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
703c827367444ee418f129b2c238299f49d3264554Jarkko Poyrystatic cl::opt<bool>
713c827367444ee418f129b2c238299f49d3264554Jarkko PoyryEnablePhysicalJoin("join-physregs",
723c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                   cl::desc("Join physical register copies"),
733c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                   cl::init(false), cl::Hidden);
743c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
753c827367444ee418f129b2c238299f49d3264554Jarkko Poyrystatic cl::opt<bool>
763c827367444ee418f129b2c238299f49d3264554Jarkko PoyryVerifyCoalescing("verify-coalescing",
773c827367444ee418f129b2c238299f49d3264554Jarkko Poyry         cl::desc("Verify machine instrs before and after register coalescing"),
783c827367444ee418f129b2c238299f49d3264554Jarkko Poyry         cl::Hidden);
793c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
803c827367444ee418f129b2c238299f49d3264554Jarkko Poyrynamespace {
813c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  class RegisterCoalescer : public MachineFunctionPass {
823c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    MachineFunction* MF;
833c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    MachineRegisterInfo* MRI;
843c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    const TargetMachine* TM;
853c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    const TargetRegisterInfo* TRI;
863c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    const TargetInstrInfo* TII;
873c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    LiveIntervals *LIS;
883c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    LiveDebugVariables *LDV;
893c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    const MachineLoopInfo* Loops;
903c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    AliasAnalysis *AA;
913c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    RegisterClassInfo RegClassInfo;
923c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
933c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// JoinedCopies - Keep track of copies eliminated due to coalescing.
943c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    ///
953c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    SmallPtrSet<MachineInstr*, 32> JoinedCopies;
963c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
973c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// ReMatCopies - Keep track of copies eliminated due to remat.
983c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    ///
993c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    SmallPtrSet<MachineInstr*, 32> ReMatCopies;
1003c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1013c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// ReMatDefs - Keep track of definition instructions which have
1023c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// been remat'ed.
1033c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    SmallPtrSet<MachineInstr*, 8> ReMatDefs;
1043c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1053c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// joinIntervals - join compatible live intervals
1063c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    void joinIntervals();
1073c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1083c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// CopyCoalesceInMBB - Coalesce copies in the specified MBB, putting
1093c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// copies that cannot yet be coalesced into the "TryAgain" list.
1103c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    void CopyCoalesceInMBB(MachineBasicBlock *MBB,
1113c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                           std::vector<MachineInstr*> &TryAgain);
1123c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1133c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1143c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// which are the src/dst of the copy instruction CopyMI.  This returns
1153c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// true if the copy was successfully coalesced away. If it is not
1163c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// currently possible to coalesce this interval, but it may be possible if
1173c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// other things get coalesced, then it returns true by reference in
1183c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// 'Again'.
1193c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool JoinCopy(MachineInstr *TheCopy, bool &Again);
1203c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1213c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// JoinIntervals - Attempt to join these two intervals.  On failure, this
1223c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// returns false.  The output "SrcInt" will not have been modified, so we
1233c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// can use this information below to update aliases.
1243c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool JoinIntervals(CoalescerPair &CP);
1253c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1263c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
1273c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// the source value number is defined by a copy from the destination reg
1283c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// see if we can merge these two destination reg valno# into a single
1293c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// value number, eliminating a copy.
1303c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool AdjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
1313c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1323c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// HasOtherReachingDefs - Return true if there are definitions of IntB
1333c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// other than BValNo val# that can reach uses of AValno val# of IntA.
1343c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool HasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
1353c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                              VNInfo *AValNo, VNInfo *BValNo);
1363c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1373c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy.
1383c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// If the source value number is defined by a commutable instruction and
1393c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// its other operand is coalesced to the copy dest register, see if we
1403c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// can transform the copy into a noop by commuting the definition.
1413c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool RemoveCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
1423c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1433c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// ReMaterializeTrivialDef - If the source of a copy is defined by a
1443c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// trivial computation, replace the copy by rematerialize the definition.
1453c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// If PreserveSrcInt is true, make sure SrcInt is valid after the call.
1463c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool ReMaterializeTrivialDef(LiveInterval &SrcInt, bool PreserveSrcInt,
1473c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                                 unsigned DstReg, MachineInstr *CopyMI);
1483c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1493c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// shouldJoinPhys - Return true if a physreg copy should be joined.
1503c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool shouldJoinPhys(CoalescerPair &CP);
1513c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1523c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1533c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// two virtual registers from different register classes.
1543c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool isWinToJoinCrossClass(unsigned SrcReg,
1553c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                               unsigned DstReg,
1563c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                               const TargetRegisterClass *SrcRC,
1573c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                               const TargetRegisterClass *DstRC,
1583c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                               const TargetRegisterClass *NewRC);
1593c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1603c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
1613c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// update the subregister number if it is not zero. If DstReg is a
1623c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// physical register and the existing subregister number of the def / use
1633c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// being updated is not zero, make sure to set it to the correct physical
1643c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// subregister.
1653c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    void UpdateRegDefsUses(const CoalescerPair &CP);
1663c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1673c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// RemoveDeadDef - If a def of a live interval is now determined dead,
1683c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// remove the val# it defines. If the live interval becomes empty, remove
1693c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// it as well.
1703c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI);
1713c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1723c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// markAsJoined - Remember that CopyMI has already been joined.
1733c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    void markAsJoined(MachineInstr *CopyMI);
1743c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1753c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// eliminateUndefCopy - Handle copies of undef values.
1763c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
1773c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1783c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  public:
1793c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    static char ID; // Class identification, replacement for typeinfo
1803c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    RegisterCoalescer() : MachineFunctionPass(ID) {
1813c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
1823c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    }
1833c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1843c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1853c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1863c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    virtual void releaseMemory();
1873c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1883c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// runOnMachineFunction - pass entry point
1893c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    virtual bool runOnMachineFunction(MachineFunction&);
1903c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1913c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    /// print - Implement the dump method.
1923c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    virtual void print(raw_ostream &O, const Module* = 0) const;
1933c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  };
1943c827367444ee418f129b2c238299f49d3264554Jarkko Poyry} /// end anonymous namespace
1953c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1963c827367444ee418f129b2c238299f49d3264554Jarkko Poyrychar &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
1973c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
1983c827367444ee418f129b2c238299f49d3264554Jarkko PoyryINITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
1993c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                      "Simple Register Coalescing", false, false)
2003c827367444ee418f129b2c238299f49d3264554Jarkko PoyryINITIALIZE_PASS_DEPENDENCY(LiveIntervals)
2013c827367444ee418f129b2c238299f49d3264554Jarkko PoyryINITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
2023c827367444ee418f129b2c238299f49d3264554Jarkko PoyryINITIALIZE_PASS_DEPENDENCY(SlotIndexes)
2033c827367444ee418f129b2c238299f49d3264554Jarkko PoyryINITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
2043c827367444ee418f129b2c238299f49d3264554Jarkko PoyryINITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2053c827367444ee418f129b2c238299f49d3264554Jarkko PoyryINITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
2063c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                    "Simple Register Coalescing", false, false)
2073c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2083c827367444ee418f129b2c238299f49d3264554Jarkko Poyrychar RegisterCoalescer::ID = 0;
2093c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2103c827367444ee418f129b2c238299f49d3264554Jarkko Poyrystatic unsigned compose(const TargetRegisterInfo &tri, unsigned a, unsigned b) {
2113c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (!a) return b;
2123c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (!b) return a;
2133c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  return tri.composeSubRegIndices(a, b);
2143c827367444ee418f129b2c238299f49d3264554Jarkko Poyry}
2153c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2163c827367444ee418f129b2c238299f49d3264554Jarkko Poyrystatic bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
2173c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                        unsigned &Src, unsigned &Dst,
2183c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                        unsigned &SrcSub, unsigned &DstSub) {
2193c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (MI->isCopy()) {
2203c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    Dst = MI->getOperand(0).getReg();
2213c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    DstSub = MI->getOperand(0).getSubReg();
2223c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    Src = MI->getOperand(1).getReg();
2233c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    SrcSub = MI->getOperand(1).getSubReg();
2243c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  } else if (MI->isSubregToReg()) {
2253c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    Dst = MI->getOperand(0).getReg();
2263c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    DstSub = compose(tri, MI->getOperand(0).getSubReg(),
2273c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                     MI->getOperand(3).getImm());
2283c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    Src = MI->getOperand(2).getReg();
2293c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    SrcSub = MI->getOperand(2).getSubReg();
2303c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  } else
2313c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
2323c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  return true;
2333c827367444ee418f129b2c238299f49d3264554Jarkko Poyry}
2343c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2353c827367444ee418f129b2c238299f49d3264554Jarkko Poyrybool CoalescerPair::setRegisters(const MachineInstr *MI) {
2363c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  SrcReg = DstReg = SubIdx = 0;
2373c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  NewRC = 0;
2383c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  Flipped = CrossClass = false;
2393c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2403c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  unsigned Src, Dst, SrcSub, DstSub;
2413c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
2423c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
2433c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  Partial = SrcSub || DstSub;
2443c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2453c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // If one register is a physreg, it must be Dst.
2463c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (TargetRegisterInfo::isPhysicalRegister(Src)) {
2473c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (TargetRegisterInfo::isPhysicalRegister(Dst))
2483c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      return false;
2493c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    std::swap(Src, Dst);
2503c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    std::swap(SrcSub, DstSub);
2513c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    Flipped = true;
2523c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  }
2533c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2543c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2553c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2563c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
2573c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // Eliminate DstSub on a physreg.
2583c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (DstSub) {
2593c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      Dst = TRI.getSubReg(Dst, DstSub);
2603c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      if (!Dst) return false;
2613c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      DstSub = 0;
2623c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    }
2633c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2643c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // Eliminate SrcSub by picking a corresponding Dst superregister.
2653c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (SrcSub) {
2663c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
2673c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      if (!Dst) return false;
2683c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      SrcSub = 0;
2693c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    } else if (!MRI.getRegClass(Src)->contains(Dst)) {
2703c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      return false;
2713c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    }
2723c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  } else {
2733c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // Both registers are virtual.
2743c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2753c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // Both registers have subreg indices.
2763c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (SrcSub && DstSub) {
2773c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      // For now we only handle the case of identical indices in commensurate
2783c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      // registers: Dreg:ssub_1 + Dreg:ssub_1 -> Dreg
2793c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      // FIXME: Handle Qreg:ssub_3 + Dreg:ssub_1 as QReg:dsub_1 + Dreg.
2803c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      if (SrcSub != DstSub)
2813c827367444ee418f129b2c238299f49d3264554Jarkko Poyry        return false;
2823c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
2833c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
2843c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      if (!TRI.getCommonSubClass(DstRC, SrcRC))
2853c827367444ee418f129b2c238299f49d3264554Jarkko Poyry        return false;
2863c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      SrcSub = DstSub = 0;
2873c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    }
2883c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2893c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // There can be no SrcSub.
2903c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (SrcSub) {
2913c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      std::swap(Src, Dst);
2923c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      DstSub = SrcSub;
2933c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      SrcSub = 0;
2943c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      assert(!Flipped && "Unexpected flip");
2953c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      Flipped = true;
2963c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    }
2973c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
2983c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // Find the new register class.
2993c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
3003c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
3013c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (DstSub)
3023c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
3033c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    else
3043c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
3053c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (!NewRC)
3063c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      return false;
3073c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    CrossClass = NewRC != DstRC || NewRC != SrcRC;
3083c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  }
3093c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Check our invariants
3103c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
3113c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
3123c827367444ee418f129b2c238299f49d3264554Jarkko Poyry         "Cannot have a physical SubIdx");
3133c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  SrcReg = Src;
3143c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  DstReg = Dst;
3153c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  SubIdx = DstSub;
3163c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  return true;
3173c827367444ee418f129b2c238299f49d3264554Jarkko Poyry}
3183c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
3193c827367444ee418f129b2c238299f49d3264554Jarkko Poyrybool CoalescerPair::flip() {
3203c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (SubIdx || TargetRegisterInfo::isPhysicalRegister(DstReg))
3213c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
3223c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  std::swap(SrcReg, DstReg);
3233c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  Flipped = !Flipped;
3243c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  return true;
3253c827367444ee418f129b2c238299f49d3264554Jarkko Poyry}
3263c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
3273c827367444ee418f129b2c238299f49d3264554Jarkko Poyrybool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
3283c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (!MI)
3293c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
3303c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  unsigned Src, Dst, SrcSub, DstSub;
3313c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
3323c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
3333c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
3343c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Find the virtual register that is SrcReg.
3353c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (Dst == SrcReg) {
3363c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    std::swap(Src, Dst);
3373c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    std::swap(SrcSub, DstSub);
3383c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  } else if (Src != SrcReg) {
3393c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
3403c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  }
3413c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
3423c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Now check that Dst matches DstReg.
3433c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
3443c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (!TargetRegisterInfo::isPhysicalRegister(Dst))
3453c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      return false;
3463c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    assert(!SubIdx && "Inconsistent CoalescerPair state.");
3473c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // DstSub could be set for a physreg from INSERT_SUBREG.
3483c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (DstSub)
3493c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      Dst = TRI.getSubReg(Dst, DstSub);
3503c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // Full copy of Src.
3513c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (!SrcSub)
3523c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      return DstReg == Dst;
3533c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // This is a partial register copy. Check that the parts match.
3543c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return TRI.getSubReg(DstReg, SrcSub) == Dst;
3553c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  } else {
3563c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // DstReg is virtual.
3573c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (DstReg != Dst)
3583c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      return false;
3593c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // Registers match, do the subregisters line up?
3603c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return compose(TRI, SubIdx, SrcSub) == DstSub;
3613c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  }
3623c827367444ee418f129b2c238299f49d3264554Jarkko Poyry}
3633c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
3643c827367444ee418f129b2c238299f49d3264554Jarkko Poyryvoid RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
3653c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.setPreservesCFG();
3663c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.addRequired<AliasAnalysis>();
3673c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.addRequired<LiveIntervals>();
3683c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.addPreserved<LiveIntervals>();
3693c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.addRequired<LiveDebugVariables>();
3703c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.addPreserved<LiveDebugVariables>();
3713c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.addPreserved<SlotIndexes>();
3723c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.addRequired<MachineLoopInfo>();
3733c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.addPreserved<MachineLoopInfo>();
3743c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  AU.addPreservedID(MachineDominatorsID);
3753c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  MachineFunctionPass::getAnalysisUsage(AU);
3763c827367444ee418f129b2c238299f49d3264554Jarkko Poyry}
3773c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
3783c827367444ee418f129b2c238299f49d3264554Jarkko Poyryvoid RegisterCoalescer::markAsJoined(MachineInstr *CopyMI) {
3793c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  /// Joined copies are not deleted immediately, but kept in JoinedCopies.
3803c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  JoinedCopies.insert(CopyMI);
3813c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
3823c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  /// Mark all register operands of CopyMI as <undef> so they won't affect dead
3833c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  /// code elimination.
3843c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  for (MachineInstr::mop_iterator I = CopyMI->operands_begin(),
3853c827367444ee418f129b2c238299f49d3264554Jarkko Poyry       E = CopyMI->operands_end(); I != E; ++I)
3863c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (I->isReg())
3873c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      I->setIsUndef(true);
3883c827367444ee418f129b2c238299f49d3264554Jarkko Poyry}
3893c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
3903c827367444ee418f129b2c238299f49d3264554Jarkko Poyry/// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
3913c827367444ee418f129b2c238299f49d3264554Jarkko Poyry/// being the source and IntB being the dest, thus this defines a value number
3923c827367444ee418f129b2c238299f49d3264554Jarkko Poyry/// in IntB.  If the source value number (in IntA) is defined by a copy from B,
3933c827367444ee418f129b2c238299f49d3264554Jarkko Poyry/// see if we can merge these two pieces of B into a single value number,
3943c827367444ee418f129b2c238299f49d3264554Jarkko Poyry/// eliminating a copy.  For example:
3953c827367444ee418f129b2c238299f49d3264554Jarkko Poyry///
3963c827367444ee418f129b2c238299f49d3264554Jarkko Poyry///  A3 = B0
3973c827367444ee418f129b2c238299f49d3264554Jarkko Poyry///    ...
3983c827367444ee418f129b2c238299f49d3264554Jarkko Poyry///  B1 = A3      <- this copy
3993c827367444ee418f129b2c238299f49d3264554Jarkko Poyry///
4003c827367444ee418f129b2c238299f49d3264554Jarkko Poyry/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
4013c827367444ee418f129b2c238299f49d3264554Jarkko Poyry/// value number to be replaced with B0 (which simplifies the B liveinterval).
4023c827367444ee418f129b2c238299f49d3264554Jarkko Poyry///
4033c827367444ee418f129b2c238299f49d3264554Jarkko Poyry/// This returns true if an interval was modified.
4043c827367444ee418f129b2c238299f49d3264554Jarkko Poyry///
4053c827367444ee418f129b2c238299f49d3264554Jarkko Poyrybool RegisterCoalescer::AdjustCopiesBackFrom(const CoalescerPair &CP,
4063c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                                                    MachineInstr *CopyMI) {
4073c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Bail if there is no dst interval - can happen when merging physical subreg
4083c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // operations.
4093c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (!LIS->hasInterval(CP.getDstReg()))
4103c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
4113c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4123c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  LiveInterval &IntA =
4133c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
4143c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  LiveInterval &IntB =
4153c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
4163c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
4173c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4183c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // BValNo is a value number in B that is defined by a copy from A.  'B3' in
4193c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // the example above.
4203c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
4213c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (BLR == IntB.end()) return false;
4223c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  VNInfo *BValNo = BLR->valno;
4233c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4243c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Get the location that B is defined at.  Two options: either this value has
4253c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // an unknown definition point or it is defined at CopyIdx.  If unknown, we
4263c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // can't process it.
4273c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (BValNo->def != CopyIdx) return false;
4283c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4293c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // AValNo is the value number in A that defines the copy, A3 in the example.
4303c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
4313c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyUseIdx);
4323c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // The live range might not exist after fun with physreg coalescing.
4333c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (ALR == IntA.end()) return false;
4343c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  VNInfo *AValNo = ALR->valno;
4353c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4363c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // If AValNo is defined as a copy from IntB, we can potentially process this.
4373c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Get the instruction that defines this value number.
4383c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
4393c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (!CP.isCoalescable(ACopyMI))
4403c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
4413c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4423c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Get the LiveRange in IntB that this value number starts with.
4433c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  LiveInterval::iterator ValLR =
4443c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    IntB.FindLiveRangeContaining(AValNo->def.getPrevSlot());
4453c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (ValLR == IntB.end())
4463c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
4473c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4483c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Make sure that the end of the live range is inside the same block as
4493c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // CopyMI.
4503c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  MachineInstr *ValLREndInst =
4513c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    LIS->getInstructionFromIndex(ValLR->end.getPrevSlot());
4523c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (!ValLREndInst || ValLREndInst->getParent() != CopyMI->getParent())
4533c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    return false;
4543c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4553c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Okay, we now know that ValLR ends in the same block that the CopyMI
4563c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // live-range starts.  If there are no intervening live ranges between them in
4573c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // IntB, we can merge them.
4583c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (ValLR+1 != BLR) return false;
4593c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4603c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // If a live interval is a physical register, conservatively check if any
4613c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // of its aliases is overlapping the live interval of the virtual register.
4623c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // If so, do not coalesce.
4633c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
4643c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    for (const unsigned *AS = TRI->getAliasSet(IntB.reg); *AS; ++AS)
4653c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
4663c827367444ee418f129b2c238299f49d3264554Jarkko Poyry        DEBUG({
4673c827367444ee418f129b2c238299f49d3264554Jarkko Poyry            dbgs() << "\t\tInterfere with alias ";
4683c827367444ee418f129b2c238299f49d3264554Jarkko Poyry            LIS->getInterval(*AS).print(dbgs(), TRI);
4693c827367444ee418f129b2c238299f49d3264554Jarkko Poyry          });
4703c827367444ee418f129b2c238299f49d3264554Jarkko Poyry        return false;
4713c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      }
4723c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  }
4733c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4743c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  DEBUG({
4753c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      dbgs() << "Extending: ";
4763c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      IntB.print(dbgs(), TRI);
4773c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    });
4783c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4793c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  SlotIndex FillerStart = ValLR->end, FillerEnd = BLR->start;
4803c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // We are about to delete CopyMI, so need to remove it as the 'instruction
4813c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // that defines this value #'. Update the valnum with the new defining
4823c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // instruction #.
4833c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  BValNo->def = FillerStart;
4843c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4853c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Okay, we can merge them.  We need to insert a new liverange:
4863c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // [ValLR.end, BLR.begin) of either value number, then we merge the
4873c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // two value numbers.
4883c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
4893c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
4903c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // If the IntB live range is assigned to a physical register, and if that
4913c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // physreg has sub-registers, update their live intervals as well.
4923c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
4933c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    for (const unsigned *SR = TRI->getSubRegisters(IntB.reg); *SR; ++SR) {
4943c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      if (!LIS->hasInterval(*SR))
4953c827367444ee418f129b2c238299f49d3264554Jarkko Poyry        continue;
4963c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      LiveInterval &SRLI = LIS->getInterval(*SR);
4973c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      SRLI.addRange(LiveRange(FillerStart, FillerEnd,
4983c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                              SRLI.getNextValue(FillerStart,
4993c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                                                LIS->getVNInfoAllocator())));
5003c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    }
5013c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  }
5023c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
5033c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Okay, merge "B1" into the same value number as "B0".
5043c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (BValNo != ValLR->valno) {
5053c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // If B1 is killed by a PHI, then the merged live range must also be killed
5063c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    // by the same PHI, as B0 and B1 can not overlap.
5073c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    bool HasPHIKill = BValNo->hasPHIKill();
5083c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    IntB.MergeValueNumberInto(BValNo, ValLR->valno);
5093c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    if (HasPHIKill)
5103c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      ValLR->valno->setHasPHIKill(true);
5113c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  }
5123c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  DEBUG({
5133c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      dbgs() << "   result = ";
5143c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      IntB.print(dbgs(), TRI);
5153c827367444ee418f129b2c238299f49d3264554Jarkko Poyry      dbgs() << "\n";
5163c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    });
5173c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
5183c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // If the source instruction was killing the source register before the
5193c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // merge, unset the isKill marker given the live range has been extended.
5203c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
5213c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (UIdx != -1) {
5223c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    ValLREndInst->getOperand(UIdx).setIsKill(false);
5233c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  }
5243c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
5253c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // Rewrite the copy. If the copy instruction was killing the destination
5263c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // register before the merge, find the last use and trim the live range. That
5273c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  // will also add the isKill marker.
5283c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  CopyMI->substituteRegister(IntA.reg, IntB.reg, CP.getSubIdx(),
5293c827367444ee418f129b2c238299f49d3264554Jarkko Poyry                             *TRI);
5303c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  if (ALR->end == CopyIdx)
5313c827367444ee418f129b2c238299f49d3264554Jarkko Poyry    LIS->shrinkToUses(&IntA);
5323c827367444ee418f129b2c238299f49d3264554Jarkko Poyry
5333c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  ++numExtends;
5343c827367444ee418f129b2c238299f49d3264554Jarkko Poyry  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.
539bool 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///
585bool 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 unsigned *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.
767bool 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);
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      NewMIImplDefs.push_back(MO.getReg());
819    }
820  }
821
822  // CopyMI may have implicit operands, transfer them over to the newly
823  // rematerialized instruction. And update implicit def interval valnos.
824  for (unsigned i = CopyMI->getDesc().getNumOperands(),
825         e = CopyMI->getNumOperands(); i != e; ++i) {
826    MachineOperand &MO = CopyMI->getOperand(i);
827    if (MO.isReg() && MO.isImplicit())
828      NewMI->addOperand(MO);
829  }
830
831  LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
832
833  SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
834  for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
835    unsigned reg = NewMIImplDefs[i];
836    LiveInterval &li = LIS->getInterval(reg);
837    VNInfo *DeadDefVN = li.getNextValue(NewMIIdx.getRegSlot(),
838                                        LIS->getVNInfoAllocator());
839    LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
840    li.addRange(lr);
841  }
842
843  NewMI->copyImplicitOps(CopyMI);
844  CopyMI->eraseFromParent();
845  ReMatCopies.insert(CopyMI);
846  ReMatDefs.insert(DefMI);
847  DEBUG(dbgs() << "Remat: " << *NewMI);
848  ++NumReMats;
849
850  // The source interval can become smaller because we removed a use.
851  if (preserveSrcInt)
852    LIS->shrinkToUses(&SrcInt);
853
854  return true;
855}
856
857/// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
858/// values, it only removes local variables. When we have a copy like:
859///
860///   %vreg1 = COPY %vreg2<undef>
861///
862/// We delete the copy and remove the corresponding value number from %vreg1.
863/// Any uses of that value number are marked as <undef>.
864bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
865                                           const CoalescerPair &CP) {
866  SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
867  LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
868  if (SrcInt->liveAt(Idx))
869    return false;
870  LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
871  if (DstInt->liveAt(Idx))
872    return false;
873
874  // No intervals are live-in to CopyMI - it is undef.
875  if (CP.isFlipped())
876    DstInt = SrcInt;
877  SrcInt = 0;
878
879  VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
880  assert(DeadVNI && "No value defined in DstInt");
881  DstInt->removeValNo(DeadVNI);
882
883  // Find new undef uses.
884  for (MachineRegisterInfo::reg_nodbg_iterator
885         I = MRI->reg_nodbg_begin(DstInt->reg), E = MRI->reg_nodbg_end();
886       I != E; ++I) {
887    MachineOperand &MO = I.getOperand();
888    if (MO.isDef() || MO.isUndef())
889      continue;
890    MachineInstr *MI = MO.getParent();
891    SlotIndex Idx = LIS->getInstructionIndex(MI);
892    if (DstInt->liveAt(Idx))
893      continue;
894    MO.setIsUndef(true);
895    DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
896  }
897  return true;
898}
899
900/// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
901/// update the subregister number if it is not zero. If DstReg is a
902/// physical register and the existing subregister number of the def / use
903/// being updated is not zero, make sure to set it to the correct physical
904/// subregister.
905void
906RegisterCoalescer::UpdateRegDefsUses(const CoalescerPair &CP) {
907  bool DstIsPhys = CP.isPhys();
908  unsigned SrcReg = CP.getSrcReg();
909  unsigned DstReg = CP.getDstReg();
910  unsigned SubIdx = CP.getSubIdx();
911
912  // Update LiveDebugVariables.
913  LDV->renameRegister(SrcReg, DstReg, SubIdx);
914
915  for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(SrcReg);
916       MachineInstr *UseMI = I.skipInstruction();) {
917    // A PhysReg copy that won't be coalesced can perhaps be rematerialized
918    // instead.
919    if (DstIsPhys) {
920      if (UseMI->isFullCopy() &&
921          UseMI->getOperand(1).getReg() == SrcReg &&
922          UseMI->getOperand(0).getReg() != SrcReg &&
923          UseMI->getOperand(0).getReg() != DstReg &&
924          !JoinedCopies.count(UseMI) &&
925          ReMaterializeTrivialDef(LIS->getInterval(SrcReg), false,
926                                  UseMI->getOperand(0).getReg(), UseMI))
927        continue;
928    }
929
930    SmallVector<unsigned,8> Ops;
931    bool Reads, Writes;
932    tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
933    bool Kills = false, Deads = false;
934
935    // Replace SrcReg with DstReg in all UseMI operands.
936    for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
937      MachineOperand &MO = UseMI->getOperand(Ops[i]);
938      Kills |= MO.isKill();
939      Deads |= MO.isDead();
940
941      // Make sure we don't create read-modify-write defs accidentally.  We
942      // assume here that a SrcReg def cannot be joined into a live DstReg.  If
943      // RegisterCoalescer starts tracking partially live registers, we will
944      // need to check the actual LiveInterval to determine if DstReg is live
945      // here.
946      if (SubIdx && !Reads)
947        MO.setIsUndef();
948
949      if (DstIsPhys)
950        MO.substPhysReg(DstReg, *TRI);
951      else
952        MO.substVirtReg(DstReg, SubIdx, *TRI);
953    }
954
955    // This instruction is a copy that will be removed.
956    if (JoinedCopies.count(UseMI))
957      continue;
958
959    if (SubIdx) {
960      // If UseMI was a simple SrcReg def, make sure we didn't turn it into a
961      // read-modify-write of DstReg.
962      if (Deads)
963        UseMI->addRegisterDead(DstReg, TRI);
964      else if (!Reads && Writes)
965        UseMI->addRegisterDefined(DstReg, TRI);
966
967      // Kill flags apply to the whole physical register.
968      if (DstIsPhys && Kills)
969        UseMI->addRegisterKilled(DstReg, TRI);
970    }
971
972    DEBUG({
973        dbgs() << "\t\tupdated: ";
974        if (!UseMI->isDebugValue())
975          dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
976        dbgs() << *UseMI;
977      });
978  }
979}
980
981/// removeIntervalIfEmpty - Check if the live interval of a physical register
982/// is empty, if so remove it and also remove the empty intervals of its
983/// sub-registers. Return true if live interval is removed.
984static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *LIS,
985                                  const TargetRegisterInfo *TRI) {
986  if (li.empty()) {
987    if (TargetRegisterInfo::isPhysicalRegister(li.reg))
988      for (const unsigned* SR = TRI->getSubRegisters(li.reg); *SR; ++SR) {
989        if (!LIS->hasInterval(*SR))
990          continue;
991        LiveInterval &sli = LIS->getInterval(*SR);
992        if (sli.empty())
993          LIS->removeInterval(*SR);
994      }
995    LIS->removeInterval(li.reg);
996    return true;
997  }
998  return false;
999}
1000
1001/// RemoveDeadDef - If a def of a live interval is now determined dead, remove
1002/// the val# it defines. If the live interval becomes empty, remove it as well.
1003bool RegisterCoalescer::RemoveDeadDef(LiveInterval &li,
1004                                             MachineInstr *DefMI) {
1005  SlotIndex DefIdx = LIS->getInstructionIndex(DefMI).getRegSlot();
1006  LiveInterval::iterator MLR = li.FindLiveRangeContaining(DefIdx);
1007  if (DefIdx != MLR->valno->def)
1008    return false;
1009  li.removeValNo(MLR->valno);
1010  return removeIntervalIfEmpty(li, LIS, TRI);
1011}
1012
1013/// shouldJoinPhys - Return true if a copy involving a physreg should be joined.
1014/// We need to be careful about coalescing a source physical register with a
1015/// virtual register. Once the coalescing is done, it cannot be broken and these
1016/// are not spillable! If the destination interval uses are far away, think
1017/// twice about coalescing them!
1018bool RegisterCoalescer::shouldJoinPhys(CoalescerPair &CP) {
1019  bool Allocatable = LIS->isAllocatable(CP.getDstReg());
1020  LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
1021
1022  /// Always join simple intervals that are defined by a single copy from a
1023  /// reserved register. This doesn't increase register pressure, so it is
1024  /// always beneficial.
1025  if (!Allocatable && CP.isFlipped() && JoinVInt.containsOneValue())
1026    return true;
1027
1028  if (!EnablePhysicalJoin) {
1029    DEBUG(dbgs() << "\tPhysreg joins disabled.\n");
1030    return false;
1031  }
1032
1033  // Only coalesce to allocatable physreg, we don't want to risk modifying
1034  // reserved registers.
1035  if (!Allocatable) {
1036    DEBUG(dbgs() << "\tRegister is an unallocatable physreg.\n");
1037    return false;  // Not coalescable.
1038  }
1039
1040  // Don't join with physregs that have a ridiculous number of live
1041  // ranges. The data structure performance is really bad when that
1042  // happens.
1043  if (LIS->hasInterval(CP.getDstReg()) &&
1044      LIS->getInterval(CP.getDstReg()).ranges.size() > 1000) {
1045    ++numAborts;
1046    DEBUG(dbgs()
1047          << "\tPhysical register live interval too complicated, abort!\n");
1048    return false;
1049  }
1050
1051  // FIXME: Why are we skipping this test for partial copies?
1052  //        CodeGen/X86/phys_subreg_coalesce-3.ll needs it.
1053  if (!CP.isPartial()) {
1054    const TargetRegisterClass *RC = MRI->getRegClass(CP.getSrcReg());
1055    unsigned Threshold = RegClassInfo.getNumAllocatableRegs(RC) * 2;
1056    unsigned Length = LIS->getApproximateInstructionCount(JoinVInt);
1057    if (Length > Threshold) {
1058      ++numAborts;
1059      DEBUG(dbgs() << "\tMay tie down a physical register, abort!\n");
1060      return false;
1061    }
1062  }
1063  return true;
1064}
1065
1066/// isWinToJoinCrossClass - Return true if it's profitable to coalesce
1067/// two virtual registers from different register classes.
1068bool
1069RegisterCoalescer::isWinToJoinCrossClass(unsigned SrcReg,
1070                                             unsigned DstReg,
1071                                             const TargetRegisterClass *SrcRC,
1072                                             const TargetRegisterClass *DstRC,
1073                                             const TargetRegisterClass *NewRC) {
1074  unsigned NewRCCount = RegClassInfo.getNumAllocatableRegs(NewRC);
1075  // This heuristics is good enough in practice, but it's obviously not *right*.
1076  // 4 is a magic number that works well enough for x86, ARM, etc. It filter
1077  // out all but the most restrictive register classes.
1078  if (NewRCCount > 4 ||
1079      // Early exit if the function is fairly small, coalesce aggressively if
1080      // that's the case. For really special register classes with 3 or
1081      // fewer registers, be a bit more careful.
1082      (LIS->getFuncInstructionCount() / NewRCCount) < 8)
1083    return true;
1084  LiveInterval &SrcInt = LIS->getInterval(SrcReg);
1085  LiveInterval &DstInt = LIS->getInterval(DstReg);
1086  unsigned SrcSize = LIS->getApproximateInstructionCount(SrcInt);
1087  unsigned DstSize = LIS->getApproximateInstructionCount(DstInt);
1088
1089  // Coalesce aggressively if the intervals are small compared to the number of
1090  // registers in the new class. The number 4 is fairly arbitrary, chosen to be
1091  // less aggressive than the 8 used for the whole function size.
1092  const unsigned ThresSize = 4 * NewRCCount;
1093  if (SrcSize <= ThresSize && DstSize <= ThresSize)
1094    return true;
1095
1096  // Estimate *register use density*. If it doubles or more, abort.
1097  unsigned SrcUses = std::distance(MRI->use_nodbg_begin(SrcReg),
1098                                   MRI->use_nodbg_end());
1099  unsigned DstUses = std::distance(MRI->use_nodbg_begin(DstReg),
1100                                   MRI->use_nodbg_end());
1101  unsigned NewUses = SrcUses + DstUses;
1102  unsigned NewSize = SrcSize + DstSize;
1103  if (SrcRC != NewRC && SrcSize > ThresSize) {
1104    unsigned SrcRCCount = RegClassInfo.getNumAllocatableRegs(SrcRC);
1105    if (NewUses*SrcSize*SrcRCCount > 2*SrcUses*NewSize*NewRCCount)
1106      return false;
1107  }
1108  if (DstRC != NewRC && DstSize > ThresSize) {
1109    unsigned DstRCCount = RegClassInfo.getNumAllocatableRegs(DstRC);
1110    if (NewUses*DstSize*DstRCCount > 2*DstUses*NewSize*NewRCCount)
1111      return false;
1112  }
1113  return true;
1114}
1115
1116
1117/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1118/// which are the src/dst of the copy instruction CopyMI.  This returns true
1119/// if the copy was successfully coalesced away. If it is not currently
1120/// possible to coalesce this interval, but it may be possible if other
1121/// things get coalesced, then it returns true by reference in 'Again'.
1122bool RegisterCoalescer::JoinCopy(MachineInstr *CopyMI, bool &Again) {
1123
1124  Again = false;
1125  if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
1126    return false; // Already done.
1127
1128  DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1129
1130  CoalescerPair CP(*TII, *TRI);
1131  if (!CP.setRegisters(CopyMI)) {
1132    DEBUG(dbgs() << "\tNot coalescable.\n");
1133    return false;
1134  }
1135
1136  // If they are already joined we continue.
1137  if (CP.getSrcReg() == CP.getDstReg()) {
1138    markAsJoined(CopyMI);
1139    DEBUG(dbgs() << "\tCopy already coalesced.\n");
1140    return false;  // Not coalescable.
1141  }
1142
1143  // Eliminate undefs.
1144  if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1145    markAsJoined(CopyMI);
1146    DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1147    return false;  // Not coalescable.
1148  }
1149
1150  DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1151               << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSubIdx())
1152               << "\n");
1153
1154  // Enforce policies.
1155  if (CP.isPhys()) {
1156    if (!shouldJoinPhys(CP)) {
1157      // Before giving up coalescing, if definition of source is defined by
1158      // trivial computation, try rematerializing it.
1159      if (!CP.isFlipped() &&
1160          ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1161                                  CP.getDstReg(), CopyMI))
1162        return true;
1163      return false;
1164    }
1165  } else {
1166    // Avoid constraining virtual register regclass too much.
1167    if (CP.isCrossClass()) {
1168      DEBUG(dbgs() << "\tCross-class to " << CP.getNewRC()->getName() << ".\n");
1169      if (DisableCrossClassJoin) {
1170        DEBUG(dbgs() << "\tCross-class joins disabled.\n");
1171        return false;
1172      }
1173      if (!isWinToJoinCrossClass(CP.getSrcReg(), CP.getDstReg(),
1174                                 MRI->getRegClass(CP.getSrcReg()),
1175                                 MRI->getRegClass(CP.getDstReg()),
1176                                 CP.getNewRC())) {
1177        DEBUG(dbgs() << "\tAvoid coalescing to constrained register class.\n");
1178        Again = true;  // May be possible to coalesce later.
1179        return false;
1180      }
1181    }
1182
1183    // When possible, let DstReg be the larger interval.
1184    if (!CP.getSubIdx() && LIS->getInterval(CP.getSrcReg()).ranges.size() >
1185                           LIS->getInterval(CP.getDstReg()).ranges.size())
1186      CP.flip();
1187  }
1188
1189  // Okay, attempt to join these two intervals.  On failure, this returns false.
1190  // Otherwise, if one of the intervals being joined is a physreg, this method
1191  // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
1192  // been modified, so we can use this information below to update aliases.
1193  if (!JoinIntervals(CP)) {
1194    // Coalescing failed.
1195
1196    // If definition of source is defined by trivial computation, try
1197    // rematerializing it.
1198    if (!CP.isFlipped() &&
1199        ReMaterializeTrivialDef(LIS->getInterval(CP.getSrcReg()), true,
1200                                CP.getDstReg(), CopyMI))
1201      return true;
1202
1203    // If we can eliminate the copy without merging the live ranges, do so now.
1204    if (!CP.isPartial()) {
1205      if (AdjustCopiesBackFrom(CP, CopyMI) ||
1206          RemoveCopyByCommutingDef(CP, CopyMI)) {
1207        markAsJoined(CopyMI);
1208        DEBUG(dbgs() << "\tTrivial!\n");
1209        return true;
1210      }
1211    }
1212
1213    // Otherwise, we are unable to join the intervals.
1214    DEBUG(dbgs() << "\tInterference!\n");
1215    Again = true;  // May be possible to coalesce later.
1216    return false;
1217  }
1218
1219  // Coalescing to a virtual register that is of a sub-register class of the
1220  // other. Make sure the resulting register is set to the right register class.
1221  if (CP.isCrossClass()) {
1222    ++numCrossRCs;
1223    MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1224  }
1225
1226  // Remember to delete the copy instruction.
1227  markAsJoined(CopyMI);
1228
1229  UpdateRegDefsUses(CP);
1230
1231  // If we have extended the live range of a physical register, make sure we
1232  // update live-in lists as well.
1233  if (CP.isPhys()) {
1234    SmallVector<MachineBasicBlock*, 16> BlockSeq;
1235    // JoinIntervals invalidates the VNInfos in SrcInt, but we only need the
1236    // ranges for this, and they are preserved.
1237    LiveInterval &SrcInt = LIS->getInterval(CP.getSrcReg());
1238    for (LiveInterval::const_iterator I = SrcInt.begin(), E = SrcInt.end();
1239         I != E; ++I ) {
1240      LIS->findLiveInMBBs(I->start, I->end, BlockSeq);
1241      for (unsigned idx = 0, size = BlockSeq.size(); idx != size; ++idx) {
1242        MachineBasicBlock &block = *BlockSeq[idx];
1243        if (!block.isLiveIn(CP.getDstReg()))
1244          block.addLiveIn(CP.getDstReg());
1245      }
1246      BlockSeq.clear();
1247    }
1248  }
1249
1250  // SrcReg is guaranteed to be the register whose live interval that is
1251  // being merged.
1252  LIS->removeInterval(CP.getSrcReg());
1253
1254  // Update regalloc hint.
1255  TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1256
1257  DEBUG({
1258    LiveInterval &DstInt = LIS->getInterval(CP.getDstReg());
1259    dbgs() << "\tJoined. Result = ";
1260    DstInt.print(dbgs(), TRI);
1261    dbgs() << "\n";
1262  });
1263
1264  ++numJoins;
1265  return true;
1266}
1267
1268/// ComputeUltimateVN - Assuming we are going to join two live intervals,
1269/// compute what the resultant value numbers for each value in the input two
1270/// ranges will be.  This is complicated by copies between the two which can
1271/// and will commonly cause multiple value numbers to be merged into one.
1272///
1273/// VN is the value number that we're trying to resolve.  InstDefiningValue
1274/// keeps track of the new InstDefiningValue assignment for the result
1275/// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
1276/// whether a value in this or other is a copy from the opposite set.
1277/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1278/// already been assigned.
1279///
1280/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1281/// contains the value number the copy is from.
1282///
1283static unsigned ComputeUltimateVN(VNInfo *VNI,
1284                                  SmallVector<VNInfo*, 16> &NewVNInfo,
1285                                  DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1286                                  DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1287                                  SmallVector<int, 16> &ThisValNoAssignments,
1288                                  SmallVector<int, 16> &OtherValNoAssignments) {
1289  unsigned VN = VNI->id;
1290
1291  // If the VN has already been computed, just return it.
1292  if (ThisValNoAssignments[VN] >= 0)
1293    return ThisValNoAssignments[VN];
1294  assert(ThisValNoAssignments[VN] != -2 && "Cyclic value numbers");
1295
1296  // If this val is not a copy from the other val, then it must be a new value
1297  // number in the destination.
1298  DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1299  if (I == ThisFromOther.end()) {
1300    NewVNInfo.push_back(VNI);
1301    return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1302  }
1303  VNInfo *OtherValNo = I->second;
1304
1305  // Otherwise, this *is* a copy from the RHS.  If the other side has already
1306  // been computed, return it.
1307  if (OtherValNoAssignments[OtherValNo->id] >= 0)
1308    return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1309
1310  // Mark this value number as currently being computed, then ask what the
1311  // ultimate value # of the other value is.
1312  ThisValNoAssignments[VN] = -2;
1313  unsigned UltimateVN =
1314    ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1315                      OtherValNoAssignments, ThisValNoAssignments);
1316  return ThisValNoAssignments[VN] = UltimateVN;
1317}
1318
1319
1320// Find out if we have something like
1321// A = X
1322// B = X
1323// if so, we can pretend this is actually
1324// A = X
1325// B = A
1326// which allows us to coalesce A and B.
1327// VNI is the definition of B. LR is the life range of A that includes
1328// the slot just before B. If we return true, we add "B = X" to DupCopies.
1329// This implies that A dominates B.
1330static bool RegistersDefinedFromSameValue(LiveIntervals &li,
1331                                          const TargetRegisterInfo &tri,
1332                                          CoalescerPair &CP,
1333                                          VNInfo *VNI,
1334                                          LiveRange *LR,
1335                                     SmallVector<MachineInstr*, 8> &DupCopies) {
1336  // FIXME: This is very conservative. For example, we don't handle
1337  // physical registers.
1338
1339  MachineInstr *MI = li.getInstructionFromIndex(VNI->def);
1340
1341  if (!MI || !MI->isFullCopy() || CP.isPartial() || CP.isPhys())
1342    return false;
1343
1344  unsigned Dst = MI->getOperand(0).getReg();
1345  unsigned Src = MI->getOperand(1).getReg();
1346
1347  if (!TargetRegisterInfo::isVirtualRegister(Src) ||
1348      !TargetRegisterInfo::isVirtualRegister(Dst))
1349    return false;
1350
1351  unsigned A = CP.getDstReg();
1352  unsigned B = CP.getSrcReg();
1353
1354  if (B == Dst)
1355    std::swap(A, B);
1356  assert(Dst == A);
1357
1358  VNInfo *Other = LR->valno;
1359  const MachineInstr *OtherMI = li.getInstructionFromIndex(Other->def);
1360
1361  if (!OtherMI || !OtherMI->isFullCopy())
1362    return false;
1363
1364  unsigned OtherDst = OtherMI->getOperand(0).getReg();
1365  unsigned OtherSrc = OtherMI->getOperand(1).getReg();
1366
1367  if (!TargetRegisterInfo::isVirtualRegister(OtherSrc) ||
1368      !TargetRegisterInfo::isVirtualRegister(OtherDst))
1369    return false;
1370
1371  assert(OtherDst == B);
1372
1373  if (Src != OtherSrc)
1374    return false;
1375
1376  // If the copies use two different value numbers of X, we cannot merge
1377  // A and B.
1378  LiveInterval &SrcInt = li.getInterval(Src);
1379  // getVNInfoBefore returns NULL for undef copies. In this case, the
1380  // optimization is still safe.
1381  if (SrcInt.getVNInfoBefore(Other->def) != SrcInt.getVNInfoBefore(VNI->def))
1382    return false;
1383
1384  DupCopies.push_back(MI);
1385
1386  return true;
1387}
1388
1389/// JoinIntervals - Attempt to join these two intervals.  On failure, this
1390/// returns false.
1391bool RegisterCoalescer::JoinIntervals(CoalescerPair &CP) {
1392  LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1393  DEBUG({ dbgs() << "\t\tRHS = "; RHS.print(dbgs(), TRI); dbgs() << "\n"; });
1394
1395  // If a live interval is a physical register, check for interference with any
1396  // aliases. The interference check implemented here is a bit more conservative
1397  // than the full interfeence check below. We allow overlapping live ranges
1398  // only when one is a copy of the other.
1399  if (CP.isPhys()) {
1400    // Optimization for reserved registers like ESP.
1401    // We can only merge with a reserved physreg if RHS has a single value that
1402    // is a copy of CP.DstReg().  The live range of the reserved register will
1403    // look like a set of dead defs - we don't properly track the live range of
1404    // reserved registers.
1405    if (RegClassInfo.isReserved(CP.getDstReg())) {
1406      assert(CP.isFlipped() && RHS.containsOneValue() &&
1407             "Invalid join with reserved register");
1408      // Deny any overlapping intervals.  This depends on all the reserved
1409      // register live ranges to look like dead defs.
1410      for (const unsigned *AS = TRI->getOverlaps(CP.getDstReg()); *AS; ++AS) {
1411        if (!LIS->hasInterval(*AS)) {
1412          // Make sure at least DstReg itself exists before attempting a join.
1413          if (*AS == CP.getDstReg())
1414            LIS->getOrCreateInterval(CP.getDstReg());
1415          continue;
1416        }
1417        if (RHS.overlaps(LIS->getInterval(*AS))) {
1418          DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\n');
1419          return false;
1420        }
1421      }
1422      // Skip any value computations, we are not adding new values to the
1423      // reserved register.  Also skip merging the live ranges, the reserved
1424      // register live range doesn't need to be accurate as long as all the
1425      // defs are there.
1426      return true;
1427    }
1428
1429    // Check if a register mask clobbers DstReg.
1430    BitVector UsableRegs;
1431    if (LIS->checkRegMaskInterference(RHS, UsableRegs) &&
1432        !UsableRegs.test(CP.getDstReg())) {
1433      DEBUG(dbgs() << "\t\tRegister mask interference.\n");
1434      return false;
1435    }
1436
1437    for (const unsigned *AS = TRI->getAliasSet(CP.getDstReg()); *AS; ++AS){
1438      if (!LIS->hasInterval(*AS))
1439        continue;
1440      const LiveInterval &LHS = LIS->getInterval(*AS);
1441      LiveInterval::const_iterator LI = LHS.begin();
1442      for (LiveInterval::const_iterator RI = RHS.begin(), RE = RHS.end();
1443           RI != RE; ++RI) {
1444        LI = std::lower_bound(LI, LHS.end(), RI->start);
1445        // Does LHS have an overlapping live range starting before RI?
1446        if ((LI != LHS.begin() && LI[-1].end > RI->start) &&
1447            (RI->start != RI->valno->def ||
1448             !CP.isCoalescable(LIS->getInstructionFromIndex(RI->start)))) {
1449          DEBUG({
1450            dbgs() << "\t\tInterference from alias: ";
1451            LHS.print(dbgs(), TRI);
1452            dbgs() << "\n\t\tOverlap at " << RI->start << " and no copy.\n";
1453          });
1454          return false;
1455        }
1456
1457        // Check that LHS ranges beginning in this range are copies.
1458        for (; LI != LHS.end() && LI->start < RI->end; ++LI) {
1459          if (LI->start != LI->valno->def ||
1460              !CP.isCoalescable(LIS->getInstructionFromIndex(LI->start))) {
1461            DEBUG({
1462              dbgs() << "\t\tInterference from alias: ";
1463              LHS.print(dbgs(), TRI);
1464              dbgs() << "\n\t\tDef at " << LI->start << " is not a copy.\n";
1465            });
1466            return false;
1467          }
1468        }
1469      }
1470    }
1471  }
1472
1473  // Compute the final value assignment, assuming that the live ranges can be
1474  // coalesced.
1475  SmallVector<int, 16> LHSValNoAssignments;
1476  SmallVector<int, 16> RHSValNoAssignments;
1477  DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1478  DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1479  SmallVector<VNInfo*, 16> NewVNInfo;
1480
1481  SmallVector<MachineInstr*, 8> DupCopies;
1482
1483  LiveInterval &LHS = LIS->getOrCreateInterval(CP.getDstReg());
1484  DEBUG({ dbgs() << "\t\tLHS = "; LHS.print(dbgs(), TRI); dbgs() << "\n"; });
1485
1486  // Loop over the value numbers of the LHS, seeing if any are defined from
1487  // the RHS.
1488  for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1489       i != e; ++i) {
1490    VNInfo *VNI = *i;
1491    if (VNI->isUnused() || VNI->isPHIDef())
1492      continue;
1493    MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1494    assert(MI && "Missing def");
1495    if (!MI->isCopyLike())  // Src not defined by a copy?
1496      continue;
1497
1498    // Figure out the value # from the RHS.
1499    LiveRange *lr = RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1500    // The copy could be to an aliased physreg.
1501    if (!lr) continue;
1502
1503    // DstReg is known to be a register in the LHS interval.  If the src is
1504    // from the RHS interval, we can use its value #.
1505    if (!CP.isCoalescable(MI) &&
1506        !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1507      continue;
1508
1509    LHSValsDefinedFromRHS[VNI] = lr->valno;
1510  }
1511
1512  // Loop over the value numbers of the RHS, seeing if any are defined from
1513  // the LHS.
1514  for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1515       i != e; ++i) {
1516    VNInfo *VNI = *i;
1517    if (VNI->isUnused() || VNI->isPHIDef())
1518      continue;
1519    MachineInstr *MI = LIS->getInstructionFromIndex(VNI->def);
1520    assert(MI && "Missing def");
1521    if (!MI->isCopyLike())  // Src not defined by a copy?
1522      continue;
1523
1524    // Figure out the value # from the LHS.
1525    LiveRange *lr = LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
1526    // The copy could be to an aliased physreg.
1527    if (!lr) continue;
1528
1529    // DstReg is known to be a register in the RHS interval.  If the src is
1530    // from the LHS interval, we can use its value #.
1531    if (!CP.isCoalescable(MI) &&
1532        !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
1533        continue;
1534
1535    RHSValsDefinedFromLHS[VNI] = lr->valno;
1536  }
1537
1538  LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1539  RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1540  NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1541
1542  for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1543       i != e; ++i) {
1544    VNInfo *VNI = *i;
1545    unsigned VN = VNI->id;
1546    if (LHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1547      continue;
1548    ComputeUltimateVN(VNI, NewVNInfo,
1549                      LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1550                      LHSValNoAssignments, RHSValNoAssignments);
1551  }
1552  for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1553       i != e; ++i) {
1554    VNInfo *VNI = *i;
1555    unsigned VN = VNI->id;
1556    if (RHSValNoAssignments[VN] >= 0 || VNI->isUnused())
1557      continue;
1558    // If this value number isn't a copy from the LHS, it's a new number.
1559    if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1560      NewVNInfo.push_back(VNI);
1561      RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1562      continue;
1563    }
1564
1565    ComputeUltimateVN(VNI, NewVNInfo,
1566                      RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1567                      RHSValNoAssignments, LHSValNoAssignments);
1568  }
1569
1570  // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1571  // interval lists to see if these intervals are coalescable.
1572  LiveInterval::const_iterator I = LHS.begin();
1573  LiveInterval::const_iterator IE = LHS.end();
1574  LiveInterval::const_iterator J = RHS.begin();
1575  LiveInterval::const_iterator JE = RHS.end();
1576
1577  // Skip ahead until the first place of potential sharing.
1578  if (I != IE && J != JE) {
1579    if (I->start < J->start) {
1580      I = std::upper_bound(I, IE, J->start);
1581      if (I != LHS.begin()) --I;
1582    } else if (J->start < I->start) {
1583      J = std::upper_bound(J, JE, I->start);
1584      if (J != RHS.begin()) --J;
1585    }
1586  }
1587
1588  while (I != IE && J != JE) {
1589    // Determine if these two live ranges overlap.
1590    bool Overlaps;
1591    if (I->start < J->start) {
1592      Overlaps = I->end > J->start;
1593    } else {
1594      Overlaps = J->end > I->start;
1595    }
1596
1597    // If so, check value # info to determine if they are really different.
1598    if (Overlaps) {
1599      // If the live range overlap will map to the same value number in the
1600      // result liverange, we can still coalesce them.  If not, we can't.
1601      if (LHSValNoAssignments[I->valno->id] !=
1602          RHSValNoAssignments[J->valno->id])
1603        return false;
1604    }
1605
1606    if (I->end < J->end)
1607      ++I;
1608    else
1609      ++J;
1610  }
1611
1612  // Update kill info. Some live ranges are extended due to copy coalescing.
1613  for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1614         E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1615    VNInfo *VNI = I->first;
1616    unsigned LHSValID = LHSValNoAssignments[VNI->id];
1617    if (VNI->hasPHIKill())
1618      NewVNInfo[LHSValID]->setHasPHIKill(true);
1619  }
1620
1621  // Update kill info. Some live ranges are extended due to copy coalescing.
1622  for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1623         E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1624    VNInfo *VNI = I->first;
1625    unsigned RHSValID = RHSValNoAssignments[VNI->id];
1626    if (VNI->hasPHIKill())
1627      NewVNInfo[RHSValID]->setHasPHIKill(true);
1628  }
1629
1630  if (LHSValNoAssignments.empty())
1631    LHSValNoAssignments.push_back(-1);
1632  if (RHSValNoAssignments.empty())
1633    RHSValNoAssignments.push_back(-1);
1634
1635  SmallVector<unsigned, 8> SourceRegisters;
1636  for (SmallVector<MachineInstr*, 8>::iterator I = DupCopies.begin(),
1637         E = DupCopies.end(); I != E; ++I) {
1638    MachineInstr *MI = *I;
1639
1640    // We have pretended that the assignment to B in
1641    // A = X
1642    // B = X
1643    // was actually a copy from A. Now that we decided to coalesce A and B,
1644    // transform the code into
1645    // A = X
1646    // X = X
1647    // and mark the X as coalesced to keep the illusion.
1648    unsigned Src = MI->getOperand(1).getReg();
1649    SourceRegisters.push_back(Src);
1650    MI->getOperand(0).substVirtReg(Src, 0, *TRI);
1651
1652    markAsJoined(MI);
1653  }
1654
1655  // If B = X was the last use of X in a liverange, we have to shrink it now
1656  // that B = X is gone.
1657  for (SmallVector<unsigned, 8>::iterator I = SourceRegisters.begin(),
1658         E = SourceRegisters.end(); I != E; ++I) {
1659    LIS->shrinkToUses(&LIS->getInterval(*I));
1660  }
1661
1662  // If we get here, we know that we can coalesce the live ranges.  Ask the
1663  // intervals to coalesce themselves now.
1664  LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo,
1665           MRI);
1666  return true;
1667}
1668
1669namespace {
1670  // DepthMBBCompare - Comparison predicate that sort first based on the loop
1671  // depth of the basic block (the unsigned), and then on the MBB number.
1672  struct DepthMBBCompare {
1673    typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1674    bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1675      // Deeper loops first
1676      if (LHS.first != RHS.first)
1677        return LHS.first > RHS.first;
1678
1679      // Prefer blocks that are more connected in the CFG. This takes care of
1680      // the most difficult copies first while intervals are short.
1681      unsigned cl = LHS.second->pred_size() + LHS.second->succ_size();
1682      unsigned cr = RHS.second->pred_size() + RHS.second->succ_size();
1683      if (cl != cr)
1684        return cl > cr;
1685
1686      // As a last resort, sort by block number.
1687      return LHS.second->getNumber() < RHS.second->getNumber();
1688    }
1689  };
1690}
1691
1692void RegisterCoalescer::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1693                                            std::vector<MachineInstr*> &TryAgain) {
1694  DEBUG(dbgs() << MBB->getName() << ":\n");
1695
1696  SmallVector<MachineInstr*, 8> VirtCopies;
1697  SmallVector<MachineInstr*, 8> PhysCopies;
1698  SmallVector<MachineInstr*, 8> ImpDefCopies;
1699  for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1700       MII != E;) {
1701    MachineInstr *Inst = MII++;
1702
1703    // If this isn't a copy nor a extract_subreg, we can't join intervals.
1704    unsigned SrcReg, DstReg;
1705    if (Inst->isCopy()) {
1706      DstReg = Inst->getOperand(0).getReg();
1707      SrcReg = Inst->getOperand(1).getReg();
1708    } else if (Inst->isSubregToReg()) {
1709      DstReg = Inst->getOperand(0).getReg();
1710      SrcReg = Inst->getOperand(2).getReg();
1711    } else
1712      continue;
1713
1714    bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1715    bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1716    if (LIS->hasInterval(SrcReg) && LIS->getInterval(SrcReg).empty())
1717      ImpDefCopies.push_back(Inst);
1718    else if (SrcIsPhys || DstIsPhys)
1719      PhysCopies.push_back(Inst);
1720    else
1721      VirtCopies.push_back(Inst);
1722  }
1723
1724  // Try coalescing implicit copies and insert_subreg <undef> first,
1725  // followed by copies to / from physical registers, then finally copies
1726  // from virtual registers to virtual registers.
1727  for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1728    MachineInstr *TheCopy = ImpDefCopies[i];
1729    bool Again = false;
1730    if (!JoinCopy(TheCopy, Again))
1731      if (Again)
1732        TryAgain.push_back(TheCopy);
1733  }
1734  for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1735    MachineInstr *TheCopy = PhysCopies[i];
1736    bool Again = false;
1737    if (!JoinCopy(TheCopy, Again))
1738      if (Again)
1739        TryAgain.push_back(TheCopy);
1740  }
1741  for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1742    MachineInstr *TheCopy = VirtCopies[i];
1743    bool Again = false;
1744    if (!JoinCopy(TheCopy, Again))
1745      if (Again)
1746        TryAgain.push_back(TheCopy);
1747  }
1748}
1749
1750void RegisterCoalescer::joinIntervals() {
1751  DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
1752
1753  std::vector<MachineInstr*> TryAgainList;
1754  if (Loops->empty()) {
1755    // If there are no loops in the function, join intervals in function order.
1756    for (MachineFunction::iterator I = MF->begin(), E = MF->end();
1757         I != E; ++I)
1758      CopyCoalesceInMBB(I, TryAgainList);
1759  } else {
1760    // Otherwise, join intervals in inner loops before other intervals.
1761    // Unfortunately we can't just iterate over loop hierarchy here because
1762    // there may be more MBB's than BB's.  Collect MBB's for sorting.
1763
1764    // Join intervals in the function prolog first. We want to join physical
1765    // registers with virtual registers before the intervals got too long.
1766    std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1767    for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
1768      MachineBasicBlock *MBB = I;
1769      MBBs.push_back(std::make_pair(Loops->getLoopDepth(MBB), I));
1770    }
1771
1772    // Sort by loop depth.
1773    std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1774
1775    // Finally, join intervals in loop nest order.
1776    for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1777      CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
1778  }
1779
1780  // Joining intervals can allow other intervals to be joined.  Iteratively join
1781  // until we make no progress.
1782  bool ProgressMade = true;
1783  while (ProgressMade) {
1784    ProgressMade = false;
1785
1786    for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1787      MachineInstr *&TheCopy = TryAgainList[i];
1788      if (!TheCopy)
1789        continue;
1790
1791      bool Again = false;
1792      bool Success = JoinCopy(TheCopy, Again);
1793      if (Success || !Again) {
1794        TheCopy= 0;   // Mark this one as done.
1795        ProgressMade = true;
1796      }
1797    }
1798  }
1799}
1800
1801void RegisterCoalescer::releaseMemory() {
1802  JoinedCopies.clear();
1803  ReMatCopies.clear();
1804  ReMatDefs.clear();
1805}
1806
1807bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
1808  MF = &fn;
1809  MRI = &fn.getRegInfo();
1810  TM = &fn.getTarget();
1811  TRI = TM->getRegisterInfo();
1812  TII = TM->getInstrInfo();
1813  LIS = &getAnalysis<LiveIntervals>();
1814  LDV = &getAnalysis<LiveDebugVariables>();
1815  AA = &getAnalysis<AliasAnalysis>();
1816  Loops = &getAnalysis<MachineLoopInfo>();
1817
1818  DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
1819               << "********** Function: "
1820               << ((Value*)MF->getFunction())->getName() << '\n');
1821
1822  if (VerifyCoalescing)
1823    MF->verify(this, "Before register coalescing");
1824
1825  RegClassInfo.runOnMachineFunction(fn);
1826
1827  // Join (coalesce) intervals if requested.
1828  if (EnableJoining) {
1829    joinIntervals();
1830    DEBUG({
1831        dbgs() << "********** INTERVALS POST JOINING **********\n";
1832        for (LiveIntervals::iterator I = LIS->begin(), E = LIS->end();
1833             I != E; ++I){
1834          I->second->print(dbgs(), TRI);
1835          dbgs() << "\n";
1836        }
1837      });
1838  }
1839
1840  // Perform a final pass over the instructions and compute spill weights
1841  // and remove identity moves.
1842  SmallVector<unsigned, 4> DeadDefs, InflateRegs;
1843  for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1844       mbbi != mbbe; ++mbbi) {
1845    MachineBasicBlock* mbb = mbbi;
1846    for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1847         mii != mie; ) {
1848      MachineInstr *MI = mii;
1849      if (JoinedCopies.count(MI)) {
1850        // Delete all coalesced copies.
1851        bool DoDelete = true;
1852        assert(MI->isCopyLike() && "Unrecognized copy instruction");
1853        unsigned SrcReg = MI->getOperand(MI->isSubregToReg() ? 2 : 1).getReg();
1854        unsigned DstReg = MI->getOperand(0).getReg();
1855
1856        // Collect candidates for register class inflation.
1857        if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1858            RegClassInfo.isProperSubClass(MRI->getRegClass(SrcReg)))
1859          InflateRegs.push_back(SrcReg);
1860        if (TargetRegisterInfo::isVirtualRegister(DstReg) &&
1861            RegClassInfo.isProperSubClass(MRI->getRegClass(DstReg)))
1862          InflateRegs.push_back(DstReg);
1863
1864        if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1865            MI->getNumOperands() > 2)
1866          // Do not delete extract_subreg, insert_subreg of physical
1867          // registers unless the definition is dead. e.g.
1868          // %DO<def> = INSERT_SUBREG %D0<undef>, %S0<kill>, 1
1869          // or else the scavenger may complain. LowerSubregs will
1870          // delete them later.
1871          DoDelete = false;
1872
1873        if (MI->allDefsAreDead()) {
1874          if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1875              LIS->hasInterval(SrcReg))
1876            LIS->shrinkToUses(&LIS->getInterval(SrcReg));
1877          DoDelete = true;
1878        }
1879        if (!DoDelete) {
1880          // We need the instruction to adjust liveness, so make it a KILL.
1881          if (MI->isSubregToReg()) {
1882            MI->RemoveOperand(3);
1883            MI->RemoveOperand(1);
1884          }
1885          MI->setDesc(TII->get(TargetOpcode::KILL));
1886          mii = llvm::next(mii);
1887        } else {
1888          LIS->RemoveMachineInstrFromMaps(MI);
1889          mii = mbbi->erase(mii);
1890          ++numPeep;
1891        }
1892        continue;
1893      }
1894
1895      // Now check if this is a remat'ed def instruction which is now dead.
1896      if (ReMatDefs.count(MI)) {
1897        bool isDead = true;
1898        for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1899          const MachineOperand &MO = MI->getOperand(i);
1900          if (!MO.isReg())
1901            continue;
1902          unsigned Reg = MO.getReg();
1903          if (!Reg)
1904            continue;
1905          DeadDefs.push_back(Reg);
1906          if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1907            // Remat may also enable register class inflation.
1908            if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
1909              InflateRegs.push_back(Reg);
1910          }
1911          if (MO.isDead())
1912            continue;
1913          if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
1914              !MRI->use_nodbg_empty(Reg)) {
1915            isDead = false;
1916            break;
1917          }
1918        }
1919        if (isDead) {
1920          while (!DeadDefs.empty()) {
1921            unsigned DeadDef = DeadDefs.back();
1922            DeadDefs.pop_back();
1923            RemoveDeadDef(LIS->getInterval(DeadDef), MI);
1924          }
1925          LIS->RemoveMachineInstrFromMaps(mii);
1926          mii = mbbi->erase(mii);
1927          continue;
1928        } else
1929          DeadDefs.clear();
1930      }
1931
1932      ++mii;
1933
1934      // Check for now unnecessary kill flags.
1935      if (LIS->isNotInMIMap(MI)) continue;
1936      SlotIndex DefIdx = LIS->getInstructionIndex(MI).getRegSlot();
1937      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1938        MachineOperand &MO = MI->getOperand(i);
1939        if (!MO.isReg() || !MO.isKill()) continue;
1940        unsigned reg = MO.getReg();
1941        if (!reg || !LIS->hasInterval(reg)) continue;
1942        if (!LIS->getInterval(reg).killedAt(DefIdx)) {
1943          MO.setIsKill(false);
1944          continue;
1945        }
1946        // When leaving a kill flag on a physreg, check if any subregs should
1947        // remain alive.
1948        if (!TargetRegisterInfo::isPhysicalRegister(reg))
1949          continue;
1950        for (const unsigned *SR = TRI->getSubRegisters(reg);
1951             unsigned S = *SR; ++SR)
1952          if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
1953            MI->addRegisterDefined(S, TRI);
1954      }
1955    }
1956  }
1957
1958  // After deleting a lot of copies, register classes may be less constrained.
1959  // Removing sub-register opreands may alow GR32_ABCD -> GR32 and DPR_VFP2 ->
1960  // DPR inflation.
1961  array_pod_sort(InflateRegs.begin(), InflateRegs.end());
1962  InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
1963                    InflateRegs.end());
1964  DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
1965  for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
1966    unsigned Reg = InflateRegs[i];
1967    if (MRI->reg_nodbg_empty(Reg))
1968      continue;
1969    if (MRI->recomputeRegClass(Reg, *TM)) {
1970      DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
1971                   << MRI->getRegClass(Reg)->getName() << '\n');
1972      ++NumInflated;
1973    }
1974  }
1975
1976  DEBUG(dump());
1977  DEBUG(LDV->dump());
1978  if (VerifyCoalescing)
1979    MF->verify(this, "After register coalescing");
1980  return true;
1981}
1982
1983/// print - Implement the dump method.
1984void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
1985   LIS->print(O, m);
1986}
1987