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