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