TwoAddressInstructionPass.cpp revision f4a5a613faa1a0eca6b884a6dfe83e8b1eb957b2
1//===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the TwoAddress instruction pass which is used
11// by most register allocators. Two-Address instructions are rewritten
12// from:
13//
14//     A = B op C
15//
16// to:
17//
18//     A = B
19//     A op= C
20//
21// Note that if a register allocator chooses to use this pass, that it
22// has to be capable of handling the non-SSA nature of these rewritten
23// virtual registers.
24//
25// It is also worth noting that the duplicate operand of the two
26// address instruction is removed.
27//
28//===----------------------------------------------------------------------===//
29
30#define DEBUG_TYPE "twoaddrinstr"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/Function.h"
33#include "llvm/CodeGen/LiveIntervalAnalysis.h"
34#include "llvm/CodeGen/LiveVariables.h"
35#include "llvm/CodeGen/MachineFunctionPass.h"
36#include "llvm/CodeGen/MachineInstr.h"
37#include "llvm/CodeGen/MachineInstrBuilder.h"
38#include "llvm/CodeGen/MachineRegisterInfo.h"
39#include "llvm/Analysis/AliasAnalysis.h"
40#include "llvm/MC/MCInstrItineraries.h"
41#include "llvm/Target/TargetRegisterInfo.h"
42#include "llvm/Target/TargetInstrInfo.h"
43#include "llvm/Target/TargetMachine.h"
44#include "llvm/Target/TargetOptions.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/ADT/BitVector.h"
48#include "llvm/ADT/DenseMap.h"
49#include "llvm/ADT/SmallSet.h"
50#include "llvm/ADT/Statistic.h"
51#include "llvm/ADT/STLExtras.h"
52using namespace llvm;
53
54STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
55STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
56STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
57STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
58STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
59STATISTIC(NumReSchedUps,       "Number of instructions re-scheduled up");
60STATISTIC(NumReSchedDowns,     "Number of instructions re-scheduled down");
61
62namespace {
63  class TwoAddressInstructionPass : public MachineFunctionPass {
64    MachineFunction *MF;
65    const TargetInstrInfo *TII;
66    const TargetRegisterInfo *TRI;
67    const InstrItineraryData *InstrItins;
68    MachineRegisterInfo *MRI;
69    LiveVariables *LV;
70    SlotIndexes *Indexes;
71    LiveIntervals *LIS;
72    AliasAnalysis *AA;
73    CodeGenOpt::Level OptLevel;
74
75    // DistanceMap - Keep track the distance of a MI from the start of the
76    // current basic block.
77    DenseMap<MachineInstr*, unsigned> DistanceMap;
78
79    // SrcRegMap - A map from virtual registers to physical registers which
80    // are likely targets to be coalesced to due to copies from physical
81    // registers to virtual registers. e.g. v1024 = move r0.
82    DenseMap<unsigned, unsigned> SrcRegMap;
83
84    // DstRegMap - A map from virtual registers to physical registers which
85    // are likely targets to be coalesced to due to copies to physical
86    // registers from virtual registers. e.g. r1 = move v1024.
87    DenseMap<unsigned, unsigned> DstRegMap;
88
89    /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
90    /// during the initial walk of the machine function.
91    SmallVector<MachineInstr*, 16> RegSequences;
92
93    bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
94                              unsigned Reg,
95                              MachineBasicBlock::iterator OldPos);
96
97    bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
98                           unsigned &LastDef);
99
100    bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
101                               MachineInstr *MI, MachineBasicBlock *MBB,
102                               unsigned Dist);
103
104    bool CommuteInstruction(MachineBasicBlock::iterator &mi,
105                            MachineFunction::iterator &mbbi,
106                            unsigned RegB, unsigned RegC, unsigned Dist);
107
108    bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
109
110    bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
111                            MachineBasicBlock::iterator &nmi,
112                            MachineFunction::iterator &mbbi,
113                            unsigned RegA, unsigned RegB, unsigned Dist);
114
115    bool isDefTooClose(unsigned Reg, unsigned Dist,
116                       MachineInstr *MI, MachineBasicBlock *MBB);
117
118    bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
119                               MachineBasicBlock::iterator &mi,
120                               MachineBasicBlock::iterator &nmi,
121                               unsigned Reg);
122    bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
123                               MachineBasicBlock::iterator &mi,
124                               MachineBasicBlock::iterator &nmi,
125                               unsigned Reg);
126
127    bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
128                                 MachineBasicBlock::iterator &nmi,
129                                 MachineFunction::iterator &mbbi,
130                                 unsigned SrcIdx, unsigned DstIdx,
131                                 unsigned Dist,
132                                 SmallPtrSet<MachineInstr*, 8> &Processed);
133
134    void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
135                  SmallPtrSet<MachineInstr*, 8> &Processed);
136
137    void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
138                     SmallPtrSet<MachineInstr*, 8> &Processed);
139
140    typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
141    typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
142    bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
143    void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
144
145    /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
146    /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
147    /// sub-register references of the register defined by REG_SEQUENCE.
148    bool EliminateRegSequences();
149
150  public:
151    static char ID; // Pass identification, replacement for typeid
152    TwoAddressInstructionPass() : MachineFunctionPass(ID) {
153      initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
154    }
155
156    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
157      AU.setPreservesCFG();
158      AU.addRequired<AliasAnalysis>();
159      AU.addPreserved<LiveVariables>();
160      AU.addPreserved<SlotIndexes>();
161      AU.addPreserved<LiveIntervals>();
162      AU.addPreservedID(MachineLoopInfoID);
163      AU.addPreservedID(MachineDominatorsID);
164      MachineFunctionPass::getAnalysisUsage(AU);
165    }
166
167    /// runOnMachineFunction - Pass entry point.
168    bool runOnMachineFunction(MachineFunction&);
169  };
170}
171
172char TwoAddressInstructionPass::ID = 0;
173INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
174                "Two-Address instruction pass", false, false)
175INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
176INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
177                "Two-Address instruction pass", false, false)
178
179char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
180
181/// Sink3AddrInstruction - A two-address instruction has been converted to a
182/// three-address instruction to avoid clobbering a register. Try to sink it
183/// past the instruction that would kill the above mentioned register to reduce
184/// register pressure.
185bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
186                                           MachineInstr *MI, unsigned SavedReg,
187                                           MachineBasicBlock::iterator OldPos) {
188  // FIXME: Shouldn't we be trying to do this before we three-addressify the
189  // instruction?  After this transformation is done, we no longer need
190  // the instruction to be in three-address form.
191
192  // Check if it's safe to move this instruction.
193  bool SeenStore = true; // Be conservative.
194  if (!MI->isSafeToMove(TII, AA, SeenStore))
195    return false;
196
197  unsigned DefReg = 0;
198  SmallSet<unsigned, 4> UseRegs;
199
200  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
201    const MachineOperand &MO = MI->getOperand(i);
202    if (!MO.isReg())
203      continue;
204    unsigned MOReg = MO.getReg();
205    if (!MOReg)
206      continue;
207    if (MO.isUse() && MOReg != SavedReg)
208      UseRegs.insert(MO.getReg());
209    if (!MO.isDef())
210      continue;
211    if (MO.isImplicit())
212      // Don't try to move it if it implicitly defines a register.
213      return false;
214    if (DefReg)
215      // For now, don't move any instructions that define multiple registers.
216      return false;
217    DefReg = MO.getReg();
218  }
219
220  // Find the instruction that kills SavedReg.
221  MachineInstr *KillMI = NULL;
222  for (MachineRegisterInfo::use_nodbg_iterator
223         UI = MRI->use_nodbg_begin(SavedReg),
224         UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
225    MachineOperand &UseMO = UI.getOperand();
226    if (!UseMO.isKill())
227      continue;
228    KillMI = UseMO.getParent();
229    break;
230  }
231
232  // If we find the instruction that kills SavedReg, and it is in an
233  // appropriate location, we can try to sink the current instruction
234  // past it.
235  if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
236      KillMI == OldPos || KillMI->isTerminator())
237    return false;
238
239  // If any of the definitions are used by another instruction between the
240  // position and the kill use, then it's not safe to sink it.
241  //
242  // FIXME: This can be sped up if there is an easy way to query whether an
243  // instruction is before or after another instruction. Then we can use
244  // MachineRegisterInfo def / use instead.
245  MachineOperand *KillMO = NULL;
246  MachineBasicBlock::iterator KillPos = KillMI;
247  ++KillPos;
248
249  unsigned NumVisited = 0;
250  for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
251    MachineInstr *OtherMI = I;
252    // DBG_VALUE cannot be counted against the limit.
253    if (OtherMI->isDebugValue())
254      continue;
255    if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
256      return false;
257    ++NumVisited;
258    for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
259      MachineOperand &MO = OtherMI->getOperand(i);
260      if (!MO.isReg())
261        continue;
262      unsigned MOReg = MO.getReg();
263      if (!MOReg)
264        continue;
265      if (DefReg == MOReg)
266        return false;
267
268      if (MO.isKill()) {
269        if (OtherMI == KillMI && MOReg == SavedReg)
270          // Save the operand that kills the register. We want to unset the kill
271          // marker if we can sink MI past it.
272          KillMO = &MO;
273        else if (UseRegs.count(MOReg))
274          // One of the uses is killed before the destination.
275          return false;
276      }
277    }
278  }
279  assert(KillMO && "Didn't find kill");
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->getNumOperands();
1204
1205  for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1206    unsigned DstIdx = 0;
1207    if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1208      continue;
1209    AnyOps = true;
1210    MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1211    MachineOperand &DstMO = MI->getOperand(DstIdx);
1212    unsigned SrcReg = SrcMO.getReg();
1213    unsigned DstReg = DstMO.getReg();
1214    // Tied constraint already satisfied?
1215    if (SrcReg == DstReg)
1216      continue;
1217
1218    assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1219
1220    // Deal with <undef> uses immediately - simply rewrite the src operand.
1221    if (SrcMO.isUndef()) {
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      SrcMO.setReg(DstReg);
1228      DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1229      continue;
1230    }
1231    TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1232  }
1233  return AnyOps;
1234}
1235
1236// Process a list of tied MI operands that all use the same source register.
1237// The tied pairs are of the form (SrcIdx, DstIdx).
1238void
1239TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1240                                            TiedPairList &TiedPairs,
1241                                            unsigned &Dist) {
1242  bool IsEarlyClobber = false;
1243  bool RemovedKillFlag = false;
1244  bool AllUsesCopied = true;
1245  unsigned LastCopiedReg = 0;
1246  unsigned RegB = 0;
1247  for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1248    unsigned SrcIdx = TiedPairs[tpi].first;
1249    unsigned DstIdx = TiedPairs[tpi].second;
1250
1251    const MachineOperand &DstMO = MI->getOperand(DstIdx);
1252    unsigned RegA = DstMO.getReg();
1253    IsEarlyClobber |= DstMO.isEarlyClobber();
1254
1255    // Grab RegB from the instruction because it may have changed if the
1256    // instruction was commuted.
1257    RegB = MI->getOperand(SrcIdx).getReg();
1258
1259    if (RegA == RegB) {
1260      // The register is tied to multiple destinations (or else we would
1261      // not have continued this far), but this use of the register
1262      // already matches the tied destination.  Leave it.
1263      AllUsesCopied = false;
1264      continue;
1265    }
1266    LastCopiedReg = RegA;
1267
1268    assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1269           "cannot make instruction into two-address form");
1270
1271#ifndef NDEBUG
1272    // First, verify that we don't have a use of "a" in the instruction
1273    // (a = b + a for example) because our transformation will not
1274    // work. This should never occur because we are in SSA form.
1275    for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1276      assert(i == DstIdx ||
1277             !MI->getOperand(i).isReg() ||
1278             MI->getOperand(i).getReg() != RegA);
1279#endif
1280
1281    // Emit a copy.
1282    BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1283            TII->get(TargetOpcode::COPY), RegA).addReg(RegB);
1284
1285    // Update DistanceMap.
1286    MachineBasicBlock::iterator PrevMI = MI;
1287    --PrevMI;
1288    DistanceMap.insert(std::make_pair(PrevMI, Dist));
1289    DistanceMap[MI] = ++Dist;
1290
1291    SlotIndex CopyIdx;
1292    if (Indexes)
1293      CopyIdx = Indexes->insertMachineInstrInMaps(PrevMI).getRegSlot();
1294
1295    DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI);
1296
1297    MachineOperand &MO = MI->getOperand(SrcIdx);
1298    assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1299           "inconsistent operand info for 2-reg pass");
1300    if (MO.isKill()) {
1301      MO.setIsKill(false);
1302      RemovedKillFlag = true;
1303    }
1304
1305    // Make sure regA is a legal regclass for the SrcIdx operand.
1306    if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1307        TargetRegisterInfo::isVirtualRegister(RegB))
1308      MRI->constrainRegClass(RegA, MRI->getRegClass(RegB));
1309
1310    MO.setReg(RegA);
1311
1312    // Propagate SrcRegMap.
1313    SrcRegMap[RegA] = RegB;
1314  }
1315
1316
1317  if (AllUsesCopied) {
1318    if (!IsEarlyClobber) {
1319      // Replace other (un-tied) uses of regB with LastCopiedReg.
1320      for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1321        MachineOperand &MO = MI->getOperand(i);
1322        if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1323          if (MO.isKill()) {
1324            MO.setIsKill(false);
1325            RemovedKillFlag = true;
1326          }
1327          MO.setReg(LastCopiedReg);
1328        }
1329      }
1330    }
1331
1332    // Update live variables for regB.
1333    if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1334      MachineBasicBlock::iterator PrevMI = MI;
1335      --PrevMI;
1336      LV->addVirtualRegisterKilled(RegB, PrevMI);
1337    }
1338
1339  } else if (RemovedKillFlag) {
1340    // Some tied uses of regB matched their destination registers, so
1341    // regB is still used in this instruction, but a kill flag was
1342    // removed from a different tied use of regB, so now we need to add
1343    // a kill flag to one of the remaining uses of regB.
1344    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1345      MachineOperand &MO = MI->getOperand(i);
1346      if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1347        MO.setIsKill(true);
1348        break;
1349      }
1350    }
1351  }
1352}
1353
1354/// runOnMachineFunction - Reduce two-address instructions to two operands.
1355///
1356bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1357  MF = &Func;
1358  const TargetMachine &TM = MF->getTarget();
1359  MRI = &MF->getRegInfo();
1360  TII = TM.getInstrInfo();
1361  TRI = TM.getRegisterInfo();
1362  InstrItins = TM.getInstrItineraryData();
1363  Indexes = getAnalysisIfAvailable<SlotIndexes>();
1364  LV = getAnalysisIfAvailable<LiveVariables>();
1365  LIS = getAnalysisIfAvailable<LiveIntervals>();
1366  AA = &getAnalysis<AliasAnalysis>();
1367  OptLevel = TM.getOptLevel();
1368
1369  bool MadeChange = false;
1370
1371  DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1372  DEBUG(dbgs() << "********** Function: "
1373        << MF->getName() << '\n');
1374
1375  // This pass takes the function out of SSA form.
1376  MRI->leaveSSA();
1377
1378  TiedOperandMap TiedOperands;
1379
1380  SmallPtrSet<MachineInstr*, 8> Processed;
1381  for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1382       mbbi != mbbe; ++mbbi) {
1383    unsigned Dist = 0;
1384    DistanceMap.clear();
1385    SrcRegMap.clear();
1386    DstRegMap.clear();
1387    Processed.clear();
1388    for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1389         mi != me; ) {
1390      MachineBasicBlock::iterator nmi = llvm::next(mi);
1391      if (mi->isDebugValue()) {
1392        mi = nmi;
1393        continue;
1394      }
1395
1396      // Remember REG_SEQUENCE instructions, we'll deal with them later.
1397      if (mi->isRegSequence())
1398        RegSequences.push_back(&*mi);
1399
1400      DistanceMap.insert(std::make_pair(mi, ++Dist));
1401
1402      ProcessCopy(&*mi, &*mbbi, Processed);
1403
1404      // First scan through all the tied register uses in this instruction
1405      // and record a list of pairs of tied operands for each register.
1406      if (!collectTiedOperands(mi, TiedOperands)) {
1407        mi = nmi;
1408        continue;
1409      }
1410
1411      ++NumTwoAddressInstrs;
1412      MadeChange = true;
1413      DEBUG(dbgs() << '\t' << *mi);
1414
1415      // If the instruction has a single pair of tied operands, try some
1416      // transformations that may either eliminate the tied operands or
1417      // improve the opportunities for coalescing away the register copy.
1418      if (TiedOperands.size() == 1) {
1419        SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1420          = TiedOperands.begin()->second;
1421        if (TiedPairs.size() == 1) {
1422          unsigned SrcIdx = TiedPairs[0].first;
1423          unsigned DstIdx = TiedPairs[0].second;
1424          unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1425          unsigned DstReg = mi->getOperand(DstIdx).getReg();
1426          if (SrcReg != DstReg &&
1427              TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1428                                      Processed)) {
1429            // The tied operands have been eliminated or shifted further down the
1430            // block to ease elimination. Continue processing with 'nmi'.
1431            TiedOperands.clear();
1432            mi = nmi;
1433            continue;
1434          }
1435        }
1436      }
1437
1438      // Now iterate over the information collected above.
1439      for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1440             OE = TiedOperands.end(); OI != OE; ++OI) {
1441        processTiedPairs(mi, OI->second, Dist);
1442        DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1443      }
1444
1445      // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1446      if (mi->isInsertSubreg()) {
1447        // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1448        // To   %reg:subidx = COPY %subreg
1449        unsigned SubIdx = mi->getOperand(3).getImm();
1450        mi->RemoveOperand(3);
1451        assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1452        mi->getOperand(0).setSubReg(SubIdx);
1453        mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1454        mi->RemoveOperand(1);
1455        mi->setDesc(TII->get(TargetOpcode::COPY));
1456        DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1457      }
1458
1459      // Clear TiedOperands here instead of at the top of the loop
1460      // since most instructions do not have tied operands.
1461      TiedOperands.clear();
1462      mi = nmi;
1463    }
1464  }
1465
1466  // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1467  // SSA form. It's now safe to de-SSA.
1468  MadeChange |= EliminateRegSequences();
1469
1470  return MadeChange;
1471}
1472
1473static void UpdateRegSequenceSrcs(unsigned SrcReg,
1474                                  unsigned DstReg, unsigned SubIdx,
1475                                  MachineRegisterInfo *MRI,
1476                                  const TargetRegisterInfo &TRI) {
1477  for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1478         RE = MRI->reg_end(); RI != RE; ) {
1479    MachineOperand &MO = RI.getOperand();
1480    ++RI;
1481    MO.substVirtReg(DstReg, SubIdx, TRI);
1482  }
1483}
1484
1485// Find the first def of Reg, assuming they are all in the same basic block.
1486static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
1487  SmallPtrSet<MachineInstr*, 8> Defs;
1488  MachineInstr *First = 0;
1489  for (MachineRegisterInfo::def_iterator RI = MRI->def_begin(Reg);
1490       MachineInstr *MI = RI.skipInstruction(); Defs.insert(MI))
1491    First = MI;
1492  if (!First)
1493    return 0;
1494
1495  MachineBasicBlock *MBB = First->getParent();
1496  MachineBasicBlock::iterator A = First, B = First;
1497  bool Moving;
1498  do {
1499    Moving = false;
1500    if (A != MBB->begin()) {
1501      Moving = true;
1502      --A;
1503      if (Defs.erase(A)) First = A;
1504    }
1505    if (B != MBB->end()) {
1506      Defs.erase(B);
1507      ++B;
1508      Moving = true;
1509    }
1510  } while (Moving && !Defs.empty());
1511  assert(Defs.empty() && "Instructions outside basic block!");
1512  return First;
1513}
1514
1515static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1516                                    MachineRegisterInfo *MRI) {
1517  for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1518         UE = MRI->use_end(); UI != UE; ++UI) {
1519    MachineInstr *UseMI = &*UI;
1520    if (UseMI != RegSeq && UseMI->isRegSequence())
1521      return true;
1522  }
1523  return false;
1524}
1525
1526/// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1527/// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1528/// sub-register references of the register defined by REG_SEQUENCE. e.g.
1529///
1530/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1531/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1532/// =>
1533/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1534bool TwoAddressInstructionPass::EliminateRegSequences() {
1535  if (RegSequences.empty())
1536    return false;
1537
1538  for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1539    MachineInstr *MI = RegSequences[i];
1540    unsigned DstReg = MI->getOperand(0).getReg();
1541    if (MI->getOperand(0).getSubReg() ||
1542        TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1543        !(MI->getNumOperands() & 1)) {
1544      DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1545      llvm_unreachable(0);
1546    }
1547
1548    bool IsImpDef = true;
1549    SmallVector<unsigned, 4> RealSrcs;
1550    SmallSet<unsigned, 4> Seen;
1551    for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1552      // Nothing needs to be inserted for <undef> operands.
1553      if (MI->getOperand(i).isUndef()) {
1554        MI->getOperand(i).setReg(0);
1555        continue;
1556      }
1557      unsigned SrcReg = MI->getOperand(i).getReg();
1558      unsigned SrcSubIdx = MI->getOperand(i).getSubReg();
1559      unsigned SubIdx = MI->getOperand(i+1).getImm();
1560      // DefMI of NULL means the value does not have a vreg in this block
1561      // i.e., its a physical register or a subreg.
1562      // In either case we force a copy to be generated.
1563      MachineInstr *DefMI = NULL;
1564      if (!MI->getOperand(i).getSubReg() &&
1565          !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1566        DefMI = MRI->getUniqueVRegDef(SrcReg);
1567      }
1568
1569      if (DefMI && DefMI->isImplicitDef()) {
1570        DefMI->eraseFromParent();
1571        continue;
1572      }
1573      IsImpDef = false;
1574
1575      // Remember COPY sources. These might be candidate for coalescing.
1576      if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1577        RealSrcs.push_back(DefMI->getOperand(1).getReg());
1578
1579      bool isKill = MI->getOperand(i).isKill();
1580      if (!DefMI || !Seen.insert(SrcReg) ||
1581          MI->getParent() != DefMI->getParent() ||
1582          !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1583          !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1584                                         MRI->getRegClass(SrcReg), SubIdx)) {
1585        // REG_SEQUENCE cannot have duplicated operands, add a copy.
1586        // Also add an copy if the source is live-in the block. We don't want
1587        // to end up with a partial-redef of a livein, e.g.
1588        // BB0:
1589        // reg1051:10<def> =
1590        // ...
1591        // BB1:
1592        // ... = reg1051:10
1593        // BB2:
1594        // reg1051:9<def> =
1595        // LiveIntervalAnalysis won't like it.
1596        //
1597        // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1598        // correctly up to date becomes very difficult. Insert a copy.
1599
1600        // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1601        // might insert a COPY that uses SrcReg after is was killed.
1602        if (isKill)
1603          for (unsigned j = i + 2; j < e; j += 2)
1604            if (MI->getOperand(j).getReg() == SrcReg) {
1605              MI->getOperand(j).setIsKill();
1606              isKill = false;
1607              break;
1608            }
1609
1610        MachineBasicBlock::iterator InsertLoc = MI;
1611        MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1612                                MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1613            .addReg(DstReg, RegState::Define, SubIdx)
1614            .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
1615        MI->getOperand(i).setReg(0);
1616        if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1617          LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1618        DEBUG(dbgs() << "Inserted: " << *CopyMI);
1619      }
1620    }
1621
1622    for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1623      unsigned SrcReg = MI->getOperand(i).getReg();
1624      if (!SrcReg) continue;
1625      unsigned SubIdx = MI->getOperand(i+1).getImm();
1626      UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1627    }
1628
1629    // Set <def,undef> flags on the first DstReg def in the basic block.
1630    // It marks the beginning of the live range. All the other defs are
1631    // read-modify-write.
1632    if (MachineInstr *Def = findFirstDef(DstReg, MRI)) {
1633      for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
1634        MachineOperand &MO = Def->getOperand(i);
1635        if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1636          MO.setIsUndef();
1637      }
1638      DEBUG(dbgs() << "First def: " << *Def);
1639    }
1640
1641    if (IsImpDef) {
1642      DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1643      MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1644      for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1645        MI->RemoveOperand(j);
1646    } else {
1647      DEBUG(dbgs() << "Eliminated: " << *MI);
1648      MI->eraseFromParent();
1649    }
1650  }
1651
1652  RegSequences.clear();
1653  return true;
1654}
1655