1//===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the TwoAddress instruction pass which is used
11// by most register allocators. Two-Address instructions are rewritten
12// from:
13//
14//     A = B op C
15//
16// to:
17//
18//     A = B
19//     A op= C
20//
21// Note that if a register allocator chooses to use this pass, that it
22// has to be capable of handling the non-SSA nature of these rewritten
23// virtual registers.
24//
25// It is also worth noting that the duplicate operand of the two
26// address instruction is removed.
27//
28//===----------------------------------------------------------------------===//
29
30#define DEBUG_TYPE "twoaddrinstr"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/Function.h"
33#include "llvm/CodeGen/LiveIntervalAnalysis.h"
34#include "llvm/CodeGen/LiveVariables.h"
35#include "llvm/CodeGen/MachineFunctionPass.h"
36#include "llvm/CodeGen/MachineInstr.h"
37#include "llvm/CodeGen/MachineInstrBuilder.h"
38#include "llvm/CodeGen/MachineRegisterInfo.h"
39#include "llvm/Analysis/AliasAnalysis.h"
40#include "llvm/MC/MCInstrItineraries.h"
41#include "llvm/Target/TargetRegisterInfo.h"
42#include "llvm/Target/TargetInstrInfo.h"
43#include "llvm/Target/TargetMachine.h"
44#include "llvm/Target/TargetOptions.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/ADT/BitVector.h"
48#include "llvm/ADT/DenseMap.h"
49#include "llvm/ADT/SmallSet.h"
50#include "llvm/ADT/Statistic.h"
51#include "llvm/ADT/STLExtras.h"
52using namespace llvm;
53
54STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
55STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
56STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
57STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
58STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
59STATISTIC(NumReSchedUps,       "Number of instructions re-scheduled up");
60STATISTIC(NumReSchedDowns,     "Number of instructions re-scheduled down");
61
62namespace {
63  class TwoAddressInstructionPass : public MachineFunctionPass {
64    MachineFunction *MF;
65    const TargetInstrInfo *TII;
66    const TargetRegisterInfo *TRI;
67    const InstrItineraryData *InstrItins;
68    MachineRegisterInfo *MRI;
69    LiveVariables *LV;
70    SlotIndexes *Indexes;
71    LiveIntervals *LIS;
72    AliasAnalysis *AA;
73    CodeGenOpt::Level OptLevel;
74
75    // DistanceMap - Keep track the distance of a MI from the start of the
76    // current basic block.
77    DenseMap<MachineInstr*, unsigned> DistanceMap;
78
79    // SrcRegMap - A map from virtual registers to physical registers which
80    // are likely targets to be coalesced to due to copies from physical
81    // registers to virtual registers. e.g. v1024 = move r0.
82    DenseMap<unsigned, unsigned> SrcRegMap;
83
84    // DstRegMap - A map from virtual registers to physical registers which
85    // are likely targets to be coalesced to due to copies to physical
86    // registers from virtual registers. e.g. r1 = move v1024.
87    DenseMap<unsigned, unsigned> DstRegMap;
88
89    /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
90    /// during the initial walk of the machine function.
91    SmallVector<MachineInstr*, 16> RegSequences;
92
93    bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
94                              unsigned Reg,
95                              MachineBasicBlock::iterator OldPos);
96
97    bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
98                           unsigned &LastDef);
99
100    bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
101                               MachineInstr *MI, MachineBasicBlock *MBB,
102                               unsigned Dist);
103
104    bool CommuteInstruction(MachineBasicBlock::iterator &mi,
105                            MachineFunction::iterator &mbbi,
106                            unsigned RegB, unsigned RegC, unsigned Dist);
107
108    bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
109
110    bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
111                            MachineBasicBlock::iterator &nmi,
112                            MachineFunction::iterator &mbbi,
113                            unsigned RegA, unsigned RegB, unsigned Dist);
114
115    bool isDefTooClose(unsigned Reg, unsigned Dist,
116                       MachineInstr *MI, MachineBasicBlock *MBB);
117
118    bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
119                               MachineBasicBlock::iterator &mi,
120                               MachineBasicBlock::iterator &nmi,
121                               unsigned Reg);
122    bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
123                               MachineBasicBlock::iterator &mi,
124                               MachineBasicBlock::iterator &nmi,
125                               unsigned Reg);
126
127    bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
128                                 MachineBasicBlock::iterator &nmi,
129                                 MachineFunction::iterator &mbbi,
130                                 unsigned SrcIdx, unsigned DstIdx,
131                                 unsigned Dist,
132                                 SmallPtrSet<MachineInstr*, 8> &Processed);
133
134    void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
135                  SmallPtrSet<MachineInstr*, 8> &Processed);
136
137    void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
138                     SmallPtrSet<MachineInstr*, 8> &Processed);
139
140    typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
141    typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
142    bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
143    void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
144
145    void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
146
147    /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
148    /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
149    /// sub-register references of the register defined by REG_SEQUENCE.
150    bool EliminateRegSequences();
151
152  public:
153    static char ID; // Pass identification, replacement for typeid
154    TwoAddressInstructionPass() : MachineFunctionPass(ID) {
155      initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
156    }
157
158    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
159      AU.setPreservesCFG();
160      AU.addRequired<AliasAnalysis>();
161      AU.addPreserved<LiveVariables>();
162      AU.addPreserved<SlotIndexes>();
163      AU.addPreserved<LiveIntervals>();
164      AU.addPreservedID(MachineLoopInfoID);
165      AU.addPreservedID(MachineDominatorsID);
166      MachineFunctionPass::getAnalysisUsage(AU);
167    }
168
169    /// runOnMachineFunction - Pass entry point.
170    bool runOnMachineFunction(MachineFunction&);
171  };
172}
173
174char TwoAddressInstructionPass::ID = 0;
175INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
176                "Two-Address instruction pass", false, false)
177INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
178INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
179                "Two-Address instruction pass", false, false)
180
181char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
182
183/// Sink3AddrInstruction - A two-address instruction has been converted to a
184/// three-address instruction to avoid clobbering a register. Try to sink it
185/// past the instruction that would kill the above mentioned register to reduce
186/// register pressure.
187bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
188                                           MachineInstr *MI, unsigned SavedReg,
189                                           MachineBasicBlock::iterator OldPos) {
190  // FIXME: Shouldn't we be trying to do this before we three-addressify the
191  // instruction?  After this transformation is done, we no longer need
192  // the instruction to be in three-address form.
193
194  // Check if it's safe to move this instruction.
195  bool SeenStore = true; // Be conservative.
196  if (!MI->isSafeToMove(TII, AA, SeenStore))
197    return false;
198
199  unsigned DefReg = 0;
200  SmallSet<unsigned, 4> UseRegs;
201
202  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
203    const MachineOperand &MO = MI->getOperand(i);
204    if (!MO.isReg())
205      continue;
206    unsigned MOReg = MO.getReg();
207    if (!MOReg)
208      continue;
209    if (MO.isUse() && MOReg != SavedReg)
210      UseRegs.insert(MO.getReg());
211    if (!MO.isDef())
212      continue;
213    if (MO.isImplicit())
214      // Don't try to move it if it implicitly defines a register.
215      return false;
216    if (DefReg)
217      // For now, don't move any instructions that define multiple registers.
218      return false;
219    DefReg = MO.getReg();
220  }
221
222  // Find the instruction that kills SavedReg.
223  MachineInstr *KillMI = NULL;
224  for (MachineRegisterInfo::use_nodbg_iterator
225         UI = MRI->use_nodbg_begin(SavedReg),
226         UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
227    MachineOperand &UseMO = UI.getOperand();
228    if (!UseMO.isKill())
229      continue;
230    KillMI = UseMO.getParent();
231    break;
232  }
233
234  // If we find the instruction that kills SavedReg, and it is in an
235  // appropriate location, we can try to sink the current instruction
236  // past it.
237  if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
238      KillMI == OldPos || KillMI->isTerminator())
239    return false;
240
241  // If any of the definitions are used by another instruction between the
242  // position and the kill use, then it's not safe to sink it.
243  //
244  // FIXME: This can be sped up if there is an easy way to query whether an
245  // instruction is before or after another instruction. Then we can use
246  // MachineRegisterInfo def / use instead.
247  MachineOperand *KillMO = NULL;
248  MachineBasicBlock::iterator KillPos = KillMI;
249  ++KillPos;
250
251  unsigned NumVisited = 0;
252  for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
253    MachineInstr *OtherMI = I;
254    // DBG_VALUE cannot be counted against the limit.
255    if (OtherMI->isDebugValue())
256      continue;
257    if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
258      return false;
259    ++NumVisited;
260    for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
261      MachineOperand &MO = OtherMI->getOperand(i);
262      if (!MO.isReg())
263        continue;
264      unsigned MOReg = MO.getReg();
265      if (!MOReg)
266        continue;
267      if (DefReg == MOReg)
268        return false;
269
270      if (MO.isKill()) {
271        if (OtherMI == KillMI && MOReg == SavedReg)
272          // Save the operand that kills the register. We want to unset the kill
273          // marker if we can sink MI past it.
274          KillMO = &MO;
275        else if (UseRegs.count(MOReg))
276          // One of the uses is killed before the destination.
277          return false;
278      }
279    }
280  }
281  assert(KillMO && "Didn't find kill");
282
283  // Update kill and LV information.
284  KillMO->setIsKill(false);
285  KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
286  KillMO->setIsKill(true);
287
288  if (LV)
289    LV->replaceKillInstruction(SavedReg, KillMI, MI);
290
291  // Move instruction to its destination.
292  MBB->remove(MI);
293  MBB->insert(KillPos, MI);
294
295  if (LIS)
296    LIS->handleMove(MI);
297
298  ++Num3AddrSunk;
299  return true;
300}
301
302/// NoUseAfterLastDef - Return true if there are no intervening uses between the
303/// last instruction in the MBB that defines the specified register and the
304/// two-address instruction which is being processed. It also returns the last
305/// def location by reference
306bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
307                                           MachineBasicBlock *MBB, unsigned Dist,
308                                           unsigned &LastDef) {
309  LastDef = 0;
310  unsigned LastUse = Dist;
311  for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
312         E = MRI->reg_end(); I != E; ++I) {
313    MachineOperand &MO = I.getOperand();
314    MachineInstr *MI = MO.getParent();
315    if (MI->getParent() != MBB || MI->isDebugValue())
316      continue;
317    DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
318    if (DI == DistanceMap.end())
319      continue;
320    if (MO.isUse() && DI->second < LastUse)
321      LastUse = DI->second;
322    if (MO.isDef() && DI->second > LastDef)
323      LastDef = DI->second;
324  }
325
326  return !(LastUse > LastDef && LastUse < Dist);
327}
328
329/// isCopyToReg - Return true if the specified MI is a copy instruction or
330/// a extract_subreg instruction. It also returns the source and destination
331/// registers and whether they are physical registers by reference.
332static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
333                        unsigned &SrcReg, unsigned &DstReg,
334                        bool &IsSrcPhys, bool &IsDstPhys) {
335  SrcReg = 0;
336  DstReg = 0;
337  if (MI.isCopy()) {
338    DstReg = MI.getOperand(0).getReg();
339    SrcReg = MI.getOperand(1).getReg();
340  } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
341    DstReg = MI.getOperand(0).getReg();
342    SrcReg = MI.getOperand(2).getReg();
343  } else
344    return false;
345
346  IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
347  IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
348  return true;
349}
350
351/// isKilled - Test if the given register value, which is used by the given
352/// instruction, is killed by the given instruction. This looks through
353/// coalescable copies to see if the original value is potentially not killed.
354///
355/// For example, in this code:
356///
357///   %reg1034 = copy %reg1024
358///   %reg1035 = copy %reg1025<kill>
359///   %reg1036 = add %reg1034<kill>, %reg1035<kill>
360///
361/// %reg1034 is not considered to be killed, since it is copied from a
362/// register which is not killed. Treating it as not killed lets the
363/// normal heuristics commute the (two-address) add, which lets
364/// coalescing eliminate the extra copy.
365///
366static bool isKilled(MachineInstr &MI, unsigned Reg,
367                     const MachineRegisterInfo *MRI,
368                     const TargetInstrInfo *TII) {
369  MachineInstr *DefMI = &MI;
370  for (;;) {
371    if (!DefMI->killsRegister(Reg))
372      return false;
373    if (TargetRegisterInfo::isPhysicalRegister(Reg))
374      return true;
375    MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
376    // If there are multiple defs, we can't do a simple analysis, so just
377    // go with what the kill flag says.
378    if (llvm::next(Begin) != MRI->def_end())
379      return true;
380    DefMI = &*Begin;
381    bool IsSrcPhys, IsDstPhys;
382    unsigned SrcReg,  DstReg;
383    // If the def is something other than a copy, then it isn't going to
384    // be coalesced, so follow the kill flag.
385    if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
386      return true;
387    Reg = SrcReg;
388  }
389}
390
391/// isTwoAddrUse - Return true if the specified MI uses the specified register
392/// as a two-address use. If so, return the destination register by reference.
393static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
394  const MCInstrDesc &MCID = MI.getDesc();
395  unsigned NumOps = MI.isInlineAsm()
396    ? MI.getNumOperands() : MCID.getNumOperands();
397  for (unsigned i = 0; i != NumOps; ++i) {
398    const MachineOperand &MO = MI.getOperand(i);
399    if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
400      continue;
401    unsigned ti;
402    if (MI.isRegTiedToDefOperand(i, &ti)) {
403      DstReg = MI.getOperand(ti).getReg();
404      return true;
405    }
406  }
407  return false;
408}
409
410/// findOnlyInterestingUse - Given a register, if has a single in-basic block
411/// use, return the use instruction if it's a copy or a two-address use.
412static
413MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
414                                     MachineRegisterInfo *MRI,
415                                     const TargetInstrInfo *TII,
416                                     bool &IsCopy,
417                                     unsigned &DstReg, bool &IsDstPhys) {
418  if (!MRI->hasOneNonDBGUse(Reg))
419    // None or more than one use.
420    return 0;
421  MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
422  if (UseMI.getParent() != MBB)
423    return 0;
424  unsigned SrcReg;
425  bool IsSrcPhys;
426  if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
427    IsCopy = true;
428    return &UseMI;
429  }
430  IsDstPhys = false;
431  if (isTwoAddrUse(UseMI, Reg, DstReg)) {
432    IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
433    return &UseMI;
434  }
435  return 0;
436}
437
438/// getMappedReg - Return the physical register the specified virtual register
439/// might be mapped to.
440static unsigned
441getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
442  while (TargetRegisterInfo::isVirtualRegister(Reg))  {
443    DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
444    if (SI == RegMap.end())
445      return 0;
446    Reg = SI->second;
447  }
448  if (TargetRegisterInfo::isPhysicalRegister(Reg))
449    return Reg;
450  return 0;
451}
452
453/// regsAreCompatible - Return true if the two registers are equal or aliased.
454///
455static bool
456regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
457  if (RegA == RegB)
458    return true;
459  if (!RegA || !RegB)
460    return false;
461  return TRI->regsOverlap(RegA, RegB);
462}
463
464
465/// isProfitableToCommute - Return true if it's potentially profitable to commute
466/// the two-address instruction that's being processed.
467bool
468TwoAddressInstructionPass::isProfitableToCommute(unsigned regA, unsigned regB,
469                                       unsigned regC,
470                                       MachineInstr *MI, MachineBasicBlock *MBB,
471                                       unsigned Dist) {
472  if (OptLevel == CodeGenOpt::None)
473    return false;
474
475  // Determine if it's profitable to commute this two address instruction. In
476  // general, we want no uses between this instruction and the definition of
477  // the two-address register.
478  // e.g.
479  // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
480  // %reg1029<def> = MOV8rr %reg1028
481  // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
482  // insert => %reg1030<def> = MOV8rr %reg1028
483  // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
484  // In this case, it might not be possible to coalesce the second MOV8rr
485  // instruction if the first one is coalesced. So it would be profitable to
486  // commute it:
487  // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
488  // %reg1029<def> = MOV8rr %reg1028
489  // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
490  // insert => %reg1030<def> = MOV8rr %reg1029
491  // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
492
493  if (!MI->killsRegister(regC))
494    return false;
495
496  // Ok, we have something like:
497  // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
498  // let's see if it's worth commuting it.
499
500  // Look for situations like this:
501  // %reg1024<def> = MOV r1
502  // %reg1025<def> = MOV r0
503  // %reg1026<def> = ADD %reg1024, %reg1025
504  // r0            = MOV %reg1026
505  // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
506  unsigned ToRegA = getMappedReg(regA, DstRegMap);
507  if (ToRegA) {
508    unsigned FromRegB = getMappedReg(regB, SrcRegMap);
509    unsigned FromRegC = getMappedReg(regC, SrcRegMap);
510    bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
511    bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
512    if (BComp != CComp)
513      return !BComp && CComp;
514  }
515
516  // If there is a use of regC between its last def (could be livein) and this
517  // instruction, then bail.
518  unsigned LastDefC = 0;
519  if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
520    return false;
521
522  // If there is a use of regB between its last def (could be livein) and this
523  // instruction, then go ahead and make this transformation.
524  unsigned LastDefB = 0;
525  if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
526    return true;
527
528  // Since there are no intervening uses for both registers, then commute
529  // if the def of regC is closer. Its live interval is shorter.
530  return LastDefB && LastDefC && LastDefC > LastDefB;
531}
532
533/// CommuteInstruction - Commute a two-address instruction and update the basic
534/// block, distance map, and live variables if needed. Return true if it is
535/// successful.
536bool
537TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
538                               MachineFunction::iterator &mbbi,
539                               unsigned RegB, unsigned RegC, unsigned Dist) {
540  MachineInstr *MI = mi;
541  DEBUG(dbgs() << "2addr: COMMUTING  : " << *MI);
542  MachineInstr *NewMI = TII->commuteInstruction(MI);
543
544  if (NewMI == 0) {
545    DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
546    return false;
547  }
548
549  DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
550  // If the instruction changed to commute it, update livevar.
551  if (NewMI != MI) {
552    if (LV)
553      // Update live variables
554      LV->replaceKillInstruction(RegC, MI, NewMI);
555    if (Indexes)
556      Indexes->replaceMachineInstrInMaps(MI, NewMI);
557
558    mbbi->insert(mi, NewMI);           // Insert the new inst
559    mbbi->erase(mi);                   // Nuke the old inst.
560    mi = NewMI;
561    DistanceMap.insert(std::make_pair(NewMI, Dist));
562  }
563
564  // Update source register map.
565  unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
566  if (FromRegC) {
567    unsigned RegA = MI->getOperand(0).getReg();
568    SrcRegMap[RegA] = FromRegC;
569  }
570
571  return true;
572}
573
574/// isProfitableToConv3Addr - Return true if it is profitable to convert the
575/// given 2-address instruction to a 3-address one.
576bool
577TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
578  // Look for situations like this:
579  // %reg1024<def> = MOV r1
580  // %reg1025<def> = MOV r0
581  // %reg1026<def> = ADD %reg1024, %reg1025
582  // r2            = MOV %reg1026
583  // Turn ADD into a 3-address instruction to avoid a copy.
584  unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
585  if (!FromRegB)
586    return false;
587  unsigned ToRegA = getMappedReg(RegA, DstRegMap);
588  return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
589}
590
591/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
592/// three address one. Return true if this transformation was successful.
593bool
594TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
595                                              MachineBasicBlock::iterator &nmi,
596                                              MachineFunction::iterator &mbbi,
597                                              unsigned RegA, unsigned RegB,
598                                              unsigned Dist) {
599  MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
600  if (NewMI) {
601    DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
602    DEBUG(dbgs() << "2addr:         TO 3-ADDR: " << *NewMI);
603    bool Sunk = false;
604
605    if (Indexes)
606      Indexes->replaceMachineInstrInMaps(mi, NewMI);
607
608    if (NewMI->findRegisterUseOperand(RegB, false, TRI))
609      // FIXME: Temporary workaround. If the new instruction doesn't
610      // uses RegB, convertToThreeAddress must have created more
611      // then one instruction.
612      Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
613
614    mbbi->erase(mi); // Nuke the old inst.
615
616    if (!Sunk) {
617      DistanceMap.insert(std::make_pair(NewMI, Dist));
618      mi = NewMI;
619      nmi = llvm::next(mi);
620    }
621
622    // Update source and destination register maps.
623    SrcRegMap.erase(RegA);
624    DstRegMap.erase(RegB);
625    return true;
626  }
627
628  return false;
629}
630
631/// ScanUses - Scan forward recursively for only uses, update maps if the use
632/// is a copy or a two-address instruction.
633void
634TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
635                                    SmallPtrSet<MachineInstr*, 8> &Processed) {
636  SmallVector<unsigned, 4> VirtRegPairs;
637  bool IsDstPhys;
638  bool IsCopy = false;
639  unsigned NewReg = 0;
640  unsigned Reg = DstReg;
641  while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
642                                                      NewReg, IsDstPhys)) {
643    if (IsCopy && !Processed.insert(UseMI))
644      break;
645
646    DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
647    if (DI != DistanceMap.end())
648      // Earlier in the same MBB.Reached via a back edge.
649      break;
650
651    if (IsDstPhys) {
652      VirtRegPairs.push_back(NewReg);
653      break;
654    }
655    bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
656    if (!isNew)
657      assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
658    VirtRegPairs.push_back(NewReg);
659    Reg = NewReg;
660  }
661
662  if (!VirtRegPairs.empty()) {
663    unsigned ToReg = VirtRegPairs.back();
664    VirtRegPairs.pop_back();
665    while (!VirtRegPairs.empty()) {
666      unsigned FromReg = VirtRegPairs.back();
667      VirtRegPairs.pop_back();
668      bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
669      if (!isNew)
670        assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
671      ToReg = FromReg;
672    }
673    bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
674    if (!isNew)
675      assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
676  }
677}
678
679/// ProcessCopy - If the specified instruction is not yet processed, process it
680/// if it's a copy. For a copy instruction, we find the physical registers the
681/// source and destination registers might be mapped to. These are kept in
682/// point-to maps used to determine future optimizations. e.g.
683/// v1024 = mov r0
684/// v1025 = mov r1
685/// v1026 = add v1024, v1025
686/// r1    = mov r1026
687/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
688/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
689/// potentially joined with r1 on the output side. It's worthwhile to commute
690/// 'add' to eliminate a copy.
691void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
692                                     MachineBasicBlock *MBB,
693                                     SmallPtrSet<MachineInstr*, 8> &Processed) {
694  if (Processed.count(MI))
695    return;
696
697  bool IsSrcPhys, IsDstPhys;
698  unsigned SrcReg, DstReg;
699  if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
700    return;
701
702  if (IsDstPhys && !IsSrcPhys)
703    DstRegMap.insert(std::make_pair(SrcReg, DstReg));
704  else if (!IsDstPhys && IsSrcPhys) {
705    bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
706    if (!isNew)
707      assert(SrcRegMap[DstReg] == SrcReg &&
708             "Can't map to two src physical registers!");
709
710    ScanUses(DstReg, MBB, Processed);
711  }
712
713  Processed.insert(MI);
714  return;
715}
716
717/// RescheduleMIBelowKill - If there is one more local instruction that reads
718/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
719/// instruction in order to eliminate the need for the copy.
720bool
721TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
722                                     MachineBasicBlock::iterator &mi,
723                                     MachineBasicBlock::iterator &nmi,
724                                     unsigned Reg) {
725  // Bail immediately if we don't have LV available. We use it to find kills
726  // efficiently.
727  if (!LV)
728    return false;
729
730  MachineInstr *MI = &*mi;
731  DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
732  if (DI == DistanceMap.end())
733    // Must be created from unfolded load. Don't waste time trying this.
734    return false;
735
736  MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
737  if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
738    // Don't mess with copies, they may be coalesced later.
739    return false;
740
741  if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
742      KillMI->isBranch() || KillMI->isTerminator())
743    // Don't move pass calls, etc.
744    return false;
745
746  unsigned DstReg;
747  if (isTwoAddrUse(*KillMI, Reg, DstReg))
748    return false;
749
750  bool SeenStore = true;
751  if (!MI->isSafeToMove(TII, AA, SeenStore))
752    return false;
753
754  if (TII->getInstrLatency(InstrItins, MI) > 1)
755    // FIXME: Needs more sophisticated heuristics.
756    return false;
757
758  SmallSet<unsigned, 2> Uses;
759  SmallSet<unsigned, 2> Kills;
760  SmallSet<unsigned, 2> Defs;
761  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
762    const MachineOperand &MO = MI->getOperand(i);
763    if (!MO.isReg())
764      continue;
765    unsigned MOReg = MO.getReg();
766    if (!MOReg)
767      continue;
768    if (MO.isDef())
769      Defs.insert(MOReg);
770    else {
771      Uses.insert(MOReg);
772      if (MO.isKill() && MOReg != Reg)
773        Kills.insert(MOReg);
774    }
775  }
776
777  // Move the copies connected to MI down as well.
778  MachineBasicBlock::iterator From = MI;
779  MachineBasicBlock::iterator To = llvm::next(From);
780  while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
781    Defs.insert(To->getOperand(0).getReg());
782    ++To;
783  }
784
785  // Check if the reschedule will not break depedencies.
786  unsigned NumVisited = 0;
787  MachineBasicBlock::iterator KillPos = KillMI;
788  ++KillPos;
789  for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
790    MachineInstr *OtherMI = I;
791    // DBG_VALUE cannot be counted against the limit.
792    if (OtherMI->isDebugValue())
793      continue;
794    if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
795      return false;
796    ++NumVisited;
797    if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
798        OtherMI->isBranch() || OtherMI->isTerminator())
799      // Don't move pass calls, etc.
800      return false;
801    for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
802      const MachineOperand &MO = OtherMI->getOperand(i);
803      if (!MO.isReg())
804        continue;
805      unsigned MOReg = MO.getReg();
806      if (!MOReg)
807        continue;
808      if (MO.isDef()) {
809        if (Uses.count(MOReg))
810          // Physical register use would be clobbered.
811          return false;
812        if (!MO.isDead() && Defs.count(MOReg))
813          // May clobber a physical register def.
814          // FIXME: This may be too conservative. It's ok if the instruction
815          // is sunken completely below the use.
816          return false;
817      } else {
818        if (Defs.count(MOReg))
819          return false;
820        if (MOReg != Reg &&
821            ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
822          // Don't want to extend other live ranges and update kills.
823          return false;
824        if (MOReg == Reg && !MO.isKill())
825          // We can't schedule across a use of the register in question.
826          return false;
827        // Ensure that if this is register in question, its the kill we expect.
828        assert((MOReg != Reg || OtherMI == KillMI) &&
829               "Found multiple kills of a register in a basic block");
830      }
831    }
832  }
833
834  // Move debug info as well.
835  while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
836    --From;
837
838  // Copies following MI may have been moved as well.
839  nmi = To;
840  MBB->splice(KillPos, MBB, From, To);
841  DistanceMap.erase(DI);
842
843  // Update live variables
844  LV->removeVirtualRegisterKilled(Reg, KillMI);
845  LV->addVirtualRegisterKilled(Reg, MI);
846  if (LIS)
847    LIS->handleMove(MI);
848
849  DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
850  return true;
851}
852
853/// isDefTooClose - Return true if the re-scheduling will put the given
854/// instruction too close to the defs of its register dependencies.
855bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
856                                              MachineInstr *MI,
857                                              MachineBasicBlock *MBB) {
858  for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
859         DE = MRI->def_end(); DI != DE; ++DI) {
860    MachineInstr *DefMI = &*DI;
861    if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
862      continue;
863    if (DefMI == MI)
864      return true; // MI is defining something KillMI uses
865    DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
866    if (DDI == DistanceMap.end())
867      return true;  // Below MI
868    unsigned DefDist = DDI->second;
869    assert(Dist > DefDist && "Visited def already?");
870    if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
871      return true;
872  }
873  return false;
874}
875
876/// RescheduleKillAboveMI - If there is one more local instruction that reads
877/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
878/// current two-address instruction in order to eliminate the need for the
879/// copy.
880bool
881TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
882                                     MachineBasicBlock::iterator &mi,
883                                     MachineBasicBlock::iterator &nmi,
884                                     unsigned Reg) {
885  // Bail immediately if we don't have LV available. We use it to find kills
886  // efficiently.
887  if (!LV)
888    return false;
889
890  MachineInstr *MI = &*mi;
891  DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
892  if (DI == DistanceMap.end())
893    // Must be created from unfolded load. Don't waste time trying this.
894    return false;
895
896  MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
897  if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
898    // Don't mess with copies, they may be coalesced later.
899    return false;
900
901  unsigned DstReg;
902  if (isTwoAddrUse(*KillMI, Reg, DstReg))
903    return false;
904
905  bool SeenStore = true;
906  if (!KillMI->isSafeToMove(TII, AA, SeenStore))
907    return false;
908
909  SmallSet<unsigned, 2> Uses;
910  SmallSet<unsigned, 2> Kills;
911  SmallSet<unsigned, 2> Defs;
912  SmallSet<unsigned, 2> LiveDefs;
913  for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
914    const MachineOperand &MO = KillMI->getOperand(i);
915    if (!MO.isReg())
916      continue;
917    unsigned MOReg = MO.getReg();
918    if (MO.isUse()) {
919      if (!MOReg)
920        continue;
921      if (isDefTooClose(MOReg, DI->second, MI, MBB))
922        return false;
923      if (MOReg == Reg && !MO.isKill())
924        return false;
925      Uses.insert(MOReg);
926      if (MO.isKill() && MOReg != Reg)
927        Kills.insert(MOReg);
928    } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
929      Defs.insert(MOReg);
930      if (!MO.isDead())
931        LiveDefs.insert(MOReg);
932    }
933  }
934
935  // Check if the reschedule will not break depedencies.
936  unsigned NumVisited = 0;
937  MachineBasicBlock::iterator KillPos = KillMI;
938  for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
939    MachineInstr *OtherMI = I;
940    // DBG_VALUE cannot be counted against the limit.
941    if (OtherMI->isDebugValue())
942      continue;
943    if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
944      return false;
945    ++NumVisited;
946    if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
947        OtherMI->isBranch() || OtherMI->isTerminator())
948      // Don't move pass calls, etc.
949      return false;
950    SmallVector<unsigned, 2> OtherDefs;
951    for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
952      const MachineOperand &MO = OtherMI->getOperand(i);
953      if (!MO.isReg())
954        continue;
955      unsigned MOReg = MO.getReg();
956      if (!MOReg)
957        continue;
958      if (MO.isUse()) {
959        if (Defs.count(MOReg))
960          // Moving KillMI can clobber the physical register if the def has
961          // not been seen.
962          return false;
963        if (Kills.count(MOReg))
964          // Don't want to extend other live ranges and update kills.
965          return false;
966        if (OtherMI != MI && MOReg == Reg && !MO.isKill())
967          // We can't schedule across a use of the register in question.
968          return false;
969      } else {
970        OtherDefs.push_back(MOReg);
971      }
972    }
973
974    for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
975      unsigned MOReg = OtherDefs[i];
976      if (Uses.count(MOReg))
977        return false;
978      if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
979          LiveDefs.count(MOReg))
980        return false;
981      // Physical register def is seen.
982      Defs.erase(MOReg);
983    }
984  }
985
986  // Move the old kill above MI, don't forget to move debug info as well.
987  MachineBasicBlock::iterator InsertPos = mi;
988  while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
989    --InsertPos;
990  MachineBasicBlock::iterator From = KillMI;
991  MachineBasicBlock::iterator To = llvm::next(From);
992  while (llvm::prior(From)->isDebugValue())
993    --From;
994  MBB->splice(InsertPos, MBB, From, To);
995
996  nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
997  DistanceMap.erase(DI);
998
999  // Update live variables
1000  LV->removeVirtualRegisterKilled(Reg, KillMI);
1001  LV->addVirtualRegisterKilled(Reg, MI);
1002  if (LIS)
1003    LIS->handleMove(KillMI);
1004
1005  DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1006  return true;
1007}
1008
1009/// TryInstructionTransform - For the case where an instruction has a single
1010/// pair of tied register operands, attempt some transformations that may
1011/// either eliminate the tied operands or improve the opportunities for
1012/// coalescing away the register copy.  Returns true if no copy needs to be
1013/// inserted to untie mi's operands (either because they were untied, or
1014/// because mi was rescheduled, and will be visited again later).
1015bool TwoAddressInstructionPass::
1016TryInstructionTransform(MachineBasicBlock::iterator &mi,
1017                        MachineBasicBlock::iterator &nmi,
1018                        MachineFunction::iterator &mbbi,
1019                        unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1020                        SmallPtrSet<MachineInstr*, 8> &Processed) {
1021  if (OptLevel == CodeGenOpt::None)
1022    return false;
1023
1024  MachineInstr &MI = *mi;
1025  unsigned regA = MI.getOperand(DstIdx).getReg();
1026  unsigned regB = MI.getOperand(SrcIdx).getReg();
1027
1028  assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1029         "cannot make instruction into two-address form");
1030  bool regBKilled = isKilled(MI, regB, MRI, TII);
1031
1032  if (TargetRegisterInfo::isVirtualRegister(regA))
1033    ScanUses(regA, &*mbbi, Processed);
1034
1035  // Check if it is profitable to commute the operands.
1036  unsigned SrcOp1, SrcOp2;
1037  unsigned regC = 0;
1038  unsigned regCIdx = ~0U;
1039  bool TryCommute = false;
1040  bool AggressiveCommute = false;
1041  if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
1042      TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
1043    if (SrcIdx == SrcOp1)
1044      regCIdx = SrcOp2;
1045    else if (SrcIdx == SrcOp2)
1046      regCIdx = SrcOp1;
1047
1048    if (regCIdx != ~0U) {
1049      regC = MI.getOperand(regCIdx).getReg();
1050      if (!regBKilled && isKilled(MI, regC, MRI, TII))
1051        // If C dies but B does not, swap the B and C operands.
1052        // This makes the live ranges of A and C joinable.
1053        TryCommute = true;
1054      else if (isProfitableToCommute(regA, regB, regC, &MI, mbbi, Dist)) {
1055        TryCommute = true;
1056        AggressiveCommute = true;
1057      }
1058    }
1059  }
1060
1061  // If it's profitable to commute, try to do so.
1062  if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1063    ++NumCommuted;
1064    if (AggressiveCommute)
1065      ++NumAggrCommuted;
1066    return false;
1067  }
1068
1069  // If there is one more use of regB later in the same MBB, consider
1070  // re-schedule this MI below it.
1071  if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1072    ++NumReSchedDowns;
1073    return true;
1074  }
1075
1076  if (MI.isConvertibleTo3Addr()) {
1077    // This instruction is potentially convertible to a true
1078    // three-address instruction.  Check if it is profitable.
1079    if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1080      // Try to convert it.
1081      if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
1082        ++NumConvertedTo3Addr;
1083        return true; // Done with this instruction.
1084      }
1085    }
1086  }
1087
1088  // If there is one more use of regB later in the same MBB, consider
1089  // re-schedule it before this MI if it's legal.
1090  if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1091    ++NumReSchedUps;
1092    return true;
1093  }
1094
1095  // If this is an instruction with a load folded into it, try unfolding
1096  // the load, e.g. avoid this:
1097  //   movq %rdx, %rcx
1098  //   addq (%rax), %rcx
1099  // in favor of this:
1100  //   movq (%rax), %rcx
1101  //   addq %rdx, %rcx
1102  // because it's preferable to schedule a load than a register copy.
1103  if (MI.mayLoad() && !regBKilled) {
1104    // Determine if a load can be unfolded.
1105    unsigned LoadRegIndex;
1106    unsigned NewOpc =
1107      TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1108                                      /*UnfoldLoad=*/true,
1109                                      /*UnfoldStore=*/false,
1110                                      &LoadRegIndex);
1111    if (NewOpc != 0) {
1112      const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1113      if (UnfoldMCID.getNumDefs() == 1) {
1114        // Unfold the load.
1115        DEBUG(dbgs() << "2addr:   UNFOLDING: " << MI);
1116        const TargetRegisterClass *RC =
1117          TRI->getAllocatableClass(
1118            TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
1119        unsigned Reg = MRI->createVirtualRegister(RC);
1120        SmallVector<MachineInstr *, 2> NewMIs;
1121        if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
1122                                      /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1123                                      NewMIs)) {
1124          DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1125          return false;
1126        }
1127        assert(NewMIs.size() == 2 &&
1128               "Unfolded a load into multiple instructions!");
1129        // The load was previously folded, so this is the only use.
1130        NewMIs[1]->addRegisterKilled(Reg, TRI);
1131
1132        // Tentatively insert the instructions into the block so that they
1133        // look "normal" to the transformation logic.
1134        mbbi->insert(mi, NewMIs[0]);
1135        mbbi->insert(mi, NewMIs[1]);
1136
1137        DEBUG(dbgs() << "2addr:    NEW LOAD: " << *NewMIs[0]
1138                     << "2addr:    NEW INST: " << *NewMIs[1]);
1139
1140        // Transform the instruction, now that it no longer has a load.
1141        unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1142        unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1143        MachineBasicBlock::iterator NewMI = NewMIs[1];
1144        bool TransformSuccess =
1145          TryInstructionTransform(NewMI, mi, mbbi,
1146                                  NewSrcIdx, NewDstIdx, Dist, Processed);
1147        if (TransformSuccess ||
1148            NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1149          // Success, or at least we made an improvement. Keep the unfolded
1150          // instructions and discard the original.
1151          if (LV) {
1152            for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1153              MachineOperand &MO = MI.getOperand(i);
1154              if (MO.isReg() &&
1155                  TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1156                if (MO.isUse()) {
1157                  if (MO.isKill()) {
1158                    if (NewMIs[0]->killsRegister(MO.getReg()))
1159                      LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1160                    else {
1161                      assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1162                             "Kill missing after load unfold!");
1163                      LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1164                    }
1165                  }
1166                } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1167                  if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1168                    LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1169                  else {
1170                    assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1171                           "Dead flag missing after load unfold!");
1172                    LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1173                  }
1174                }
1175              }
1176            }
1177            LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1178          }
1179          MI.eraseFromParent();
1180          mi = NewMIs[1];
1181          if (TransformSuccess)
1182            return true;
1183        } else {
1184          // Transforming didn't eliminate the tie and didn't lead to an
1185          // improvement. Clean up the unfolded instructions and keep the
1186          // original.
1187          DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1188          NewMIs[0]->eraseFromParent();
1189          NewMIs[1]->eraseFromParent();
1190        }
1191      }
1192    }
1193  }
1194
1195  return false;
1196}
1197
1198// Collect tied operands of MI that need to be handled.
1199// Rewrite trivial cases immediately.
1200// Return true if any tied operands where found, including the trivial ones.
1201bool TwoAddressInstructionPass::
1202collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1203  const MCInstrDesc &MCID = MI->getDesc();
1204  bool AnyOps = false;
1205  unsigned NumOps = MI->getNumOperands();
1206
1207  for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1208    unsigned DstIdx = 0;
1209    if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1210      continue;
1211    AnyOps = true;
1212    MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1213    MachineOperand &DstMO = MI->getOperand(DstIdx);
1214    unsigned SrcReg = SrcMO.getReg();
1215    unsigned DstReg = DstMO.getReg();
1216    // Tied constraint already satisfied?
1217    if (SrcReg == DstReg)
1218      continue;
1219
1220    assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1221
1222    // Deal with <undef> uses immediately - simply rewrite the src operand.
1223    if (SrcMO.isUndef()) {
1224      // Constrain the DstReg register class if required.
1225      if (TargetRegisterInfo::isVirtualRegister(DstReg))
1226        if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1227                                                             TRI, *MF))
1228          MRI->constrainRegClass(DstReg, RC);
1229      SrcMO.setReg(DstReg);
1230      DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1231      continue;
1232    }
1233    TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1234  }
1235  return AnyOps;
1236}
1237
1238// Process a list of tied MI operands that all use the same source register.
1239// The tied pairs are of the form (SrcIdx, DstIdx).
1240void
1241TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1242                                            TiedPairList &TiedPairs,
1243                                            unsigned &Dist) {
1244  bool IsEarlyClobber = false;
1245  bool RemovedKillFlag = false;
1246  bool AllUsesCopied = true;
1247  unsigned LastCopiedReg = 0;
1248  unsigned RegB = 0;
1249  for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1250    unsigned SrcIdx = TiedPairs[tpi].first;
1251    unsigned DstIdx = TiedPairs[tpi].second;
1252
1253    const MachineOperand &DstMO = MI->getOperand(DstIdx);
1254    unsigned RegA = DstMO.getReg();
1255    IsEarlyClobber |= DstMO.isEarlyClobber();
1256
1257    // Grab RegB from the instruction because it may have changed if the
1258    // instruction was commuted.
1259    RegB = MI->getOperand(SrcIdx).getReg();
1260
1261    if (RegA == RegB) {
1262      // The register is tied to multiple destinations (or else we would
1263      // not have continued this far), but this use of the register
1264      // already matches the tied destination.  Leave it.
1265      AllUsesCopied = false;
1266      continue;
1267    }
1268    LastCopiedReg = RegA;
1269
1270    assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1271           "cannot make instruction into two-address form");
1272
1273#ifndef NDEBUG
1274    // First, verify that we don't have a use of "a" in the instruction
1275    // (a = b + a for example) because our transformation will not
1276    // work. This should never occur because we are in SSA form.
1277    for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1278      assert(i == DstIdx ||
1279             !MI->getOperand(i).isReg() ||
1280             MI->getOperand(i).getReg() != RegA);
1281#endif
1282
1283    // Emit a copy.
1284    BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1285            TII->get(TargetOpcode::COPY), RegA).addReg(RegB);
1286
1287    // Update DistanceMap.
1288    MachineBasicBlock::iterator PrevMI = MI;
1289    --PrevMI;
1290    DistanceMap.insert(std::make_pair(PrevMI, Dist));
1291    DistanceMap[MI] = ++Dist;
1292
1293    SlotIndex CopyIdx;
1294    if (Indexes)
1295      CopyIdx = Indexes->insertMachineInstrInMaps(PrevMI).getRegSlot();
1296
1297    DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI);
1298
1299    MachineOperand &MO = MI->getOperand(SrcIdx);
1300    assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1301           "inconsistent operand info for 2-reg pass");
1302    if (MO.isKill()) {
1303      MO.setIsKill(false);
1304      RemovedKillFlag = true;
1305    }
1306
1307    // Make sure regA is a legal regclass for the SrcIdx operand.
1308    if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1309        TargetRegisterInfo::isVirtualRegister(RegB))
1310      MRI->constrainRegClass(RegA, MRI->getRegClass(RegB));
1311
1312    MO.setReg(RegA);
1313
1314    // Propagate SrcRegMap.
1315    SrcRegMap[RegA] = RegB;
1316  }
1317
1318
1319  if (AllUsesCopied) {
1320    if (!IsEarlyClobber) {
1321      // Replace other (un-tied) uses of regB with LastCopiedReg.
1322      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1323        MachineOperand &MO = MI->getOperand(i);
1324        if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1325          if (MO.isKill()) {
1326            MO.setIsKill(false);
1327            RemovedKillFlag = true;
1328          }
1329          MO.setReg(LastCopiedReg);
1330        }
1331      }
1332    }
1333
1334    // Update live variables for regB.
1335    if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1336      MachineBasicBlock::iterator PrevMI = MI;
1337      --PrevMI;
1338      LV->addVirtualRegisterKilled(RegB, PrevMI);
1339    }
1340
1341  } else if (RemovedKillFlag) {
1342    // Some tied uses of regB matched their destination registers, so
1343    // regB is still used in this instruction, but a kill flag was
1344    // removed from a different tied use of regB, so now we need to add
1345    // a kill flag to one of the remaining uses of regB.
1346    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1347      MachineOperand &MO = MI->getOperand(i);
1348      if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1349        MO.setIsKill(true);
1350        break;
1351      }
1352    }
1353  }
1354}
1355
1356/// runOnMachineFunction - Reduce two-address instructions to two operands.
1357///
1358bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1359  MF = &Func;
1360  const TargetMachine &TM = MF->getTarget();
1361  MRI = &MF->getRegInfo();
1362  TII = TM.getInstrInfo();
1363  TRI = TM.getRegisterInfo();
1364  InstrItins = TM.getInstrItineraryData();
1365  Indexes = getAnalysisIfAvailable<SlotIndexes>();
1366  LV = getAnalysisIfAvailable<LiveVariables>();
1367  LIS = getAnalysisIfAvailable<LiveIntervals>();
1368  AA = &getAnalysis<AliasAnalysis>();
1369  OptLevel = TM.getOptLevel();
1370
1371  bool MadeChange = false;
1372
1373  DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1374  DEBUG(dbgs() << "********** Function: "
1375        << MF->getName() << '\n');
1376
1377  // This pass takes the function out of SSA form.
1378  MRI->leaveSSA();
1379
1380  TiedOperandMap TiedOperands;
1381
1382  SmallPtrSet<MachineInstr*, 8> Processed;
1383  for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1384       mbbi != mbbe; ++mbbi) {
1385    unsigned Dist = 0;
1386    DistanceMap.clear();
1387    SrcRegMap.clear();
1388    DstRegMap.clear();
1389    Processed.clear();
1390    for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1391         mi != me; ) {
1392      MachineBasicBlock::iterator nmi = llvm::next(mi);
1393      if (mi->isDebugValue()) {
1394        mi = nmi;
1395        continue;
1396      }
1397
1398      // Remember REG_SEQUENCE instructions, we'll deal with them later.
1399      if (mi->isRegSequence())
1400        RegSequences.push_back(&*mi);
1401
1402      DistanceMap.insert(std::make_pair(mi, ++Dist));
1403
1404      ProcessCopy(&*mi, &*mbbi, Processed);
1405
1406      // First scan through all the tied register uses in this instruction
1407      // and record a list of pairs of tied operands for each register.
1408      if (!collectTiedOperands(mi, TiedOperands)) {
1409        mi = nmi;
1410        continue;
1411      }
1412
1413      ++NumTwoAddressInstrs;
1414      MadeChange = true;
1415      DEBUG(dbgs() << '\t' << *mi);
1416
1417      // If the instruction has a single pair of tied operands, try some
1418      // transformations that may either eliminate the tied operands or
1419      // improve the opportunities for coalescing away the register copy.
1420      if (TiedOperands.size() == 1) {
1421        SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1422          = TiedOperands.begin()->second;
1423        if (TiedPairs.size() == 1) {
1424          unsigned SrcIdx = TiedPairs[0].first;
1425          unsigned DstIdx = TiedPairs[0].second;
1426          unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1427          unsigned DstReg = mi->getOperand(DstIdx).getReg();
1428          if (SrcReg != DstReg &&
1429              TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1430                                      Processed)) {
1431            // The tied operands have been eliminated or shifted further down the
1432            // block to ease elimination. Continue processing with 'nmi'.
1433            TiedOperands.clear();
1434            mi = nmi;
1435            continue;
1436          }
1437        }
1438      }
1439
1440      // Now iterate over the information collected above.
1441      for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1442             OE = TiedOperands.end(); OI != OE; ++OI) {
1443        processTiedPairs(mi, OI->second, Dist);
1444        DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1445      }
1446
1447      // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1448      if (mi->isInsertSubreg()) {
1449        // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1450        // To   %reg:subidx = COPY %subreg
1451        unsigned SubIdx = mi->getOperand(3).getImm();
1452        mi->RemoveOperand(3);
1453        assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1454        mi->getOperand(0).setSubReg(SubIdx);
1455        mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1456        mi->RemoveOperand(1);
1457        mi->setDesc(TII->get(TargetOpcode::COPY));
1458        DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1459      }
1460
1461      // Clear TiedOperands here instead of at the top of the loop
1462      // since most instructions do not have tied operands.
1463      TiedOperands.clear();
1464      mi = nmi;
1465    }
1466  }
1467
1468  // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1469  // SSA form. It's now safe to de-SSA.
1470  MadeChange |= EliminateRegSequences();
1471
1472  return MadeChange;
1473}
1474
1475static void UpdateRegSequenceSrcs(unsigned SrcReg,
1476                                  unsigned DstReg, unsigned SubIdx,
1477                                  MachineRegisterInfo *MRI,
1478                                  const TargetRegisterInfo &TRI) {
1479  for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1480         RE = MRI->reg_end(); RI != RE; ) {
1481    MachineOperand &MO = RI.getOperand();
1482    ++RI;
1483    MO.substVirtReg(DstReg, SubIdx, TRI);
1484  }
1485}
1486
1487// Find the first def of Reg, assuming they are all in the same basic block.
1488static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
1489  SmallPtrSet<MachineInstr*, 8> Defs;
1490  MachineInstr *First = 0;
1491  for (MachineRegisterInfo::def_iterator RI = MRI->def_begin(Reg);
1492       MachineInstr *MI = RI.skipInstruction(); Defs.insert(MI))
1493    First = MI;
1494  if (!First)
1495    return 0;
1496
1497  MachineBasicBlock *MBB = First->getParent();
1498  MachineBasicBlock::iterator A = First, B = First;
1499  bool Moving;
1500  do {
1501    Moving = false;
1502    if (A != MBB->begin()) {
1503      Moving = true;
1504      --A;
1505      if (Defs.erase(A)) First = A;
1506    }
1507    if (B != MBB->end()) {
1508      Defs.erase(B);
1509      ++B;
1510      Moving = true;
1511    }
1512  } while (Moving && !Defs.empty());
1513  assert(Defs.empty() && "Instructions outside basic block!");
1514  return First;
1515}
1516
1517/// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1518/// EXTRACT_SUBREG from the same register and to the same virtual register
1519/// with different sub-register indices, attempt to combine the
1520/// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1521/// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1522/// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1523/// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1524/// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1525/// reg1026 to reg1029.
1526void
1527TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1528                                              unsigned DstReg) {
1529  SmallSet<unsigned, 4> Seen;
1530  for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1531    unsigned SrcReg = Srcs[i];
1532    if (!Seen.insert(SrcReg))
1533      continue;
1534
1535    // Check that the instructions are all in the same basic block.
1536    MachineInstr *SrcDefMI = MRI->getUniqueVRegDef(SrcReg);
1537    MachineInstr *DstDefMI = MRI->getUniqueVRegDef(DstReg);
1538    if (!SrcDefMI || !DstDefMI ||
1539        SrcDefMI->getParent() != DstDefMI->getParent())
1540      continue;
1541
1542    // If there are no other uses than copies which feed into
1543    // the reg_sequence, then we might be able to coalesce them.
1544    bool CanCoalesce = true;
1545    SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
1546    for (MachineRegisterInfo::use_nodbg_iterator
1547           UI = MRI->use_nodbg_begin(SrcReg),
1548           UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1549      MachineInstr *UseMI = &*UI;
1550      if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
1551        CanCoalesce = false;
1552        break;
1553      }
1554      SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
1555      DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
1556    }
1557
1558    if (!CanCoalesce || SrcSubIndices.size() < 2)
1559      continue;
1560
1561    // Check that the source subregisters can be combined.
1562    std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
1563    unsigned NewSrcSubIdx = 0;
1564    if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
1565                                      NewSrcSubIdx))
1566      continue;
1567
1568    // Check that the destination subregisters can also be combined.
1569    std::sort(DstSubIndices.begin(), DstSubIndices.end());
1570    unsigned NewDstSubIdx = 0;
1571    if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1572                                      NewDstSubIdx))
1573      continue;
1574
1575    // If neither source nor destination can be combined to the full register,
1576    // just give up.  This could be improved if it ever matters.
1577    if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1578      continue;
1579
1580    // Now that we know that all the uses are extract_subregs and that those
1581    // subregs can somehow be combined, scan all the extract_subregs again to
1582    // make sure the subregs are in the right order and can be composed.
1583    MachineInstr *SomeMI = 0;
1584    CanCoalesce = true;
1585    for (MachineRegisterInfo::use_nodbg_iterator
1586           UI = MRI->use_nodbg_begin(SrcReg),
1587           UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1588      MachineInstr *UseMI = &*UI;
1589      assert(UseMI->isCopy());
1590      unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
1591      unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
1592      assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
1593      if ((NewDstSubIdx == 0 &&
1594           TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1595          (NewSrcSubIdx == 0 &&
1596           TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
1597        CanCoalesce = false;
1598        break;
1599      }
1600      // Keep track of one of the uses.  Preferably the first one which has a
1601      // <def,undef> flag.
1602      if (!SomeMI || UseMI->getOperand(0).isUndef())
1603        SomeMI = UseMI;
1604    }
1605    if (!CanCoalesce)
1606      continue;
1607
1608    // Insert a copy to replace the original.
1609    MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1610                                   SomeMI->getDebugLoc(),
1611                                   TII->get(TargetOpcode::COPY))
1612      .addReg(DstReg, RegState::Define |
1613                      getUndefRegState(SomeMI->getOperand(0).isUndef()),
1614              NewDstSubIdx)
1615      .addReg(SrcReg, 0, NewSrcSubIdx);
1616
1617    // Remove all the old extract instructions.
1618    for (MachineRegisterInfo::use_nodbg_iterator
1619           UI = MRI->use_nodbg_begin(SrcReg),
1620           UE = MRI->use_nodbg_end(); UI != UE; ) {
1621      MachineInstr *UseMI = &*UI;
1622      ++UI;
1623      if (UseMI == CopyMI)
1624        continue;
1625      assert(UseMI->isCopy());
1626      // Move any kills to the new copy or extract instruction.
1627      if (UseMI->getOperand(1).isKill()) {
1628        CopyMI->getOperand(1).setIsKill();
1629        if (LV)
1630          // Update live variables
1631          LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1632      }
1633      UseMI->eraseFromParent();
1634    }
1635  }
1636}
1637
1638static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1639                                    MachineRegisterInfo *MRI) {
1640  for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1641         UE = MRI->use_end(); UI != UE; ++UI) {
1642    MachineInstr *UseMI = &*UI;
1643    if (UseMI != RegSeq && UseMI->isRegSequence())
1644      return true;
1645  }
1646  return false;
1647}
1648
1649/// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1650/// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1651/// sub-register references of the register defined by REG_SEQUENCE. e.g.
1652///
1653/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1654/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1655/// =>
1656/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1657bool TwoAddressInstructionPass::EliminateRegSequences() {
1658  if (RegSequences.empty())
1659    return false;
1660
1661  for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1662    MachineInstr *MI = RegSequences[i];
1663    unsigned DstReg = MI->getOperand(0).getReg();
1664    if (MI->getOperand(0).getSubReg() ||
1665        TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1666        !(MI->getNumOperands() & 1)) {
1667      DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1668      llvm_unreachable(0);
1669    }
1670
1671    bool IsImpDef = true;
1672    SmallVector<unsigned, 4> RealSrcs;
1673    SmallSet<unsigned, 4> Seen;
1674    for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1675      // Nothing needs to be inserted for <undef> operands.
1676      if (MI->getOperand(i).isUndef()) {
1677        MI->getOperand(i).setReg(0);
1678        continue;
1679      }
1680      unsigned SrcReg = MI->getOperand(i).getReg();
1681      unsigned SrcSubIdx = MI->getOperand(i).getSubReg();
1682      unsigned SubIdx = MI->getOperand(i+1).getImm();
1683      // DefMI of NULL means the value does not have a vreg in this block
1684      // i.e., its a physical register or a subreg.
1685      // In either case we force a copy to be generated.
1686      MachineInstr *DefMI = NULL;
1687      if (!MI->getOperand(i).getSubReg() &&
1688          !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1689        DefMI = MRI->getUniqueVRegDef(SrcReg);
1690      }
1691
1692      if (DefMI && DefMI->isImplicitDef()) {
1693        DefMI->eraseFromParent();
1694        continue;
1695      }
1696      IsImpDef = false;
1697
1698      // Remember COPY sources. These might be candidate for coalescing.
1699      if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1700        RealSrcs.push_back(DefMI->getOperand(1).getReg());
1701
1702      bool isKill = MI->getOperand(i).isKill();
1703      if (!DefMI || !Seen.insert(SrcReg) ||
1704          MI->getParent() != DefMI->getParent() ||
1705          !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1706          !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1707                                         MRI->getRegClass(SrcReg), SubIdx)) {
1708        // REG_SEQUENCE cannot have duplicated operands, add a copy.
1709        // Also add an copy if the source is live-in the block. We don't want
1710        // to end up with a partial-redef of a livein, e.g.
1711        // BB0:
1712        // reg1051:10<def> =
1713        // ...
1714        // BB1:
1715        // ... = reg1051:10
1716        // BB2:
1717        // reg1051:9<def> =
1718        // LiveIntervalAnalysis won't like it.
1719        //
1720        // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1721        // correctly up to date becomes very difficult. Insert a copy.
1722
1723        // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1724        // might insert a COPY that uses SrcReg after is was killed.
1725        if (isKill)
1726          for (unsigned j = i + 2; j < e; j += 2)
1727            if (MI->getOperand(j).getReg() == SrcReg) {
1728              MI->getOperand(j).setIsKill();
1729              isKill = false;
1730              break;
1731            }
1732
1733        MachineBasicBlock::iterator InsertLoc = MI;
1734        MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1735                                MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1736            .addReg(DstReg, RegState::Define, SubIdx)
1737            .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
1738        MI->getOperand(i).setReg(0);
1739        if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1740          LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1741        DEBUG(dbgs() << "Inserted: " << *CopyMI);
1742      }
1743    }
1744
1745    for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1746      unsigned SrcReg = MI->getOperand(i).getReg();
1747      if (!SrcReg) continue;
1748      unsigned SubIdx = MI->getOperand(i+1).getImm();
1749      UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1750    }
1751
1752    // Set <def,undef> flags on the first DstReg def in the basic block.
1753    // It marks the beginning of the live range. All the other defs are
1754    // read-modify-write.
1755    if (MachineInstr *Def = findFirstDef(DstReg, MRI)) {
1756      for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
1757        MachineOperand &MO = Def->getOperand(i);
1758        if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1759          MO.setIsUndef();
1760      }
1761      DEBUG(dbgs() << "First def: " << *Def);
1762    }
1763
1764    if (IsImpDef) {
1765      DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1766      MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1767      for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1768        MI->RemoveOperand(j);
1769    } else {
1770      DEBUG(dbgs() << "Eliminated: " << *MI);
1771      MI->eraseFromParent();
1772    }
1773
1774    // Try coalescing some EXTRACT_SUBREG instructions. This can create
1775    // INSERT_SUBREG instructions that must have <undef> flags added by
1776    // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1777    if (LV)
1778      CoalesceExtSubRegs(RealSrcs, DstReg);
1779  }
1780
1781  RegSequences.clear();
1782  return true;
1783}
1784