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