LLVM API Documentation

TwoAddressInstructionPass.cpp
Go to the documentation of this file.
00001 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the TwoAddress instruction pass which is used
00011 // by most register allocators. Two-Address instructions are rewritten
00012 // from:
00013 //
00014 //     A = B op C
00015 //
00016 // to:
00017 //
00018 //     A = B
00019 //     A op= C
00020 //
00021 // Note that if a register allocator chooses to use this pass, that it
00022 // has to be capable of handling the non-SSA nature of these rewritten
00023 // virtual registers.
00024 //
00025 // It is also worth noting that the duplicate operand of the two
00026 // address instruction is removed.
00027 //
00028 //===----------------------------------------------------------------------===//
00029 
00030 #include "llvm/CodeGen/Passes.h"
00031 #include "llvm/ADT/BitVector.h"
00032 #include "llvm/ADT/DenseMap.h"
00033 #include "llvm/ADT/STLExtras.h"
00034 #include "llvm/ADT/SmallSet.h"
00035 #include "llvm/ADT/Statistic.h"
00036 #include "llvm/Analysis/AliasAnalysis.h"
00037 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00038 #include "llvm/CodeGen/LiveVariables.h"
00039 #include "llvm/CodeGen/MachineFunctionPass.h"
00040 #include "llvm/CodeGen/MachineInstr.h"
00041 #include "llvm/CodeGen/MachineInstrBuilder.h"
00042 #include "llvm/CodeGen/MachineRegisterInfo.h"
00043 #include "llvm/IR/Function.h"
00044 #include "llvm/MC/MCInstrItineraries.h"
00045 #include "llvm/Support/CommandLine.h"
00046 #include "llvm/Support/Debug.h"
00047 #include "llvm/Support/ErrorHandling.h"
00048 #include "llvm/Target/TargetInstrInfo.h"
00049 #include "llvm/Target/TargetMachine.h"
00050 #include "llvm/Target/TargetRegisterInfo.h"
00051 #include "llvm/Target/TargetSubtargetInfo.h"
00052 using namespace llvm;
00053 
00054 #define DEBUG_TYPE "twoaddrinstr"
00055 
00056 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
00057 STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
00058 STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
00059 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
00060 STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
00061 STATISTIC(NumReSchedUps,       "Number of instructions re-scheduled up");
00062 STATISTIC(NumReSchedDowns,     "Number of instructions re-scheduled down");
00063 
00064 // Temporary flag to disable rescheduling.
00065 static cl::opt<bool>
00066 EnableRescheduling("twoaddr-reschedule",
00067                    cl::desc("Coalesce copies by rescheduling (default=true)"),
00068                    cl::init(true), cl::Hidden);
00069 
00070 namespace {
00071 class TwoAddressInstructionPass : public MachineFunctionPass {
00072   MachineFunction *MF;
00073   const TargetInstrInfo *TII;
00074   const TargetRegisterInfo *TRI;
00075   const InstrItineraryData *InstrItins;
00076   MachineRegisterInfo *MRI;
00077   LiveVariables *LV;
00078   LiveIntervals *LIS;
00079   AliasAnalysis *AA;
00080   CodeGenOpt::Level OptLevel;
00081 
00082   // The current basic block being processed.
00083   MachineBasicBlock *MBB;
00084 
00085   // DistanceMap - Keep track the distance of a MI from the start of the
00086   // current basic block.
00087   DenseMap<MachineInstr*, unsigned> DistanceMap;
00088 
00089   // Set of already processed instructions in the current block.
00090   SmallPtrSet<MachineInstr*, 8> Processed;
00091 
00092   // SrcRegMap - A map from virtual registers to physical registers which are
00093   // likely targets to be coalesced to due to copies from physical registers to
00094   // virtual registers. e.g. v1024 = move r0.
00095   DenseMap<unsigned, unsigned> SrcRegMap;
00096 
00097   // DstRegMap - A map from virtual registers to physical registers which are
00098   // likely targets to be coalesced to due to copies to physical registers from
00099   // virtual registers. e.g. r1 = move v1024.
00100   DenseMap<unsigned, unsigned> DstRegMap;
00101 
00102   bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
00103                             MachineBasicBlock::iterator OldPos);
00104 
00105   bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
00106 
00107   bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
00108                              MachineInstr *MI, unsigned Dist);
00109 
00110   bool commuteInstruction(MachineBasicBlock::iterator &mi,
00111                           unsigned RegB, unsigned RegC, unsigned Dist);
00112 
00113   bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
00114 
00115   bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
00116                           MachineBasicBlock::iterator &nmi,
00117                           unsigned RegA, unsigned RegB, unsigned Dist);
00118 
00119   bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
00120 
00121   bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
00122                              MachineBasicBlock::iterator &nmi,
00123                              unsigned Reg);
00124   bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
00125                              MachineBasicBlock::iterator &nmi,
00126                              unsigned Reg);
00127 
00128   bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
00129                                MachineBasicBlock::iterator &nmi,
00130                                unsigned SrcIdx, unsigned DstIdx,
00131                                unsigned Dist, bool shouldOnlyCommute);
00132 
00133   void scanUses(unsigned DstReg);
00134 
00135   void processCopy(MachineInstr *MI);
00136 
00137   typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
00138   typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
00139   bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
00140   void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
00141   void eliminateRegSequence(MachineBasicBlock::iterator&);
00142 
00143 public:
00144   static char ID; // Pass identification, replacement for typeid
00145   TwoAddressInstructionPass() : MachineFunctionPass(ID) {
00146     initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
00147   }
00148 
00149   void getAnalysisUsage(AnalysisUsage &AU) const override {
00150     AU.setPreservesCFG();
00151     AU.addRequired<AliasAnalysis>();
00152     AU.addPreserved<LiveVariables>();
00153     AU.addPreserved<SlotIndexes>();
00154     AU.addPreserved<LiveIntervals>();
00155     AU.addPreservedID(MachineLoopInfoID);
00156     AU.addPreservedID(MachineDominatorsID);
00157     MachineFunctionPass::getAnalysisUsage(AU);
00158   }
00159 
00160   /// runOnMachineFunction - Pass entry point.
00161   bool runOnMachineFunction(MachineFunction&) override;
00162 };
00163 } // end anonymous namespace
00164 
00165 char TwoAddressInstructionPass::ID = 0;
00166 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
00167                 "Two-Address instruction pass", false, false)
00168 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00169 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
00170                 "Two-Address instruction pass", false, false)
00171 
00172 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
00173 
00174 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
00175 
00176 /// sink3AddrInstruction - A two-address instruction has been converted to a
00177 /// three-address instruction to avoid clobbering a register. Try to sink it
00178 /// past the instruction that would kill the above mentioned register to reduce
00179 /// register pressure.
00180 bool TwoAddressInstructionPass::
00181 sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
00182                      MachineBasicBlock::iterator OldPos) {
00183   // FIXME: Shouldn't we be trying to do this before we three-addressify the
00184   // instruction?  After this transformation is done, we no longer need
00185   // the instruction to be in three-address form.
00186 
00187   // Check if it's safe to move this instruction.
00188   bool SeenStore = true; // Be conservative.
00189   if (!MI->isSafeToMove(TII, AA, SeenStore))
00190     return false;
00191 
00192   unsigned DefReg = 0;
00193   SmallSet<unsigned, 4> UseRegs;
00194 
00195   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00196     const MachineOperand &MO = MI->getOperand(i);
00197     if (!MO.isReg())
00198       continue;
00199     unsigned MOReg = MO.getReg();
00200     if (!MOReg)
00201       continue;
00202     if (MO.isUse() && MOReg != SavedReg)
00203       UseRegs.insert(MO.getReg());
00204     if (!MO.isDef())
00205       continue;
00206     if (MO.isImplicit())
00207       // Don't try to move it if it implicitly defines a register.
00208       return false;
00209     if (DefReg)
00210       // For now, don't move any instructions that define multiple registers.
00211       return false;
00212     DefReg = MO.getReg();
00213   }
00214 
00215   // Find the instruction that kills SavedReg.
00216   MachineInstr *KillMI = nullptr;
00217   if (LIS) {
00218     LiveInterval &LI = LIS->getInterval(SavedReg);
00219     assert(LI.end() != LI.begin() &&
00220            "Reg should not have empty live interval.");
00221 
00222     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
00223     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
00224     if (I != LI.end() && I->start < MBBEndIdx)
00225       return false;
00226 
00227     --I;
00228     KillMI = LIS->getInstructionFromIndex(I->end);
00229   }
00230   if (!KillMI) {
00231     for (MachineRegisterInfo::use_nodbg_iterator
00232            UI = MRI->use_nodbg_begin(SavedReg),
00233            UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
00234       MachineOperand &UseMO = *UI;
00235       if (!UseMO.isKill())
00236         continue;
00237       KillMI = UseMO.getParent();
00238       break;
00239     }
00240   }
00241 
00242   // If we find the instruction that kills SavedReg, and it is in an
00243   // appropriate location, we can try to sink the current instruction
00244   // past it.
00245   if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
00246       KillMI == OldPos || KillMI->isTerminator())
00247     return false;
00248 
00249   // If any of the definitions are used by another instruction between the
00250   // position and the kill use, then it's not safe to sink it.
00251   //
00252   // FIXME: This can be sped up if there is an easy way to query whether an
00253   // instruction is before or after another instruction. Then we can use
00254   // MachineRegisterInfo def / use instead.
00255   MachineOperand *KillMO = nullptr;
00256   MachineBasicBlock::iterator KillPos = KillMI;
00257   ++KillPos;
00258 
00259   unsigned NumVisited = 0;
00260   for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) {
00261     MachineInstr *OtherMI = I;
00262     // DBG_VALUE cannot be counted against the limit.
00263     if (OtherMI->isDebugValue())
00264       continue;
00265     if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
00266       return false;
00267     ++NumVisited;
00268     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
00269       MachineOperand &MO = OtherMI->getOperand(i);
00270       if (!MO.isReg())
00271         continue;
00272       unsigned MOReg = MO.getReg();
00273       if (!MOReg)
00274         continue;
00275       if (DefReg == MOReg)
00276         return false;
00277 
00278       if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
00279         if (OtherMI == KillMI && MOReg == SavedReg)
00280           // Save the operand that kills the register. We want to unset the kill
00281           // marker if we can sink MI past it.
00282           KillMO = &MO;
00283         else if (UseRegs.count(MOReg))
00284           // One of the uses is killed before the destination.
00285           return false;
00286       }
00287     }
00288   }
00289   assert(KillMO && "Didn't find kill");
00290 
00291   if (!LIS) {
00292     // Update kill and LV information.
00293     KillMO->setIsKill(false);
00294     KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
00295     KillMO->setIsKill(true);
00296 
00297     if (LV)
00298       LV->replaceKillInstruction(SavedReg, KillMI, MI);
00299   }
00300 
00301   // Move instruction to its destination.
00302   MBB->remove(MI);
00303   MBB->insert(KillPos, MI);
00304 
00305   if (LIS)
00306     LIS->handleMove(MI);
00307 
00308   ++Num3AddrSunk;
00309   return true;
00310 }
00311 
00312 /// noUseAfterLastDef - Return true if there are no intervening uses between the
00313 /// last instruction in the MBB that defines the specified register and the
00314 /// two-address instruction which is being processed. It also returns the last
00315 /// def location by reference
00316 bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
00317                                                   unsigned &LastDef) {
00318   LastDef = 0;
00319   unsigned LastUse = Dist;
00320   for (MachineOperand &MO : MRI->reg_operands(Reg)) {
00321     MachineInstr *MI = MO.getParent();
00322     if (MI->getParent() != MBB || MI->isDebugValue())
00323       continue;
00324     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
00325     if (DI == DistanceMap.end())
00326       continue;
00327     if (MO.isUse() && DI->second < LastUse)
00328       LastUse = DI->second;
00329     if (MO.isDef() && DI->second > LastDef)
00330       LastDef = DI->second;
00331   }
00332 
00333   return !(LastUse > LastDef && LastUse < Dist);
00334 }
00335 
00336 /// isCopyToReg - Return true if the specified MI is a copy instruction or
00337 /// a extract_subreg instruction. It also returns the source and destination
00338 /// registers and whether they are physical registers by reference.
00339 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
00340                         unsigned &SrcReg, unsigned &DstReg,
00341                         bool &IsSrcPhys, bool &IsDstPhys) {
00342   SrcReg = 0;
00343   DstReg = 0;
00344   if (MI.isCopy()) {
00345     DstReg = MI.getOperand(0).getReg();
00346     SrcReg = MI.getOperand(1).getReg();
00347   } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
00348     DstReg = MI.getOperand(0).getReg();
00349     SrcReg = MI.getOperand(2).getReg();
00350   } else
00351     return false;
00352 
00353   IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
00354   IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
00355   return true;
00356 }
00357 
00358 /// isPLainlyKilled - Test if the given register value, which is used by the
00359 // given instruction, is killed by the given instruction.
00360 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
00361                             LiveIntervals *LIS) {
00362   if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
00363       !LIS->isNotInMIMap(MI)) {
00364     // FIXME: Sometimes tryInstructionTransform() will add instructions and
00365     // test whether they can be folded before keeping them. In this case it
00366     // sets a kill before recursively calling tryInstructionTransform() again.
00367     // If there is no interval available, we assume that this instruction is
00368     // one of those. A kill flag is manually inserted on the operand so the
00369     // check below will handle it.
00370     LiveInterval &LI = LIS->getInterval(Reg);
00371     // This is to match the kill flag version where undefs don't have kill
00372     // flags.
00373     if (!LI.hasAtLeastOneValue())
00374       return false;
00375 
00376     SlotIndex useIdx = LIS->getInstructionIndex(MI);
00377     LiveInterval::const_iterator I = LI.find(useIdx);
00378     assert(I != LI.end() && "Reg must be live-in to use.");
00379     return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
00380   }
00381 
00382   return MI->killsRegister(Reg);
00383 }
00384 
00385 /// isKilled - Test if the given register value, which is used by the given
00386 /// instruction, is killed by the given instruction. This looks through
00387 /// coalescable copies to see if the original value is potentially not killed.
00388 ///
00389 /// For example, in this code:
00390 ///
00391 ///   %reg1034 = copy %reg1024
00392 ///   %reg1035 = copy %reg1025<kill>
00393 ///   %reg1036 = add %reg1034<kill>, %reg1035<kill>
00394 ///
00395 /// %reg1034 is not considered to be killed, since it is copied from a
00396 /// register which is not killed. Treating it as not killed lets the
00397 /// normal heuristics commute the (two-address) add, which lets
00398 /// coalescing eliminate the extra copy.
00399 ///
00400 /// If allowFalsePositives is true then likely kills are treated as kills even
00401 /// if it can't be proven that they are kills.
00402 static bool isKilled(MachineInstr &MI, unsigned Reg,
00403                      const MachineRegisterInfo *MRI,
00404                      const TargetInstrInfo *TII,
00405                      LiveIntervals *LIS,
00406                      bool allowFalsePositives) {
00407   MachineInstr *DefMI = &MI;
00408   for (;;) {
00409     // All uses of physical registers are likely to be kills.
00410     if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
00411         (allowFalsePositives || MRI->hasOneUse(Reg)))
00412       return true;
00413     if (!isPlainlyKilled(DefMI, Reg, LIS))
00414       return false;
00415     if (TargetRegisterInfo::isPhysicalRegister(Reg))
00416       return true;
00417     MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
00418     // If there are multiple defs, we can't do a simple analysis, so just
00419     // go with what the kill flag says.
00420     if (std::next(Begin) != MRI->def_end())
00421       return true;
00422     DefMI = Begin->getParent();
00423     bool IsSrcPhys, IsDstPhys;
00424     unsigned SrcReg,  DstReg;
00425     // If the def is something other than a copy, then it isn't going to
00426     // be coalesced, so follow the kill flag.
00427     if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
00428       return true;
00429     Reg = SrcReg;
00430   }
00431 }
00432 
00433 /// isTwoAddrUse - Return true if the specified MI uses the specified register
00434 /// as a two-address use. If so, return the destination register by reference.
00435 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
00436   for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
00437     const MachineOperand &MO = MI.getOperand(i);
00438     if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
00439       continue;
00440     unsigned ti;
00441     if (MI.isRegTiedToDefOperand(i, &ti)) {
00442       DstReg = MI.getOperand(ti).getReg();
00443       return true;
00444     }
00445   }
00446   return false;
00447 }
00448 
00449 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
00450 /// use, return the use instruction if it's a copy or a two-address use.
00451 static
00452 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
00453                                      MachineRegisterInfo *MRI,
00454                                      const TargetInstrInfo *TII,
00455                                      bool &IsCopy,
00456                                      unsigned &DstReg, bool &IsDstPhys) {
00457   if (!MRI->hasOneNonDBGUse(Reg))
00458     // None or more than one use.
00459     return nullptr;
00460   MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
00461   if (UseMI.getParent() != MBB)
00462     return nullptr;
00463   unsigned SrcReg;
00464   bool IsSrcPhys;
00465   if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
00466     IsCopy = true;
00467     return &UseMI;
00468   }
00469   IsDstPhys = false;
00470   if (isTwoAddrUse(UseMI, Reg, DstReg)) {
00471     IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
00472     return &UseMI;
00473   }
00474   return nullptr;
00475 }
00476 
00477 /// getMappedReg - Return the physical register the specified virtual register
00478 /// might be mapped to.
00479 static unsigned
00480 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
00481   while (TargetRegisterInfo::isVirtualRegister(Reg))  {
00482     DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
00483     if (SI == RegMap.end())
00484       return 0;
00485     Reg = SI->second;
00486   }
00487   if (TargetRegisterInfo::isPhysicalRegister(Reg))
00488     return Reg;
00489   return 0;
00490 }
00491 
00492 /// regsAreCompatible - Return true if the two registers are equal or aliased.
00493 ///
00494 static bool
00495 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
00496   if (RegA == RegB)
00497     return true;
00498   if (!RegA || !RegB)
00499     return false;
00500   return TRI->regsOverlap(RegA, RegB);
00501 }
00502 
00503 
00504 /// isProfitableToCommute - Return true if it's potentially profitable to commute
00505 /// the two-address instruction that's being processed.
00506 bool
00507 TwoAddressInstructionPass::
00508 isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
00509                       MachineInstr *MI, unsigned Dist) {
00510   if (OptLevel == CodeGenOpt::None)
00511     return false;
00512 
00513   // Determine if it's profitable to commute this two address instruction. In
00514   // general, we want no uses between this instruction and the definition of
00515   // the two-address register.
00516   // e.g.
00517   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
00518   // %reg1029<def> = MOV8rr %reg1028
00519   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
00520   // insert => %reg1030<def> = MOV8rr %reg1028
00521   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
00522   // In this case, it might not be possible to coalesce the second MOV8rr
00523   // instruction if the first one is coalesced. So it would be profitable to
00524   // commute it:
00525   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
00526   // %reg1029<def> = MOV8rr %reg1028
00527   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
00528   // insert => %reg1030<def> = MOV8rr %reg1029
00529   // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
00530 
00531   if (!isPlainlyKilled(MI, regC, LIS))
00532     return false;
00533 
00534   // Ok, we have something like:
00535   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
00536   // let's see if it's worth commuting it.
00537 
00538   // Look for situations like this:
00539   // %reg1024<def> = MOV r1
00540   // %reg1025<def> = MOV r0
00541   // %reg1026<def> = ADD %reg1024, %reg1025
00542   // r0            = MOV %reg1026
00543   // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
00544   unsigned ToRegA = getMappedReg(regA, DstRegMap);
00545   if (ToRegA) {
00546     unsigned FromRegB = getMappedReg(regB, SrcRegMap);
00547     unsigned FromRegC = getMappedReg(regC, SrcRegMap);
00548     bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
00549     bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
00550     if (BComp != CComp)
00551       return !BComp && CComp;
00552   }
00553 
00554   // If there is a use of regC between its last def (could be livein) and this
00555   // instruction, then bail.
00556   unsigned LastDefC = 0;
00557   if (!noUseAfterLastDef(regC, Dist, LastDefC))
00558     return false;
00559 
00560   // If there is a use of regB between its last def (could be livein) and this
00561   // instruction, then go ahead and make this transformation.
00562   unsigned LastDefB = 0;
00563   if (!noUseAfterLastDef(regB, Dist, LastDefB))
00564     return true;
00565 
00566   // Since there are no intervening uses for both registers, then commute
00567   // if the def of regC is closer. Its live interval is shorter.
00568   return LastDefB && LastDefC && LastDefC > LastDefB;
00569 }
00570 
00571 /// commuteInstruction - Commute a two-address instruction and update the basic
00572 /// block, distance map, and live variables if needed. Return true if it is
00573 /// successful.
00574 bool TwoAddressInstructionPass::
00575 commuteInstruction(MachineBasicBlock::iterator &mi,
00576                    unsigned RegB, unsigned RegC, unsigned Dist) {
00577   MachineInstr *MI = mi;
00578   DEBUG(dbgs() << "2addr: COMMUTING  : " << *MI);
00579   MachineInstr *NewMI = TII->commuteInstruction(MI);
00580 
00581   if (NewMI == nullptr) {
00582     DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
00583     return false;
00584   }
00585 
00586   DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
00587   assert(NewMI == MI &&
00588          "TargetInstrInfo::commuteInstruction() should not return a new "
00589          "instruction unless it was requested.");
00590 
00591   // Update source register map.
00592   unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
00593   if (FromRegC) {
00594     unsigned RegA = MI->getOperand(0).getReg();
00595     SrcRegMap[RegA] = FromRegC;
00596   }
00597 
00598   return true;
00599 }
00600 
00601 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
00602 /// given 2-address instruction to a 3-address one.
00603 bool
00604 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
00605   // Look for situations like this:
00606   // %reg1024<def> = MOV r1
00607   // %reg1025<def> = MOV r0
00608   // %reg1026<def> = ADD %reg1024, %reg1025
00609   // r2            = MOV %reg1026
00610   // Turn ADD into a 3-address instruction to avoid a copy.
00611   unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
00612   if (!FromRegB)
00613     return false;
00614   unsigned ToRegA = getMappedReg(RegA, DstRegMap);
00615   return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
00616 }
00617 
00618 /// convertInstTo3Addr - Convert the specified two-address instruction into a
00619 /// three address one. Return true if this transformation was successful.
00620 bool
00621 TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
00622                                               MachineBasicBlock::iterator &nmi,
00623                                               unsigned RegA, unsigned RegB,
00624                                               unsigned Dist) {
00625   // FIXME: Why does convertToThreeAddress() need an iterator reference?
00626   MachineFunction::iterator MFI = MBB;
00627   MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
00628   assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
00629   if (!NewMI)
00630     return false;
00631 
00632   DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
00633   DEBUG(dbgs() << "2addr:         TO 3-ADDR: " << *NewMI);
00634   bool Sunk = false;
00635 
00636   if (LIS)
00637     LIS->ReplaceMachineInstrInMaps(mi, NewMI);
00638 
00639   if (NewMI->findRegisterUseOperand(RegB, false, TRI))
00640     // FIXME: Temporary workaround. If the new instruction doesn't
00641     // uses RegB, convertToThreeAddress must have created more
00642     // then one instruction.
00643     Sunk = sink3AddrInstruction(NewMI, RegB, mi);
00644 
00645   MBB->erase(mi); // Nuke the old inst.
00646 
00647   if (!Sunk) {
00648     DistanceMap.insert(std::make_pair(NewMI, Dist));
00649     mi = NewMI;
00650     nmi = std::next(mi);
00651   }
00652 
00653   // Update source and destination register maps.
00654   SrcRegMap.erase(RegA);
00655   DstRegMap.erase(RegB);
00656   return true;
00657 }
00658 
00659 /// scanUses - Scan forward recursively for only uses, update maps if the use
00660 /// is a copy or a two-address instruction.
00661 void
00662 TwoAddressInstructionPass::scanUses(unsigned DstReg) {
00663   SmallVector<unsigned, 4> VirtRegPairs;
00664   bool IsDstPhys;
00665   bool IsCopy = false;
00666   unsigned NewReg = 0;
00667   unsigned Reg = DstReg;
00668   while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
00669                                                       NewReg, IsDstPhys)) {
00670     if (IsCopy && !Processed.insert(UseMI))
00671       break;
00672 
00673     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
00674     if (DI != DistanceMap.end())
00675       // Earlier in the same MBB.Reached via a back edge.
00676       break;
00677 
00678     if (IsDstPhys) {
00679       VirtRegPairs.push_back(NewReg);
00680       break;
00681     }
00682     bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
00683     if (!isNew)
00684       assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
00685     VirtRegPairs.push_back(NewReg);
00686     Reg = NewReg;
00687   }
00688 
00689   if (!VirtRegPairs.empty()) {
00690     unsigned ToReg = VirtRegPairs.back();
00691     VirtRegPairs.pop_back();
00692     while (!VirtRegPairs.empty()) {
00693       unsigned FromReg = VirtRegPairs.back();
00694       VirtRegPairs.pop_back();
00695       bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
00696       if (!isNew)
00697         assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
00698       ToReg = FromReg;
00699     }
00700     bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
00701     if (!isNew)
00702       assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
00703   }
00704 }
00705 
00706 /// processCopy - If the specified instruction is not yet processed, process it
00707 /// if it's a copy. For a copy instruction, we find the physical registers the
00708 /// source and destination registers might be mapped to. These are kept in
00709 /// point-to maps used to determine future optimizations. e.g.
00710 /// v1024 = mov r0
00711 /// v1025 = mov r1
00712 /// v1026 = add v1024, v1025
00713 /// r1    = mov r1026
00714 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
00715 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
00716 /// potentially joined with r1 on the output side. It's worthwhile to commute
00717 /// 'add' to eliminate a copy.
00718 void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
00719   if (Processed.count(MI))
00720     return;
00721 
00722   bool IsSrcPhys, IsDstPhys;
00723   unsigned SrcReg, DstReg;
00724   if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
00725     return;
00726 
00727   if (IsDstPhys && !IsSrcPhys)
00728     DstRegMap.insert(std::make_pair(SrcReg, DstReg));
00729   else if (!IsDstPhys && IsSrcPhys) {
00730     bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
00731     if (!isNew)
00732       assert(SrcRegMap[DstReg] == SrcReg &&
00733              "Can't map to two src physical registers!");
00734 
00735     scanUses(DstReg);
00736   }
00737 
00738   Processed.insert(MI);
00739   return;
00740 }
00741 
00742 /// rescheduleMIBelowKill - If there is one more local instruction that reads
00743 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
00744 /// instruction in order to eliminate the need for the copy.
00745 bool TwoAddressInstructionPass::
00746 rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
00747                       MachineBasicBlock::iterator &nmi,
00748                       unsigned Reg) {
00749   // Bail immediately if we don't have LV or LIS available. We use them to find
00750   // kills efficiently.
00751   if (!LV && !LIS)
00752     return false;
00753 
00754   MachineInstr *MI = &*mi;
00755   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
00756   if (DI == DistanceMap.end())
00757     // Must be created from unfolded load. Don't waste time trying this.
00758     return false;
00759 
00760   MachineInstr *KillMI = nullptr;
00761   if (LIS) {
00762     LiveInterval &LI = LIS->getInterval(Reg);
00763     assert(LI.end() != LI.begin() &&
00764            "Reg should not have empty live interval.");
00765 
00766     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
00767     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
00768     if (I != LI.end() && I->start < MBBEndIdx)
00769       return false;
00770 
00771     --I;
00772     KillMI = LIS->getInstructionFromIndex(I->end);
00773   } else {
00774     KillMI = LV->getVarInfo(Reg).findKill(MBB);
00775   }
00776   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
00777     // Don't mess with copies, they may be coalesced later.
00778     return false;
00779 
00780   if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
00781       KillMI->isBranch() || KillMI->isTerminator())
00782     // Don't move pass calls, etc.
00783     return false;
00784 
00785   unsigned DstReg;
00786   if (isTwoAddrUse(*KillMI, Reg, DstReg))
00787     return false;
00788 
00789   bool SeenStore = true;
00790   if (!MI->isSafeToMove(TII, AA, SeenStore))
00791     return false;
00792 
00793   if (TII->getInstrLatency(InstrItins, MI) > 1)
00794     // FIXME: Needs more sophisticated heuristics.
00795     return false;
00796 
00797   SmallSet<unsigned, 2> Uses;
00798   SmallSet<unsigned, 2> Kills;
00799   SmallSet<unsigned, 2> Defs;
00800   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00801     const MachineOperand &MO = MI->getOperand(i);
00802     if (!MO.isReg())
00803       continue;
00804     unsigned MOReg = MO.getReg();
00805     if (!MOReg)
00806       continue;
00807     if (MO.isDef())
00808       Defs.insert(MOReg);
00809     else {
00810       Uses.insert(MOReg);
00811       if (MOReg != Reg && (MO.isKill() ||
00812                            (LIS && isPlainlyKilled(MI, MOReg, LIS))))
00813         Kills.insert(MOReg);
00814     }
00815   }
00816 
00817   // Move the copies connected to MI down as well.
00818   MachineBasicBlock::iterator Begin = MI;
00819   MachineBasicBlock::iterator AfterMI = std::next(Begin);
00820 
00821   MachineBasicBlock::iterator End = AfterMI;
00822   while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
00823     Defs.insert(End->getOperand(0).getReg());
00824     ++End;
00825   }
00826 
00827   // Check if the reschedule will not break depedencies.
00828   unsigned NumVisited = 0;
00829   MachineBasicBlock::iterator KillPos = KillMI;
00830   ++KillPos;
00831   for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
00832     MachineInstr *OtherMI = I;
00833     // DBG_VALUE cannot be counted against the limit.
00834     if (OtherMI->isDebugValue())
00835       continue;
00836     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
00837       return false;
00838     ++NumVisited;
00839     if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
00840         OtherMI->isBranch() || OtherMI->isTerminator())
00841       // Don't move pass calls, etc.
00842       return false;
00843     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
00844       const MachineOperand &MO = OtherMI->getOperand(i);
00845       if (!MO.isReg())
00846         continue;
00847       unsigned MOReg = MO.getReg();
00848       if (!MOReg)
00849         continue;
00850       if (MO.isDef()) {
00851         if (Uses.count(MOReg))
00852           // Physical register use would be clobbered.
00853           return false;
00854         if (!MO.isDead() && Defs.count(MOReg))
00855           // May clobber a physical register def.
00856           // FIXME: This may be too conservative. It's ok if the instruction
00857           // is sunken completely below the use.
00858           return false;
00859       } else {
00860         if (Defs.count(MOReg))
00861           return false;
00862         bool isKill = MO.isKill() ||
00863                       (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
00864         if (MOReg != Reg &&
00865             ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
00866           // Don't want to extend other live ranges and update kills.
00867           return false;
00868         if (MOReg == Reg && !isKill)
00869           // We can't schedule across a use of the register in question.
00870           return false;
00871         // Ensure that if this is register in question, its the kill we expect.
00872         assert((MOReg != Reg || OtherMI == KillMI) &&
00873                "Found multiple kills of a register in a basic block");
00874       }
00875     }
00876   }
00877 
00878   // Move debug info as well.
00879   while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
00880     --Begin;
00881 
00882   nmi = End;
00883   MachineBasicBlock::iterator InsertPos = KillPos;
00884   if (LIS) {
00885     // We have to move the copies first so that the MBB is still well-formed
00886     // when calling handleMove().
00887     for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
00888       MachineInstr *CopyMI = MBBI;
00889       ++MBBI;
00890       MBB->splice(InsertPos, MBB, CopyMI);
00891       LIS->handleMove(CopyMI);
00892       InsertPos = CopyMI;
00893     }
00894     End = std::next(MachineBasicBlock::iterator(MI));
00895   }
00896 
00897   // Copies following MI may have been moved as well.
00898   MBB->splice(InsertPos, MBB, Begin, End);
00899   DistanceMap.erase(DI);
00900 
00901   // Update live variables
00902   if (LIS) {
00903     LIS->handleMove(MI);
00904   } else {
00905     LV->removeVirtualRegisterKilled(Reg, KillMI);
00906     LV->addVirtualRegisterKilled(Reg, MI);
00907   }
00908 
00909   DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
00910   return true;
00911 }
00912 
00913 /// isDefTooClose - Return true if the re-scheduling will put the given
00914 /// instruction too close to the defs of its register dependencies.
00915 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
00916                                               MachineInstr *MI) {
00917   for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
00918     if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
00919       continue;
00920     if (&DefMI == MI)
00921       return true; // MI is defining something KillMI uses
00922     DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
00923     if (DDI == DistanceMap.end())
00924       return true;  // Below MI
00925     unsigned DefDist = DDI->second;
00926     assert(Dist > DefDist && "Visited def already?");
00927     if (TII->getInstrLatency(InstrItins, &DefMI) > (Dist - DefDist))
00928       return true;
00929   }
00930   return false;
00931 }
00932 
00933 /// rescheduleKillAboveMI - If there is one more local instruction that reads
00934 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
00935 /// current two-address instruction in order to eliminate the need for the
00936 /// copy.
00937 bool TwoAddressInstructionPass::
00938 rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
00939                       MachineBasicBlock::iterator &nmi,
00940                       unsigned Reg) {
00941   // Bail immediately if we don't have LV or LIS available. We use them to find
00942   // kills efficiently.
00943   if (!LV && !LIS)
00944     return false;
00945 
00946   MachineInstr *MI = &*mi;
00947   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
00948   if (DI == DistanceMap.end())
00949     // Must be created from unfolded load. Don't waste time trying this.
00950     return false;
00951 
00952   MachineInstr *KillMI = nullptr;
00953   if (LIS) {
00954     LiveInterval &LI = LIS->getInterval(Reg);
00955     assert(LI.end() != LI.begin() &&
00956            "Reg should not have empty live interval.");
00957 
00958     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
00959     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
00960     if (I != LI.end() && I->start < MBBEndIdx)
00961       return false;
00962 
00963     --I;
00964     KillMI = LIS->getInstructionFromIndex(I->end);
00965   } else {
00966     KillMI = LV->getVarInfo(Reg).findKill(MBB);
00967   }
00968   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
00969     // Don't mess with copies, they may be coalesced later.
00970     return false;
00971 
00972   unsigned DstReg;
00973   if (isTwoAddrUse(*KillMI, Reg, DstReg))
00974     return false;
00975 
00976   bool SeenStore = true;
00977   if (!KillMI->isSafeToMove(TII, AA, SeenStore))
00978     return false;
00979 
00980   SmallSet<unsigned, 2> Uses;
00981   SmallSet<unsigned, 2> Kills;
00982   SmallSet<unsigned, 2> Defs;
00983   SmallSet<unsigned, 2> LiveDefs;
00984   for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
00985     const MachineOperand &MO = KillMI->getOperand(i);
00986     if (!MO.isReg())
00987       continue;
00988     unsigned MOReg = MO.getReg();
00989     if (MO.isUse()) {
00990       if (!MOReg)
00991         continue;
00992       if (isDefTooClose(MOReg, DI->second, MI))
00993         return false;
00994       bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
00995       if (MOReg == Reg && !isKill)
00996         return false;
00997       Uses.insert(MOReg);
00998       if (isKill && MOReg != Reg)
00999         Kills.insert(MOReg);
01000     } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
01001       Defs.insert(MOReg);
01002       if (!MO.isDead())
01003         LiveDefs.insert(MOReg);
01004     }
01005   }
01006 
01007   // Check if the reschedule will not break depedencies.
01008   unsigned NumVisited = 0;
01009   MachineBasicBlock::iterator KillPos = KillMI;
01010   for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
01011     MachineInstr *OtherMI = I;
01012     // DBG_VALUE cannot be counted against the limit.
01013     if (OtherMI->isDebugValue())
01014       continue;
01015     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
01016       return false;
01017     ++NumVisited;
01018     if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
01019         OtherMI->isBranch() || OtherMI->isTerminator())
01020       // Don't move pass calls, etc.
01021       return false;
01022     SmallVector<unsigned, 2> OtherDefs;
01023     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
01024       const MachineOperand &MO = OtherMI->getOperand(i);
01025       if (!MO.isReg())
01026         continue;
01027       unsigned MOReg = MO.getReg();
01028       if (!MOReg)
01029         continue;
01030       if (MO.isUse()) {
01031         if (Defs.count(MOReg))
01032           // Moving KillMI can clobber the physical register if the def has
01033           // not been seen.
01034           return false;
01035         if (Kills.count(MOReg))
01036           // Don't want to extend other live ranges and update kills.
01037           return false;
01038         if (OtherMI != MI && MOReg == Reg &&
01039             !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
01040           // We can't schedule across a use of the register in question.
01041           return false;
01042       } else {
01043         OtherDefs.push_back(MOReg);
01044       }
01045     }
01046 
01047     for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
01048       unsigned MOReg = OtherDefs[i];
01049       if (Uses.count(MOReg))
01050         return false;
01051       if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
01052           LiveDefs.count(MOReg))
01053         return false;
01054       // Physical register def is seen.
01055       Defs.erase(MOReg);
01056     }
01057   }
01058 
01059   // Move the old kill above MI, don't forget to move debug info as well.
01060   MachineBasicBlock::iterator InsertPos = mi;
01061   while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
01062     --InsertPos;
01063   MachineBasicBlock::iterator From = KillMI;
01064   MachineBasicBlock::iterator To = std::next(From);
01065   while (std::prev(From)->isDebugValue())
01066     --From;
01067   MBB->splice(InsertPos, MBB, From, To);
01068 
01069   nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
01070   DistanceMap.erase(DI);
01071 
01072   // Update live variables
01073   if (LIS) {
01074     LIS->handleMove(KillMI);
01075   } else {
01076     LV->removeVirtualRegisterKilled(Reg, KillMI);
01077     LV->addVirtualRegisterKilled(Reg, MI);
01078   }
01079 
01080   DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
01081   return true;
01082 }
01083 
01084 /// tryInstructionTransform - For the case where an instruction has a single
01085 /// pair of tied register operands, attempt some transformations that may
01086 /// either eliminate the tied operands or improve the opportunities for
01087 /// coalescing away the register copy.  Returns true if no copy needs to be
01088 /// inserted to untie mi's operands (either because they were untied, or
01089 /// because mi was rescheduled, and will be visited again later). If the
01090 /// shouldOnlyCommute flag is true, only instruction commutation is attempted.
01091 bool TwoAddressInstructionPass::
01092 tryInstructionTransform(MachineBasicBlock::iterator &mi,
01093                         MachineBasicBlock::iterator &nmi,
01094                         unsigned SrcIdx, unsigned DstIdx,
01095                         unsigned Dist, bool shouldOnlyCommute) {
01096   if (OptLevel == CodeGenOpt::None)
01097     return false;
01098 
01099   MachineInstr &MI = *mi;
01100   unsigned regA = MI.getOperand(DstIdx).getReg();
01101   unsigned regB = MI.getOperand(SrcIdx).getReg();
01102 
01103   assert(TargetRegisterInfo::isVirtualRegister(regB) &&
01104          "cannot make instruction into two-address form");
01105   bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
01106 
01107   if (TargetRegisterInfo::isVirtualRegister(regA))
01108     scanUses(regA);
01109 
01110   // Check if it is profitable to commute the operands.
01111   unsigned SrcOp1, SrcOp2;
01112   unsigned regC = 0;
01113   unsigned regCIdx = ~0U;
01114   bool TryCommute = false;
01115   bool AggressiveCommute = false;
01116   if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
01117       TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
01118     if (SrcIdx == SrcOp1)
01119       regCIdx = SrcOp2;
01120     else if (SrcIdx == SrcOp2)
01121       regCIdx = SrcOp1;
01122 
01123     if (regCIdx != ~0U) {
01124       regC = MI.getOperand(regCIdx).getReg();
01125       if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
01126         // If C dies but B does not, swap the B and C operands.
01127         // This makes the live ranges of A and C joinable.
01128         TryCommute = true;
01129       else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
01130         TryCommute = true;
01131         AggressiveCommute = true;
01132       }
01133     }
01134   }
01135 
01136   // If it's profitable to commute, try to do so.
01137   if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
01138     ++NumCommuted;
01139     if (AggressiveCommute)
01140       ++NumAggrCommuted;
01141     return false;
01142   }
01143 
01144   if (shouldOnlyCommute)
01145     return false;
01146 
01147   // If there is one more use of regB later in the same MBB, consider
01148   // re-schedule this MI below it.
01149   if (EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
01150     ++NumReSchedDowns;
01151     return true;
01152   }
01153 
01154   if (MI.isConvertibleTo3Addr()) {
01155     // This instruction is potentially convertible to a true
01156     // three-address instruction.  Check if it is profitable.
01157     if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
01158       // Try to convert it.
01159       if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
01160         ++NumConvertedTo3Addr;
01161         return true; // Done with this instruction.
01162       }
01163     }
01164   }
01165 
01166   // If there is one more use of regB later in the same MBB, consider
01167   // re-schedule it before this MI if it's legal.
01168   if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
01169     ++NumReSchedUps;
01170     return true;
01171   }
01172 
01173   // If this is an instruction with a load folded into it, try unfolding
01174   // the load, e.g. avoid this:
01175   //   movq %rdx, %rcx
01176   //   addq (%rax), %rcx
01177   // in favor of this:
01178   //   movq (%rax), %rcx
01179   //   addq %rdx, %rcx
01180   // because it's preferable to schedule a load than a register copy.
01181   if (MI.mayLoad() && !regBKilled) {
01182     // Determine if a load can be unfolded.
01183     unsigned LoadRegIndex;
01184     unsigned NewOpc =
01185       TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
01186                                       /*UnfoldLoad=*/true,
01187                                       /*UnfoldStore=*/false,
01188                                       &LoadRegIndex);
01189     if (NewOpc != 0) {
01190       const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
01191       if (UnfoldMCID.getNumDefs() == 1) {
01192         // Unfold the load.
01193         DEBUG(dbgs() << "2addr:   UNFOLDING: " << MI);
01194         const TargetRegisterClass *RC =
01195           TRI->getAllocatableClass(
01196             TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
01197         unsigned Reg = MRI->createVirtualRegister(RC);
01198         SmallVector<MachineInstr *, 2> NewMIs;
01199         if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
01200                                       /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
01201                                       NewMIs)) {
01202           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
01203           return false;
01204         }
01205         assert(NewMIs.size() == 2 &&
01206                "Unfolded a load into multiple instructions!");
01207         // The load was previously folded, so this is the only use.
01208         NewMIs[1]->addRegisterKilled(Reg, TRI);
01209 
01210         // Tentatively insert the instructions into the block so that they
01211         // look "normal" to the transformation logic.
01212         MBB->insert(mi, NewMIs[0]);
01213         MBB->insert(mi, NewMIs[1]);
01214 
01215         DEBUG(dbgs() << "2addr:    NEW LOAD: " << *NewMIs[0]
01216                      << "2addr:    NEW INST: " << *NewMIs[1]);
01217 
01218         // Transform the instruction, now that it no longer has a load.
01219         unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
01220         unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
01221         MachineBasicBlock::iterator NewMI = NewMIs[1];
01222         bool TransformResult =
01223           tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
01224         (void)TransformResult;
01225         assert(!TransformResult &&
01226                "tryInstructionTransform() should return false.");
01227         if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
01228           // Success, or at least we made an improvement. Keep the unfolded
01229           // instructions and discard the original.
01230           if (LV) {
01231             for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
01232               MachineOperand &MO = MI.getOperand(i);
01233               if (MO.isReg() &&
01234                   TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
01235                 if (MO.isUse()) {
01236                   if (MO.isKill()) {
01237                     if (NewMIs[0]->killsRegister(MO.getReg()))
01238                       LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
01239                     else {
01240                       assert(NewMIs[1]->killsRegister(MO.getReg()) &&
01241                              "Kill missing after load unfold!");
01242                       LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
01243                     }
01244                   }
01245                 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
01246                   if (NewMIs[1]->registerDefIsDead(MO.getReg()))
01247                     LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
01248                   else {
01249                     assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
01250                            "Dead flag missing after load unfold!");
01251                     LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
01252                   }
01253                 }
01254               }
01255             }
01256             LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
01257           }
01258 
01259           SmallVector<unsigned, 4> OrigRegs;
01260           if (LIS) {
01261             for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
01262                  MOE = MI.operands_end(); MOI != MOE; ++MOI) {
01263               if (MOI->isReg())
01264                 OrigRegs.push_back(MOI->getReg());
01265             }
01266           }
01267 
01268           MI.eraseFromParent();
01269 
01270           // Update LiveIntervals.
01271           if (LIS) {
01272             MachineBasicBlock::iterator Begin(NewMIs[0]);
01273             MachineBasicBlock::iterator End(NewMIs[1]);
01274             LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
01275           }
01276 
01277           mi = NewMIs[1];
01278         } else {
01279           // Transforming didn't eliminate the tie and didn't lead to an
01280           // improvement. Clean up the unfolded instructions and keep the
01281           // original.
01282           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
01283           NewMIs[0]->eraseFromParent();
01284           NewMIs[1]->eraseFromParent();
01285         }
01286       }
01287     }
01288   }
01289 
01290   return false;
01291 }
01292 
01293 // Collect tied operands of MI that need to be handled.
01294 // Rewrite trivial cases immediately.
01295 // Return true if any tied operands where found, including the trivial ones.
01296 bool TwoAddressInstructionPass::
01297 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
01298   const MCInstrDesc &MCID = MI->getDesc();
01299   bool AnyOps = false;
01300   unsigned NumOps = MI->getNumOperands();
01301 
01302   for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
01303     unsigned DstIdx = 0;
01304     if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
01305       continue;
01306     AnyOps = true;
01307     MachineOperand &SrcMO = MI->getOperand(SrcIdx);
01308     MachineOperand &DstMO = MI->getOperand(DstIdx);
01309     unsigned SrcReg = SrcMO.getReg();
01310     unsigned DstReg = DstMO.getReg();
01311     // Tied constraint already satisfied?
01312     if (SrcReg == DstReg)
01313       continue;
01314 
01315     assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
01316 
01317     // Deal with <undef> uses immediately - simply rewrite the src operand.
01318     if (SrcMO.isUndef() && !DstMO.getSubReg()) {
01319       // Constrain the DstReg register class if required.
01320       if (TargetRegisterInfo::isVirtualRegister(DstReg))
01321         if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
01322                                                              TRI, *MF))
01323           MRI->constrainRegClass(DstReg, RC);
01324       SrcMO.setReg(DstReg);
01325       SrcMO.setSubReg(0);
01326       DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
01327       continue;
01328     }
01329     TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
01330   }
01331   return AnyOps;
01332 }
01333 
01334 // Process a list of tied MI operands that all use the same source register.
01335 // The tied pairs are of the form (SrcIdx, DstIdx).
01336 void
01337 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
01338                                             TiedPairList &TiedPairs,
01339                                             unsigned &Dist) {
01340   bool IsEarlyClobber = false;
01341   for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
01342     const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
01343     IsEarlyClobber |= DstMO.isEarlyClobber();
01344   }
01345 
01346   bool RemovedKillFlag = false;
01347   bool AllUsesCopied = true;
01348   unsigned LastCopiedReg = 0;
01349   SlotIndex LastCopyIdx;
01350   unsigned RegB = 0;
01351   unsigned SubRegB = 0;
01352   for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
01353     unsigned SrcIdx = TiedPairs[tpi].first;
01354     unsigned DstIdx = TiedPairs[tpi].second;
01355 
01356     const MachineOperand &DstMO = MI->getOperand(DstIdx);
01357     unsigned RegA = DstMO.getReg();
01358 
01359     // Grab RegB from the instruction because it may have changed if the
01360     // instruction was commuted.
01361     RegB = MI->getOperand(SrcIdx).getReg();
01362     SubRegB = MI->getOperand(SrcIdx).getSubReg();
01363 
01364     if (RegA == RegB) {
01365       // The register is tied to multiple destinations (or else we would
01366       // not have continued this far), but this use of the register
01367       // already matches the tied destination.  Leave it.
01368       AllUsesCopied = false;
01369       continue;
01370     }
01371     LastCopiedReg = RegA;
01372 
01373     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
01374            "cannot make instruction into two-address form");
01375 
01376 #ifndef NDEBUG
01377     // First, verify that we don't have a use of "a" in the instruction
01378     // (a = b + a for example) because our transformation will not
01379     // work. This should never occur because we are in SSA form.
01380     for (unsigned i = 0; i != MI->getNumOperands(); ++i)
01381       assert(i == DstIdx ||
01382              !MI->getOperand(i).isReg() ||
01383              MI->getOperand(i).getReg() != RegA);
01384 #endif
01385 
01386     // Emit a copy.
01387     MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
01388                                       TII->get(TargetOpcode::COPY), RegA);
01389     // If this operand is folding a truncation, the truncation now moves to the
01390     // copy so that the register classes remain valid for the operands.
01391     MIB.addReg(RegB, 0, SubRegB);
01392     const TargetRegisterClass *RC = MRI->getRegClass(RegB);
01393     if (SubRegB) {
01394       if (TargetRegisterInfo::isVirtualRegister(RegA)) {
01395         assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
01396                                              SubRegB) &&
01397                "tied subregister must be a truncation");
01398         // The superreg class will not be used to constrain the subreg class.
01399         RC = nullptr;
01400       }
01401       else {
01402         assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
01403                && "tied subregister must be a truncation");
01404       }
01405     }
01406 
01407     // Update DistanceMap.
01408     MachineBasicBlock::iterator PrevMI = MI;
01409     --PrevMI;
01410     DistanceMap.insert(std::make_pair(PrevMI, Dist));
01411     DistanceMap[MI] = ++Dist;
01412 
01413     if (LIS) {
01414       LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
01415 
01416       if (TargetRegisterInfo::isVirtualRegister(RegA)) {
01417         LiveInterval &LI = LIS->getInterval(RegA);
01418         VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
01419         SlotIndex endIdx =
01420           LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
01421         LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
01422       }
01423     }
01424 
01425     DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
01426 
01427     MachineOperand &MO = MI->getOperand(SrcIdx);
01428     assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
01429            "inconsistent operand info for 2-reg pass");
01430     if (MO.isKill()) {
01431       MO.setIsKill(false);
01432       RemovedKillFlag = true;
01433     }
01434 
01435     // Make sure regA is a legal regclass for the SrcIdx operand.
01436     if (TargetRegisterInfo::isVirtualRegister(RegA) &&
01437         TargetRegisterInfo::isVirtualRegister(RegB))
01438       MRI->constrainRegClass(RegA, RC);
01439     MO.setReg(RegA);
01440     // The getMatchingSuper asserts guarantee that the register class projected
01441     // by SubRegB is compatible with RegA with no subregister. So regardless of
01442     // whether the dest oper writes a subreg, the source oper should not.
01443     MO.setSubReg(0);
01444 
01445     // Propagate SrcRegMap.
01446     SrcRegMap[RegA] = RegB;
01447   }
01448 
01449 
01450   if (AllUsesCopied) {
01451     if (!IsEarlyClobber) {
01452       // Replace other (un-tied) uses of regB with LastCopiedReg.
01453       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01454         MachineOperand &MO = MI->getOperand(i);
01455         if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
01456             MO.isUse()) {
01457           if (MO.isKill()) {
01458             MO.setIsKill(false);
01459             RemovedKillFlag = true;
01460           }
01461           MO.setReg(LastCopiedReg);
01462           MO.setSubReg(0);
01463         }
01464       }
01465     }
01466 
01467     // Update live variables for regB.
01468     if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
01469       MachineBasicBlock::iterator PrevMI = MI;
01470       --PrevMI;
01471       LV->addVirtualRegisterKilled(RegB, PrevMI);
01472     }
01473 
01474     // Update LiveIntervals.
01475     if (LIS) {
01476       LiveInterval &LI = LIS->getInterval(RegB);
01477       SlotIndex MIIdx = LIS->getInstructionIndex(MI);
01478       LiveInterval::const_iterator I = LI.find(MIIdx);
01479       assert(I != LI.end() && "RegB must be live-in to use.");
01480 
01481       SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
01482       if (I->end == UseIdx)
01483         LI.removeSegment(LastCopyIdx, UseIdx);
01484     }
01485 
01486   } else if (RemovedKillFlag) {
01487     // Some tied uses of regB matched their destination registers, so
01488     // regB is still used in this instruction, but a kill flag was
01489     // removed from a different tied use of regB, so now we need to add
01490     // a kill flag to one of the remaining uses of regB.
01491     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01492       MachineOperand &MO = MI->getOperand(i);
01493       if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
01494         MO.setIsKill(true);
01495         break;
01496       }
01497     }
01498   }
01499 }
01500 
01501 /// runOnMachineFunction - Reduce two-address instructions to two operands.
01502 ///
01503 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
01504   MF = &Func;
01505   const TargetMachine &TM = MF->getTarget();
01506   MRI = &MF->getRegInfo();
01507   TII = TM.getSubtargetImpl()->getInstrInfo();
01508   TRI = TM.getSubtargetImpl()->getRegisterInfo();
01509   InstrItins = TM.getSubtargetImpl()->getInstrItineraryData();
01510   LV = getAnalysisIfAvailable<LiveVariables>();
01511   LIS = getAnalysisIfAvailable<LiveIntervals>();
01512   AA = &getAnalysis<AliasAnalysis>();
01513   OptLevel = TM.getOptLevel();
01514 
01515   bool MadeChange = false;
01516 
01517   DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
01518   DEBUG(dbgs() << "********** Function: "
01519         << MF->getName() << '\n');
01520 
01521   // This pass takes the function out of SSA form.
01522   MRI->leaveSSA();
01523 
01524   TiedOperandMap TiedOperands;
01525   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
01526        MBBI != MBBE; ++MBBI) {
01527     MBB = MBBI;
01528     unsigned Dist = 0;
01529     DistanceMap.clear();
01530     SrcRegMap.clear();
01531     DstRegMap.clear();
01532     Processed.clear();
01533     for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
01534          mi != me; ) {
01535       MachineBasicBlock::iterator nmi = std::next(mi);
01536       if (mi->isDebugValue()) {
01537         mi = nmi;
01538         continue;
01539       }
01540 
01541       // Expand REG_SEQUENCE instructions. This will position mi at the first
01542       // expanded instruction.
01543       if (mi->isRegSequence())
01544         eliminateRegSequence(mi);
01545 
01546       DistanceMap.insert(std::make_pair(mi, ++Dist));
01547 
01548       processCopy(&*mi);
01549 
01550       // First scan through all the tied register uses in this instruction
01551       // and record a list of pairs of tied operands for each register.
01552       if (!collectTiedOperands(mi, TiedOperands)) {
01553         mi = nmi;
01554         continue;
01555       }
01556 
01557       ++NumTwoAddressInstrs;
01558       MadeChange = true;
01559       DEBUG(dbgs() << '\t' << *mi);
01560 
01561       // If the instruction has a single pair of tied operands, try some
01562       // transformations that may either eliminate the tied operands or
01563       // improve the opportunities for coalescing away the register copy.
01564       if (TiedOperands.size() == 1) {
01565         SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
01566           = TiedOperands.begin()->second;
01567         if (TiedPairs.size() == 1) {
01568           unsigned SrcIdx = TiedPairs[0].first;
01569           unsigned DstIdx = TiedPairs[0].second;
01570           unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
01571           unsigned DstReg = mi->getOperand(DstIdx).getReg();
01572           if (SrcReg != DstReg &&
01573               tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
01574             // The tied operands have been eliminated or shifted further down the
01575             // block to ease elimination. Continue processing with 'nmi'.
01576             TiedOperands.clear();
01577             mi = nmi;
01578             continue;
01579           }
01580         }
01581       }
01582 
01583       // Now iterate over the information collected above.
01584       for (TiedOperandMap::iterator OI = TiedOperands.begin(),
01585              OE = TiedOperands.end(); OI != OE; ++OI) {
01586         processTiedPairs(mi, OI->second, Dist);
01587         DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
01588       }
01589 
01590       // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
01591       if (mi->isInsertSubreg()) {
01592         // From %reg = INSERT_SUBREG %reg, %subreg, subidx
01593         // To   %reg:subidx = COPY %subreg
01594         unsigned SubIdx = mi->getOperand(3).getImm();
01595         mi->RemoveOperand(3);
01596         assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
01597         mi->getOperand(0).setSubReg(SubIdx);
01598         mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
01599         mi->RemoveOperand(1);
01600         mi->setDesc(TII->get(TargetOpcode::COPY));
01601         DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
01602       }
01603 
01604       // Clear TiedOperands here instead of at the top of the loop
01605       // since most instructions do not have tied operands.
01606       TiedOperands.clear();
01607       mi = nmi;
01608     }
01609   }
01610 
01611   if (LIS)
01612     MF->verify(this, "After two-address instruction pass");
01613 
01614   return MadeChange;
01615 }
01616 
01617 /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
01618 ///
01619 /// The instruction is turned into a sequence of sub-register copies:
01620 ///
01621 ///   %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
01622 ///
01623 /// Becomes:
01624 ///
01625 ///   %dst:ssub0<def,undef> = COPY %v1
01626 ///   %dst:ssub1<def> = COPY %v2
01627 ///
01628 void TwoAddressInstructionPass::
01629 eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
01630   MachineInstr *MI = MBBI;
01631   unsigned DstReg = MI->getOperand(0).getReg();
01632   if (MI->getOperand(0).getSubReg() ||
01633       TargetRegisterInfo::isPhysicalRegister(DstReg) ||
01634       !(MI->getNumOperands() & 1)) {
01635     DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
01636     llvm_unreachable(nullptr);
01637   }
01638 
01639   SmallVector<unsigned, 4> OrigRegs;
01640   if (LIS) {
01641     OrigRegs.push_back(MI->getOperand(0).getReg());
01642     for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
01643       OrigRegs.push_back(MI->getOperand(i).getReg());
01644   }
01645 
01646   bool DefEmitted = false;
01647   for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
01648     MachineOperand &UseMO = MI->getOperand(i);
01649     unsigned SrcReg = UseMO.getReg();
01650     unsigned SubIdx = MI->getOperand(i+1).getImm();
01651     // Nothing needs to be inserted for <undef> operands.
01652     if (UseMO.isUndef())
01653       continue;
01654 
01655     // Defer any kill flag to the last operand using SrcReg. Otherwise, we
01656     // might insert a COPY that uses SrcReg after is was killed.
01657     bool isKill = UseMO.isKill();
01658     if (isKill)
01659       for (unsigned j = i + 2; j < e; j += 2)
01660         if (MI->getOperand(j).getReg() == SrcReg) {
01661           MI->getOperand(j).setIsKill();
01662           UseMO.setIsKill(false);
01663           isKill = false;
01664           break;
01665         }
01666 
01667     // Insert the sub-register copy.
01668     MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
01669                                    TII->get(TargetOpcode::COPY))
01670       .addReg(DstReg, RegState::Define, SubIdx)
01671       .addOperand(UseMO);
01672 
01673     // The first def needs an <undef> flag because there is no live register
01674     // before it.
01675     if (!DefEmitted) {
01676       CopyMI->getOperand(0).setIsUndef(true);
01677       // Return an iterator pointing to the first inserted instr.
01678       MBBI = CopyMI;
01679     }
01680     DefEmitted = true;
01681 
01682     // Update LiveVariables' kill info.
01683     if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
01684       LV->replaceKillInstruction(SrcReg, MI, CopyMI);
01685 
01686     DEBUG(dbgs() << "Inserted: " << *CopyMI);
01687   }
01688 
01689   MachineBasicBlock::iterator EndMBBI =
01690       std::next(MachineBasicBlock::iterator(MI));
01691 
01692   if (!DefEmitted) {
01693     DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
01694     MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
01695     for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
01696       MI->RemoveOperand(j);
01697   } else {
01698     DEBUG(dbgs() << "Eliminated: " << *MI);
01699     MI->eraseFromParent();
01700   }
01701 
01702   // Udpate LiveIntervals.
01703   if (LIS)
01704     LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
01705 }