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