Begin adding static dependence information to passes, which will allow us to
[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/Function.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/ADT/BitVector.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/SmallSet.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/STLExtras.h"
50 using namespace llvm;
51
52 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
53 STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
54 STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
55 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
56 STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
57 STATISTIC(NumReMats,           "Number of instructions re-materialized");
58 STATISTIC(NumDeletes,          "Number of dead instructions deleted");
59
60 namespace {
61   class TwoAddressInstructionPass : public MachineFunctionPass {
62     const TargetInstrInfo *TII;
63     const TargetRegisterInfo *TRI;
64     MachineRegisterInfo *MRI;
65     LiveVariables *LV;
66     AliasAnalysis *AA;
67
68     // DistanceMap - Keep track the distance of a MI from the start of the
69     // current basic block.
70     DenseMap<MachineInstr*, unsigned> DistanceMap;
71
72     // SrcRegMap - A map from virtual registers to physical registers which
73     // are likely targets to be coalesced to due to copies from physical
74     // registers to virtual registers. e.g. v1024 = move r0.
75     DenseMap<unsigned, unsigned> SrcRegMap;
76
77     // DstRegMap - A map from virtual registers to physical registers which
78     // are likely targets to be coalesced to due to copies to physical
79     // registers from virtual registers. e.g. r1 = move v1024.
80     DenseMap<unsigned, unsigned> DstRegMap;
81
82     /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
83     /// during the initial walk of the machine function.
84     SmallVector<MachineInstr*, 16> RegSequences;
85
86     bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
87                               unsigned Reg,
88                               MachineBasicBlock::iterator OldPos);
89
90     bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
91                              MachineInstr *MI, MachineInstr *DefMI,
92                              MachineBasicBlock *MBB, unsigned Loc);
93
94     bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
95                            unsigned &LastDef);
96
97     MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
98                                    unsigned Dist);
99
100     bool isProfitableToCommute(unsigned regB, unsigned regC,
101                                MachineInstr *MI, MachineBasicBlock *MBB,
102                                unsigned Dist);
103
104     bool CommuteInstruction(MachineBasicBlock::iterator &mi,
105                             MachineFunction::iterator &mbbi,
106                             unsigned RegB, unsigned RegC, unsigned Dist);
107
108     bool isProfitableToConv3Addr(unsigned RegA);
109
110     bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
111                             MachineBasicBlock::iterator &nmi,
112                             MachineFunction::iterator &mbbi,
113                             unsigned RegB, unsigned Dist);
114
115     typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
116     bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
117                                SmallVector<NewKill, 4> &NewKills,
118                                MachineBasicBlock *MBB, unsigned Dist);
119     bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
120                            MachineBasicBlock::iterator &nmi,
121                            MachineFunction::iterator &mbbi, unsigned Dist);
122
123     bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
124                                  MachineBasicBlock::iterator &nmi,
125                                  MachineFunction::iterator &mbbi,
126                                  unsigned SrcIdx, unsigned DstIdx,
127                                  unsigned Dist);
128
129     void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
130                      SmallPtrSet<MachineInstr*, 8> &Processed);
131
132     void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
133
134     /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
135     /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
136     /// sub-register references of the register defined by REG_SEQUENCE.
137     bool EliminateRegSequences();
138
139   public:
140     static char ID; // Pass identification, replacement for typeid
141     TwoAddressInstructionPass() : MachineFunctionPass(ID) {}
142
143     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
144       AU.setPreservesCFG();
145       AU.addRequired<AliasAnalysis>();
146       AU.addPreserved<LiveVariables>();
147       AU.addPreservedID(MachineLoopInfoID);
148       AU.addPreservedID(MachineDominatorsID);
149       if (StrongPHIElim)
150         AU.addPreservedID(StrongPHIEliminationID);
151       else
152         AU.addPreservedID(PHIEliminationID);
153       MachineFunctionPass::getAnalysisUsage(AU);
154     }
155
156     /// runOnMachineFunction - Pass entry point.
157     bool runOnMachineFunction(MachineFunction&);
158   };
159 }
160
161 char TwoAddressInstructionPass::ID = 0;
162 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
163                 "Two-Address instruction pass", false, false)
164 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
165 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
166                 "Two-Address instruction pass", false, false)
167
168 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
169
170 /// Sink3AddrInstruction - A two-address instruction has been converted to a
171 /// three-address instruction to avoid clobbering a register. Try to sink it
172 /// past the instruction that would kill the above mentioned register to reduce
173 /// register pressure.
174 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
175                                            MachineInstr *MI, unsigned SavedReg,
176                                            MachineBasicBlock::iterator OldPos) {
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 (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
218     return false;
219
220   // If any of the definitions are used by another instruction between the
221   // position and the kill use, then it's not safe to sink it.
222   // 
223   // FIXME: This can be sped up if there is an easy way to query whether an
224   // instruction is before or after another instruction. Then we can use
225   // MachineRegisterInfo def / use instead.
226   MachineOperand *KillMO = NULL;
227   MachineBasicBlock::iterator KillPos = KillMI;
228   ++KillPos;
229
230   unsigned NumVisited = 0;
231   for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
232     MachineInstr *OtherMI = I;
233     // DBG_VALUE cannot be counted against the limit.
234     if (OtherMI->isDebugValue())
235       continue;
236     if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
237       return false;
238     ++NumVisited;
239     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
240       MachineOperand &MO = OtherMI->getOperand(i);
241       if (!MO.isReg())
242         continue;
243       unsigned MOReg = MO.getReg();
244       if (!MOReg)
245         continue;
246       if (DefReg == MOReg)
247         return false;
248
249       if (MO.isKill()) {
250         if (OtherMI == KillMI && MOReg == SavedReg)
251           // Save the operand that kills the register. We want to unset the kill
252           // marker if we can sink MI past it.
253           KillMO = &MO;
254         else if (UseRegs.count(MOReg))
255           // One of the uses is killed before the destination.
256           return false;
257       }
258     }
259   }
260
261   // Update kill and LV information.
262   KillMO->setIsKill(false);
263   KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
264   KillMO->setIsKill(true);
265   
266   if (LV)
267     LV->replaceKillInstruction(SavedReg, KillMI, MI);
268
269   // Move instruction to its destination.
270   MBB->remove(MI);
271   MBB->insert(KillPos, MI);
272
273   ++Num3AddrSunk;
274   return true;
275 }
276
277 /// isTwoAddrUse - Return true if the specified MI is using the specified
278 /// register as a two-address operand.
279 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
280   const TargetInstrDesc &TID = UseMI->getDesc();
281   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
282     MachineOperand &MO = UseMI->getOperand(i);
283     if (MO.isReg() && MO.getReg() == Reg &&
284         (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
285       // Earlier use is a two-address one.
286       return true;
287   }
288   return false;
289 }
290
291 /// isProfitableToReMat - Return true if the heuristics determines it is likely
292 /// to be profitable to re-materialize the definition of Reg rather than copy
293 /// the register.
294 bool
295 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
296                                          const TargetRegisterClass *RC,
297                                          MachineInstr *MI, MachineInstr *DefMI,
298                                          MachineBasicBlock *MBB, unsigned Loc) {
299   bool OtherUse = false;
300   for (MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg),
301          UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
302     MachineOperand &UseMO = UI.getOperand();
303     MachineInstr *UseMI = UseMO.getParent();
304     MachineBasicBlock *UseMBB = UseMI->getParent();
305     if (UseMBB == MBB) {
306       DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
307       if (DI != DistanceMap.end() && DI->second == Loc)
308         continue;  // Current use.
309       OtherUse = true;
310       // There is at least one other use in the MBB that will clobber the
311       // register. 
312       if (isTwoAddrUse(UseMI, Reg))
313         return true;
314     }
315   }
316
317   // If other uses in MBB are not two-address uses, then don't remat.
318   if (OtherUse)
319     return false;
320
321   // No other uses in the same block, remat if it's defined in the same
322   // block so it does not unnecessarily extend the live range.
323   return MBB == DefMI->getParent();
324 }
325
326 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
327 /// last instruction in the MBB that defines the specified register and the
328 /// two-address instruction which is being processed. It also returns the last
329 /// def location by reference
330 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
331                                            MachineBasicBlock *MBB, unsigned Dist,
332                                            unsigned &LastDef) {
333   LastDef = 0;
334   unsigned LastUse = Dist;
335   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
336          E = MRI->reg_end(); I != E; ++I) {
337     MachineOperand &MO = I.getOperand();
338     MachineInstr *MI = MO.getParent();
339     if (MI->getParent() != MBB || MI->isDebugValue())
340       continue;
341     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
342     if (DI == DistanceMap.end())
343       continue;
344     if (MO.isUse() && DI->second < LastUse)
345       LastUse = DI->second;
346     if (MO.isDef() && DI->second > LastDef)
347       LastDef = DI->second;
348   }
349
350   return !(LastUse > LastDef && LastUse < Dist);
351 }
352
353 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
354                                                          MachineBasicBlock *MBB,
355                                                          unsigned Dist) {
356   unsigned LastUseDist = 0;
357   MachineInstr *LastUse = 0;
358   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
359          E = MRI->reg_end(); I != E; ++I) {
360     MachineOperand &MO = I.getOperand();
361     MachineInstr *MI = MO.getParent();
362     if (MI->getParent() != MBB || MI->isDebugValue())
363       continue;
364     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
365     if (DI == DistanceMap.end())
366       continue;
367     if (DI->second >= Dist)
368       continue;
369
370     if (MO.isUse() && DI->second > LastUseDist) {
371       LastUse = DI->first;
372       LastUseDist = DI->second;
373     }
374   }
375   return LastUse;
376 }
377
378 /// isCopyToReg - Return true if the specified MI is a copy instruction or
379 /// a extract_subreg instruction. It also returns the source and destination
380 /// registers and whether they are physical registers by reference.
381 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
382                         unsigned &SrcReg, unsigned &DstReg,
383                         bool &IsSrcPhys, bool &IsDstPhys) {
384   SrcReg = 0;
385   DstReg = 0;
386   if (MI.isCopy()) {
387     DstReg = MI.getOperand(0).getReg();
388     SrcReg = MI.getOperand(1).getReg();
389   } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
390     DstReg = MI.getOperand(0).getReg();
391     SrcReg = MI.getOperand(2).getReg();
392   } else
393     return false;
394
395   IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
396   IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
397   return true;
398 }
399
400 /// isKilled - Test if the given register value, which is used by the given
401 /// instruction, is killed by the given instruction. This looks through
402 /// coalescable copies to see if the original value is potentially not killed.
403 ///
404 /// For example, in this code:
405 ///
406 ///   %reg1034 = copy %reg1024
407 ///   %reg1035 = copy %reg1025<kill>
408 ///   %reg1036 = add %reg1034<kill>, %reg1035<kill>
409 ///
410 /// %reg1034 is not considered to be killed, since it is copied from a
411 /// register which is not killed. Treating it as not killed lets the
412 /// normal heuristics commute the (two-address) add, which lets
413 /// coalescing eliminate the extra copy.
414 ///
415 static bool isKilled(MachineInstr &MI, unsigned Reg,
416                      const MachineRegisterInfo *MRI,
417                      const TargetInstrInfo *TII) {
418   MachineInstr *DefMI = &MI;
419   for (;;) {
420     if (!DefMI->killsRegister(Reg))
421       return false;
422     if (TargetRegisterInfo::isPhysicalRegister(Reg))
423       return true;
424     MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
425     // If there are multiple defs, we can't do a simple analysis, so just
426     // go with what the kill flag says.
427     if (llvm::next(Begin) != MRI->def_end())
428       return true;
429     DefMI = &*Begin;
430     bool IsSrcPhys, IsDstPhys;
431     unsigned SrcReg,  DstReg;
432     // If the def is something other than a copy, then it isn't going to
433     // be coalesced, so follow the kill flag.
434     if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
435       return true;
436     Reg = SrcReg;
437   }
438 }
439
440 /// isTwoAddrUse - Return true if the specified MI uses the specified register
441 /// as a two-address use. If so, return the destination register by reference.
442 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
443   const TargetInstrDesc &TID = MI.getDesc();
444   unsigned NumOps = MI.isInlineAsm() ? MI.getNumOperands():TID.getNumOperands();
445   for (unsigned i = 0; i != NumOps; ++i) {
446     const MachineOperand &MO = MI.getOperand(i);
447     if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
448       continue;
449     unsigned ti;
450     if (MI.isRegTiedToDefOperand(i, &ti)) {
451       DstReg = MI.getOperand(ti).getReg();
452       return true;
453     }
454   }
455   return false;
456 }
457
458 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
459 /// use, return the use instruction if it's a copy or a two-address use.
460 static
461 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
462                                      MachineRegisterInfo *MRI,
463                                      const TargetInstrInfo *TII,
464                                      bool &IsCopy,
465                                      unsigned &DstReg, bool &IsDstPhys) {
466   if (!MRI->hasOneNonDBGUse(Reg))
467     // None or more than one use.
468     return 0;
469   MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
470   if (UseMI.getParent() != MBB)
471     return 0;
472   unsigned SrcReg;
473   bool IsSrcPhys;
474   if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
475     IsCopy = true;
476     return &UseMI;
477   }
478   IsDstPhys = false;
479   if (isTwoAddrUse(UseMI, Reg, DstReg)) {
480     IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
481     return &UseMI;
482   }
483   return 0;
484 }
485
486 /// getMappedReg - Return the physical register the specified virtual register
487 /// might be mapped to.
488 static unsigned
489 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
490   while (TargetRegisterInfo::isVirtualRegister(Reg))  {
491     DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
492     if (SI == RegMap.end())
493       return 0;
494     Reg = SI->second;
495   }
496   if (TargetRegisterInfo::isPhysicalRegister(Reg))
497     return Reg;
498   return 0;
499 }
500
501 /// regsAreCompatible - Return true if the two registers are equal or aliased.
502 ///
503 static bool
504 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
505   if (RegA == RegB)
506     return true;
507   if (!RegA || !RegB)
508     return false;
509   return TRI->regsOverlap(RegA, RegB);
510 }
511
512
513 /// isProfitableToReMat - Return true if it's potentially profitable to commute
514 /// the two-address instruction that's being processed.
515 bool
516 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
517                                        MachineInstr *MI, MachineBasicBlock *MBB,
518                                        unsigned Dist) {
519   // Determine if it's profitable to commute this two address instruction. In
520   // general, we want no uses between this instruction and the definition of
521   // the two-address register.
522   // e.g.
523   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
524   // %reg1029<def> = MOV8rr %reg1028
525   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
526   // insert => %reg1030<def> = MOV8rr %reg1028
527   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
528   // In this case, it might not be possible to coalesce the second MOV8rr
529   // instruction if the first one is coalesced. So it would be profitable to
530   // commute it:
531   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
532   // %reg1029<def> = MOV8rr %reg1028
533   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
534   // insert => %reg1030<def> = MOV8rr %reg1029
535   // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>  
536
537   if (!MI->killsRegister(regC))
538     return false;
539
540   // Ok, we have something like:
541   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
542   // let's see if it's worth commuting it.
543
544   // Look for situations like this:
545   // %reg1024<def> = MOV r1
546   // %reg1025<def> = MOV r0
547   // %reg1026<def> = ADD %reg1024, %reg1025
548   // r0            = MOV %reg1026
549   // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
550   unsigned FromRegB = getMappedReg(regB, SrcRegMap);
551   unsigned FromRegC = getMappedReg(regC, SrcRegMap);
552   unsigned ToRegB = getMappedReg(regB, DstRegMap);
553   unsigned ToRegC = getMappedReg(regC, DstRegMap);
554   if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
555       (regsAreCompatible(FromRegB, ToRegC, TRI) ||
556        regsAreCompatible(FromRegC, ToRegB, TRI)))
557     return true;
558
559   // If there is a use of regC between its last def (could be livein) and this
560   // instruction, then bail.
561   unsigned LastDefC = 0;
562   if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
563     return false;
564
565   // If there is a use of regB between its last def (could be livein) and this
566   // instruction, then go ahead and make this transformation.
567   unsigned LastDefB = 0;
568   if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
569     return true;
570
571   // Since there are no intervening uses for both registers, then commute
572   // if the def of regC is closer. Its live interval is shorter.
573   return LastDefB && LastDefC && LastDefC > LastDefB;
574 }
575
576 /// CommuteInstruction - Commute a two-address instruction and update the basic
577 /// block, distance map, and live variables if needed. Return true if it is
578 /// successful.
579 bool
580 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
581                                MachineFunction::iterator &mbbi,
582                                unsigned RegB, unsigned RegC, unsigned Dist) {
583   MachineInstr *MI = mi;
584   DEBUG(dbgs() << "2addr: COMMUTING  : " << *MI);
585   MachineInstr *NewMI = TII->commuteInstruction(MI);
586
587   if (NewMI == 0) {
588     DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
589     return false;
590   }
591
592   DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
593   // If the instruction changed to commute it, update livevar.
594   if (NewMI != MI) {
595     if (LV)
596       // Update live variables
597       LV->replaceKillInstruction(RegC, MI, NewMI);
598
599     mbbi->insert(mi, NewMI);           // Insert the new inst
600     mbbi->erase(mi);                   // Nuke the old inst.
601     mi = NewMI;
602     DistanceMap.insert(std::make_pair(NewMI, Dist));
603   }
604
605   // Update source register map.
606   unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
607   if (FromRegC) {
608     unsigned RegA = MI->getOperand(0).getReg();
609     SrcRegMap[RegA] = FromRegC;
610   }
611
612   return true;
613 }
614
615 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
616 /// given 2-address instruction to a 3-address one.
617 bool
618 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
619   // Look for situations like this:
620   // %reg1024<def> = MOV r1
621   // %reg1025<def> = MOV r0
622   // %reg1026<def> = ADD %reg1024, %reg1025
623   // r2            = MOV %reg1026
624   // Turn ADD into a 3-address instruction to avoid a copy.
625   unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
626   unsigned ToRegA = getMappedReg(RegA, DstRegMap);
627   return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
628 }
629
630 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
631 /// three address one. Return true if this transformation was successful.
632 bool
633 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
634                                               MachineBasicBlock::iterator &nmi,
635                                               MachineFunction::iterator &mbbi,
636                                               unsigned RegB, unsigned Dist) {
637   MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
638   if (NewMI) {
639     DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
640     DEBUG(dbgs() << "2addr:         TO 3-ADDR: " << *NewMI);
641     bool Sunk = false;
642
643     if (NewMI->findRegisterUseOperand(RegB, false, TRI))
644       // FIXME: Temporary workaround. If the new instruction doesn't
645       // uses RegB, convertToThreeAddress must have created more
646       // then one instruction.
647       Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
648
649     mbbi->erase(mi); // Nuke the old inst.
650
651     if (!Sunk) {
652       DistanceMap.insert(std::make_pair(NewMI, Dist));
653       mi = NewMI;
654       nmi = llvm::next(mi);
655     }
656     return true;
657   }
658
659   return false;
660 }
661
662 /// ProcessCopy - If the specified instruction is not yet processed, process it
663 /// if it's a copy. For a copy instruction, we find the physical registers the
664 /// source and destination registers might be mapped to. These are kept in
665 /// point-to maps used to determine future optimizations. e.g.
666 /// v1024 = mov r0
667 /// v1025 = mov r1
668 /// v1026 = add v1024, v1025
669 /// r1    = mov r1026
670 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
671 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
672 /// potentially joined with r1 on the output side. It's worthwhile to commute
673 /// 'add' to eliminate a copy.
674 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
675                                      MachineBasicBlock *MBB,
676                                      SmallPtrSet<MachineInstr*, 8> &Processed) {
677   if (Processed.count(MI))
678     return;
679
680   bool IsSrcPhys, IsDstPhys;
681   unsigned SrcReg, DstReg;
682   if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
683     return;
684
685   if (IsDstPhys && !IsSrcPhys)
686     DstRegMap.insert(std::make_pair(SrcReg, DstReg));
687   else if (!IsDstPhys && IsSrcPhys) {
688     bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
689     if (!isNew)
690       assert(SrcRegMap[DstReg] == SrcReg &&
691              "Can't map to two src physical registers!");
692
693     SmallVector<unsigned, 4> VirtRegPairs;
694     bool IsCopy = false;
695     unsigned NewReg = 0;
696     while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
697                                                    IsCopy, NewReg, IsDstPhys)) {
698       if (IsCopy) {
699         if (!Processed.insert(UseMI))
700           break;
701       }
702
703       DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
704       if (DI != DistanceMap.end())
705         // Earlier in the same MBB.Reached via a back edge.
706         break;
707
708       if (IsDstPhys) {
709         VirtRegPairs.push_back(NewReg);
710         break;
711       }
712       bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
713       if (!isNew)
714         assert(SrcRegMap[NewReg] == DstReg &&
715                "Can't map to two src physical registers!");
716       VirtRegPairs.push_back(NewReg);
717       DstReg = NewReg;
718     }
719
720     if (!VirtRegPairs.empty()) {
721       unsigned ToReg = VirtRegPairs.back();
722       VirtRegPairs.pop_back();
723       while (!VirtRegPairs.empty()) {
724         unsigned FromReg = VirtRegPairs.back();
725         VirtRegPairs.pop_back();
726         bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
727         if (!isNew)
728           assert(DstRegMap[FromReg] == ToReg &&
729                  "Can't map to two dst physical registers!");
730         ToReg = FromReg;
731       }
732     }
733   }
734
735   Processed.insert(MI);
736 }
737
738 /// isSafeToDelete - If the specified instruction does not produce any side
739 /// effects and all of its defs are dead, then it's safe to delete.
740 static bool isSafeToDelete(MachineInstr *MI,
741                            const TargetInstrInfo *TII,
742                            SmallVector<unsigned, 4> &Kills) {
743   const TargetInstrDesc &TID = MI->getDesc();
744   if (TID.mayStore() || TID.isCall())
745     return false;
746   if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
747     return false;
748
749   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
750     MachineOperand &MO = MI->getOperand(i);
751     if (!MO.isReg())
752       continue;
753     if (MO.isDef() && !MO.isDead())
754       return false;
755     if (MO.isUse() && MO.isKill())
756       Kills.push_back(MO.getReg());
757   }
758   return true;
759 }
760
761 /// canUpdateDeletedKills - Check if all the registers listed in Kills are
762 /// killed by instructions in MBB preceding the current instruction at
763 /// position Dist.  If so, return true and record information about the
764 /// preceding kills in NewKills.
765 bool TwoAddressInstructionPass::
766 canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
767                       SmallVector<NewKill, 4> &NewKills,
768                       MachineBasicBlock *MBB, unsigned Dist) {
769   while (!Kills.empty()) {
770     unsigned Kill = Kills.back();
771     Kills.pop_back();
772     if (TargetRegisterInfo::isPhysicalRegister(Kill))
773       return false;
774
775     MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
776     if (!LastKill)
777       return false;
778
779     bool isModRef = LastKill->definesRegister(Kill);
780     NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
781                                       LastKill));
782   }
783   return true;
784 }
785
786 /// DeleteUnusedInstr - If an instruction with a tied register operand can
787 /// be safely deleted, just delete it.
788 bool
789 TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
790                                              MachineBasicBlock::iterator &nmi,
791                                              MachineFunction::iterator &mbbi,
792                                              unsigned Dist) {
793   // Check if the instruction has no side effects and if all its defs are dead.
794   SmallVector<unsigned, 4> Kills;
795   if (!isSafeToDelete(mi, TII, Kills))
796     return false;
797
798   // If this instruction kills some virtual registers, we need to
799   // update the kill information. If it's not possible to do so,
800   // then bail out.
801   SmallVector<NewKill, 4> NewKills;
802   if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
803     return false;
804
805   if (LV) {
806     while (!NewKills.empty()) {
807       MachineInstr *NewKill = NewKills.back().second;
808       unsigned Kill = NewKills.back().first.first;
809       bool isDead = NewKills.back().first.second;
810       NewKills.pop_back();
811       if (LV->removeVirtualRegisterKilled(Kill, mi)) {
812         if (isDead)
813           LV->addVirtualRegisterDead(Kill, NewKill);
814         else
815           LV->addVirtualRegisterKilled(Kill, NewKill);
816       }
817     }
818   }
819
820   mbbi->erase(mi); // Nuke the old inst.
821   mi = nmi;
822   return true;
823 }
824
825 /// TryInstructionTransform - For the case where an instruction has a single
826 /// pair of tied register operands, attempt some transformations that may
827 /// either eliminate the tied operands or improve the opportunities for
828 /// coalescing away the register copy.  Returns true if the tied operands
829 /// are eliminated altogether.
830 bool TwoAddressInstructionPass::
831 TryInstructionTransform(MachineBasicBlock::iterator &mi,
832                         MachineBasicBlock::iterator &nmi,
833                         MachineFunction::iterator &mbbi,
834                         unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
835   const TargetInstrDesc &TID = mi->getDesc();
836   unsigned regA = mi->getOperand(DstIdx).getReg();
837   unsigned regB = mi->getOperand(SrcIdx).getReg();
838
839   assert(TargetRegisterInfo::isVirtualRegister(regB) &&
840          "cannot make instruction into two-address form");
841
842   // If regA is dead and the instruction can be deleted, just delete
843   // it so it doesn't clobber regB.
844   bool regBKilled = isKilled(*mi, regB, MRI, TII);
845   if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
846       DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
847     ++NumDeletes;
848     return true; // Done with this instruction.
849   }
850
851   // Check if it is profitable to commute the operands.
852   unsigned SrcOp1, SrcOp2;
853   unsigned regC = 0;
854   unsigned regCIdx = ~0U;
855   bool TryCommute = false;
856   bool AggressiveCommute = false;
857   if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
858       TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
859     if (SrcIdx == SrcOp1)
860       regCIdx = SrcOp2;
861     else if (SrcIdx == SrcOp2)
862       regCIdx = SrcOp1;
863
864     if (regCIdx != ~0U) {
865       regC = mi->getOperand(regCIdx).getReg();
866       if (!regBKilled && isKilled(*mi, regC, MRI, TII))
867         // If C dies but B does not, swap the B and C operands.
868         // This makes the live ranges of A and C joinable.
869         TryCommute = true;
870       else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
871         TryCommute = true;
872         AggressiveCommute = true;
873       }
874     }
875   }
876
877   // If it's profitable to commute, try to do so.
878   if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
879     ++NumCommuted;
880     if (AggressiveCommute)
881       ++NumAggrCommuted;
882     return false;
883   }
884
885   if (TID.isConvertibleTo3Addr()) {
886     // This instruction is potentially convertible to a true
887     // three-address instruction.  Check if it is profitable.
888     if (!regBKilled || isProfitableToConv3Addr(regA)) {
889       // Try to convert it.
890       if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
891         ++NumConvertedTo3Addr;
892         return true; // Done with this instruction.
893       }
894     }
895   }
896
897   // If this is an instruction with a load folded into it, try unfolding
898   // the load, e.g. avoid this:
899   //   movq %rdx, %rcx
900   //   addq (%rax), %rcx
901   // in favor of this:
902   //   movq (%rax), %rcx
903   //   addq %rdx, %rcx
904   // because it's preferable to schedule a load than a register copy.
905   if (TID.mayLoad() && !regBKilled) {
906     // Determine if a load can be unfolded.
907     unsigned LoadRegIndex;
908     unsigned NewOpc =
909       TII->getOpcodeAfterMemoryUnfold(mi->getOpcode(),
910                                       /*UnfoldLoad=*/true,
911                                       /*UnfoldStore=*/false,
912                                       &LoadRegIndex);
913     if (NewOpc != 0) {
914       const TargetInstrDesc &UnfoldTID = TII->get(NewOpc);
915       if (UnfoldTID.getNumDefs() == 1) {
916         MachineFunction &MF = *mbbi->getParent();
917
918         // Unfold the load.
919         DEBUG(dbgs() << "2addr:   UNFOLDING: " << *mi);
920         const TargetRegisterClass *RC =
921           UnfoldTID.OpInfo[LoadRegIndex].getRegClass(TRI);
922         unsigned Reg = MRI->createVirtualRegister(RC);
923         SmallVector<MachineInstr *, 2> NewMIs;
924         if (!TII->unfoldMemoryOperand(MF, mi, Reg,
925                                       /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
926                                       NewMIs)) {
927           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
928           return false;
929         }
930         assert(NewMIs.size() == 2 &&
931                "Unfolded a load into multiple instructions!");
932         // The load was previously folded, so this is the only use.
933         NewMIs[1]->addRegisterKilled(Reg, TRI);
934
935         // Tentatively insert the instructions into the block so that they
936         // look "normal" to the transformation logic.
937         mbbi->insert(mi, NewMIs[0]);
938         mbbi->insert(mi, NewMIs[1]);
939
940         DEBUG(dbgs() << "2addr:    NEW LOAD: " << *NewMIs[0]
941                      << "2addr:    NEW INST: " << *NewMIs[1]);
942
943         // Transform the instruction, now that it no longer has a load.
944         unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
945         unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
946         MachineBasicBlock::iterator NewMI = NewMIs[1];
947         bool TransformSuccess =
948           TryInstructionTransform(NewMI, mi, mbbi,
949                                   NewSrcIdx, NewDstIdx, Dist);
950         if (TransformSuccess ||
951             NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
952           // Success, or at least we made an improvement. Keep the unfolded
953           // instructions and discard the original.
954           if (LV) {
955             for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
956               MachineOperand &MO = mi->getOperand(i);
957               if (MO.isReg() && MO.getReg() != 0 &&
958                   TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
959                 if (MO.isUse()) {
960                   if (MO.isKill()) {
961                     if (NewMIs[0]->killsRegister(MO.getReg()))
962                       LV->replaceKillInstruction(MO.getReg(), mi, NewMIs[0]);
963                     else {
964                       assert(NewMIs[1]->killsRegister(MO.getReg()) &&
965                              "Kill missing after load unfold!");
966                       LV->replaceKillInstruction(MO.getReg(), mi, NewMIs[1]);
967                     }
968                   }
969                 } else if (LV->removeVirtualRegisterDead(MO.getReg(), mi)) {
970                   if (NewMIs[1]->registerDefIsDead(MO.getReg()))
971                     LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
972                   else {
973                     assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
974                            "Dead flag missing after load unfold!");
975                     LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
976                   }
977                 }
978               }
979             }
980             LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
981           }
982           mi->eraseFromParent();
983           mi = NewMIs[1];
984           if (TransformSuccess)
985             return true;
986         } else {
987           // Transforming didn't eliminate the tie and didn't lead to an
988           // improvement. Clean up the unfolded instructions and keep the
989           // original.
990           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
991           NewMIs[0]->eraseFromParent();
992           NewMIs[1]->eraseFromParent();
993         }
994       }
995     }
996   }
997
998   return false;
999 }
1000
1001 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1002 ///
1003 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
1004   DEBUG(dbgs() << "Machine Function\n");
1005   const TargetMachine &TM = MF.getTarget();
1006   MRI = &MF.getRegInfo();
1007   TII = TM.getInstrInfo();
1008   TRI = TM.getRegisterInfo();
1009   LV = getAnalysisIfAvailable<LiveVariables>();
1010   AA = &getAnalysis<AliasAnalysis>();
1011
1012   bool MadeChange = false;
1013
1014   DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1015   DEBUG(dbgs() << "********** Function: " 
1016         << MF.getFunction()->getName() << '\n');
1017
1018   // ReMatRegs - Keep track of the registers whose def's are remat'ed.
1019   BitVector ReMatRegs;
1020   ReMatRegs.resize(MRI->getLastVirtReg()+1);
1021
1022   typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1023     TiedOperandMap;
1024   TiedOperandMap TiedOperands(4);
1025
1026   SmallPtrSet<MachineInstr*, 8> Processed;
1027   for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1028        mbbi != mbbe; ++mbbi) {
1029     unsigned Dist = 0;
1030     DistanceMap.clear();
1031     SrcRegMap.clear();
1032     DstRegMap.clear();
1033     Processed.clear();
1034     for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1035          mi != me; ) {
1036       MachineBasicBlock::iterator nmi = llvm::next(mi);
1037       if (mi->isDebugValue()) {
1038         mi = nmi;
1039         continue;
1040       }
1041
1042       // Remember REG_SEQUENCE instructions, we'll deal with them later.
1043       if (mi->isRegSequence())
1044         RegSequences.push_back(&*mi);
1045
1046       const TargetInstrDesc &TID = mi->getDesc();
1047       bool FirstTied = true;
1048
1049       DistanceMap.insert(std::make_pair(mi, ++Dist));
1050
1051       ProcessCopy(&*mi, &*mbbi, Processed);
1052
1053       // First scan through all the tied register uses in this instruction
1054       // and record a list of pairs of tied operands for each register.
1055       unsigned NumOps = mi->isInlineAsm()
1056         ? mi->getNumOperands() : TID.getNumOperands();
1057       for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1058         unsigned DstIdx = 0;
1059         if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1060           continue;
1061
1062         if (FirstTied) {
1063           FirstTied = false;
1064           ++NumTwoAddressInstrs;
1065           DEBUG(dbgs() << '\t' << *mi);
1066         }
1067
1068         assert(mi->getOperand(SrcIdx).isReg() &&
1069                mi->getOperand(SrcIdx).getReg() &&
1070                mi->getOperand(SrcIdx).isUse() &&
1071                "two address instruction invalid");
1072
1073         unsigned regB = mi->getOperand(SrcIdx).getReg();
1074         TiedOperandMap::iterator OI = TiedOperands.find(regB);
1075         if (OI == TiedOperands.end()) {
1076           SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
1077           OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
1078         }
1079         OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
1080       }
1081
1082       // Now iterate over the information collected above.
1083       for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1084              OE = TiedOperands.end(); OI != OE; ++OI) {
1085         SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
1086
1087         // If the instruction has a single pair of tied operands, try some
1088         // transformations that may either eliminate the tied operands or
1089         // improve the opportunities for coalescing away the register copy.
1090         if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
1091           unsigned SrcIdx = TiedPairs[0].first;
1092           unsigned DstIdx = TiedPairs[0].second;
1093
1094           // If the registers are already equal, nothing needs to be done.
1095           if (mi->getOperand(SrcIdx).getReg() ==
1096               mi->getOperand(DstIdx).getReg())
1097             break; // Done with this instruction.
1098
1099           if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
1100             break; // The tied operands have been eliminated.
1101         }
1102
1103         bool RemovedKillFlag = false;
1104         bool AllUsesCopied = true;
1105         unsigned LastCopiedReg = 0;
1106         unsigned regB = OI->first;
1107         for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1108           unsigned SrcIdx = TiedPairs[tpi].first;
1109           unsigned DstIdx = TiedPairs[tpi].second;
1110           unsigned regA = mi->getOperand(DstIdx).getReg();
1111           // Grab regB from the instruction because it may have changed if the
1112           // instruction was commuted.
1113           regB = mi->getOperand(SrcIdx).getReg();
1114
1115           if (regA == regB) {
1116             // The register is tied to multiple destinations (or else we would
1117             // not have continued this far), but this use of the register
1118             // already matches the tied destination.  Leave it.
1119             AllUsesCopied = false;
1120             continue;
1121           }
1122           LastCopiedReg = regA;
1123
1124           assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1125                  "cannot make instruction into two-address form");
1126
1127 #ifndef NDEBUG
1128           // First, verify that we don't have a use of "a" in the instruction
1129           // (a = b + a for example) because our transformation will not
1130           // work. This should never occur because we are in SSA form.
1131           for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1132             assert(i == DstIdx ||
1133                    !mi->getOperand(i).isReg() ||
1134                    mi->getOperand(i).getReg() != regA);
1135 #endif
1136
1137           // Emit a copy or rematerialize the definition.
1138           const TargetRegisterClass *rc = MRI->getRegClass(regB);
1139           MachineInstr *DefMI = MRI->getVRegDef(regB);
1140           // If it's safe and profitable, remat the definition instead of
1141           // copying it.
1142           if (DefMI &&
1143               DefMI->getDesc().isAsCheapAsAMove() &&
1144               DefMI->isSafeToReMat(TII, AA, regB) &&
1145               isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
1146             DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
1147             unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
1148             TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, *TRI);
1149             ReMatRegs.set(regB);
1150             ++NumReMats;
1151           } else {
1152             BuildMI(*mbbi, mi, mi->getDebugLoc(), TII->get(TargetOpcode::COPY),
1153                     regA).addReg(regB);
1154           }
1155
1156           MachineBasicBlock::iterator prevMI = prior(mi);
1157           // Update DistanceMap.
1158           DistanceMap.insert(std::make_pair(prevMI, Dist));
1159           DistanceMap[mi] = ++Dist;
1160
1161           DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
1162
1163           MachineOperand &MO = mi->getOperand(SrcIdx);
1164           assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1165                  "inconsistent operand info for 2-reg pass");
1166           if (MO.isKill()) {
1167             MO.setIsKill(false);
1168             RemovedKillFlag = true;
1169           }
1170           MO.setReg(regA);
1171         }
1172
1173         if (AllUsesCopied) {
1174           // Replace other (un-tied) uses of regB with LastCopiedReg.
1175           for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1176             MachineOperand &MO = mi->getOperand(i);
1177             if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1178               if (MO.isKill()) {
1179                 MO.setIsKill(false);
1180                 RemovedKillFlag = true;
1181               }
1182               MO.setReg(LastCopiedReg);
1183             }
1184           }
1185
1186           // Update live variables for regB.
1187           if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1188             LV->addVirtualRegisterKilled(regB, prior(mi));
1189
1190         } else if (RemovedKillFlag) {
1191           // Some tied uses of regB matched their destination registers, so
1192           // regB is still used in this instruction, but a kill flag was
1193           // removed from a different tied use of regB, so now we need to add
1194           // a kill flag to one of the remaining uses of regB.
1195           for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1196             MachineOperand &MO = mi->getOperand(i);
1197             if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1198               MO.setIsKill(true);
1199               break;
1200             }
1201           }
1202         }
1203
1204         // Schedule the source copy / remat inserted to form two-address
1205         // instruction. FIXME: Does it matter the distance map may not be
1206         // accurate after it's scheduled?
1207         TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1208
1209         MadeChange = true;
1210
1211         DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1212       }
1213
1214       // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1215       if (mi->isInsertSubreg()) {
1216         // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1217         // To   %reg:subidx = COPY %subreg
1218         unsigned SubIdx = mi->getOperand(3).getImm();
1219         mi->RemoveOperand(3);
1220         assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1221         mi->getOperand(0).setSubReg(SubIdx);
1222         mi->RemoveOperand(1);
1223         mi->setDesc(TII->get(TargetOpcode::COPY));
1224         DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1225       }
1226
1227       // Clear TiedOperands here instead of at the top of the loop
1228       // since most instructions do not have tied operands.
1229       TiedOperands.clear();
1230       mi = nmi;
1231     }
1232   }
1233
1234   // Some remat'ed instructions are dead.
1235   int VReg = ReMatRegs.find_first();
1236   while (VReg != -1) {
1237     if (MRI->use_nodbg_empty(VReg)) {
1238       MachineInstr *DefMI = MRI->getVRegDef(VReg);
1239       DefMI->eraseFromParent();
1240     }
1241     VReg = ReMatRegs.find_next(VReg);
1242   }
1243
1244   // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1245   // SSA form. It's now safe to de-SSA.
1246   MadeChange |= EliminateRegSequences();
1247
1248   return MadeChange;
1249 }
1250
1251 static void UpdateRegSequenceSrcs(unsigned SrcReg,
1252                                   unsigned DstReg, unsigned SubIdx,
1253                                   MachineRegisterInfo *MRI,
1254                                   const TargetRegisterInfo &TRI) {
1255   for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1256          RE = MRI->reg_end(); RI != RE; ) {
1257     MachineOperand &MO = RI.getOperand();
1258     ++RI;
1259     MO.substVirtReg(DstReg, SubIdx, TRI);
1260   }
1261 }
1262
1263 /// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1264 /// EXTRACT_SUBREG from the same register and to the same virtual register
1265 /// with different sub-register indices, attempt to combine the
1266 /// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1267 /// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1268 /// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1269 /// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1270 /// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1271 /// reg1026 to reg1029.
1272 void
1273 TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1274                                               unsigned DstReg) {
1275   SmallSet<unsigned, 4> Seen;
1276   for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1277     unsigned SrcReg = Srcs[i];
1278     if (!Seen.insert(SrcReg))
1279       continue;
1280
1281     // Check that the instructions are all in the same basic block.
1282     MachineInstr *SrcDefMI = MRI->getVRegDef(SrcReg);
1283     MachineInstr *DstDefMI = MRI->getVRegDef(DstReg);
1284     if (SrcDefMI->getParent() != DstDefMI->getParent())
1285       continue;
1286
1287     // If there are no other uses than copies which feed into
1288     // the reg_sequence, then we might be able to coalesce them.
1289     bool CanCoalesce = true;
1290     SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
1291     for (MachineRegisterInfo::use_nodbg_iterator
1292            UI = MRI->use_nodbg_begin(SrcReg),
1293            UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1294       MachineInstr *UseMI = &*UI;
1295       if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
1296         CanCoalesce = false;
1297         break;
1298       }
1299       SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
1300       DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
1301     }
1302
1303     if (!CanCoalesce || SrcSubIndices.size() < 2)
1304       continue;
1305
1306     // Check that the source subregisters can be combined.
1307     std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
1308     unsigned NewSrcSubIdx = 0;
1309     if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
1310                                       NewSrcSubIdx))
1311       continue;
1312
1313     // Check that the destination subregisters can also be combined.
1314     std::sort(DstSubIndices.begin(), DstSubIndices.end());
1315     unsigned NewDstSubIdx = 0;
1316     if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1317                                       NewDstSubIdx))
1318       continue;
1319
1320     // If neither source nor destination can be combined to the full register,
1321     // just give up.  This could be improved if it ever matters.
1322     if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1323       continue;
1324
1325     // Now that we know that all the uses are extract_subregs and that those
1326     // subregs can somehow be combined, scan all the extract_subregs again to
1327     // make sure the subregs are in the right order and can be composed.
1328     MachineInstr *SomeMI = 0;
1329     CanCoalesce = true;
1330     for (MachineRegisterInfo::use_nodbg_iterator
1331            UI = MRI->use_nodbg_begin(SrcReg),
1332            UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1333       MachineInstr *UseMI = &*UI;
1334       assert(UseMI->isCopy());
1335       unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
1336       unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
1337       assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
1338       if ((NewDstSubIdx == 0 &&
1339            TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1340           (NewSrcSubIdx == 0 &&
1341            TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
1342         CanCoalesce = false;
1343         break;
1344       }
1345       // Keep track of one of the uses.
1346       SomeMI = UseMI;
1347     }
1348     if (!CanCoalesce)
1349       continue;
1350
1351     // Insert a copy to replace the original.
1352     MachineBasicBlock::iterator InsertLoc = SomeMI;
1353     MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1354                                    SomeMI->getDebugLoc(),
1355                                    TII->get(TargetOpcode::COPY))
1356       .addReg(DstReg, RegState::Define, NewDstSubIdx)
1357       .addReg(SrcReg, 0, NewSrcSubIdx);
1358
1359     // Remove all the old extract instructions.
1360     for (MachineRegisterInfo::use_nodbg_iterator
1361            UI = MRI->use_nodbg_begin(SrcReg),
1362            UE = MRI->use_nodbg_end(); UI != UE; ) {
1363       MachineInstr *UseMI = &*UI;
1364       ++UI;
1365       if (UseMI == CopyMI)
1366         continue;
1367       assert(UseMI->isCopy());
1368       // Move any kills to the new copy or extract instruction.
1369       if (UseMI->getOperand(1).isKill()) {
1370         CopyMI->getOperand(1).setIsKill();
1371         if (LV)
1372           // Update live variables
1373           LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1374       }
1375       UseMI->eraseFromParent();
1376     }
1377   }
1378 }
1379
1380 static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1381                                     MachineRegisterInfo *MRI) {
1382   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1383          UE = MRI->use_end(); UI != UE; ++UI) {
1384     MachineInstr *UseMI = &*UI;
1385     if (UseMI != RegSeq && UseMI->isRegSequence())
1386       return true;
1387   }
1388   return false;
1389 }
1390
1391 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1392 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1393 /// sub-register references of the register defined by REG_SEQUENCE. e.g.
1394 ///
1395 /// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1396 /// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1397 /// =>
1398 /// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1399 bool TwoAddressInstructionPass::EliminateRegSequences() {
1400   if (RegSequences.empty())
1401     return false;
1402
1403   for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1404     MachineInstr *MI = RegSequences[i];
1405     unsigned DstReg = MI->getOperand(0).getReg();
1406     if (MI->getOperand(0).getSubReg() ||
1407         TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1408         !(MI->getNumOperands() & 1)) {
1409       DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1410       llvm_unreachable(0);
1411     }
1412
1413     bool IsImpDef = true;
1414     SmallVector<unsigned, 4> RealSrcs;
1415     SmallSet<unsigned, 4> Seen;
1416     for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1417       unsigned SrcReg = MI->getOperand(i).getReg();
1418       if (MI->getOperand(i).getSubReg() ||
1419           TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1420         DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1421         llvm_unreachable(0);
1422       }
1423
1424       MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
1425       if (DefMI->isImplicitDef()) {
1426         DefMI->eraseFromParent();
1427         continue;
1428       }
1429       IsImpDef = false;
1430
1431       // Remember COPY sources. These might be candidate for coalescing.
1432       if (DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1433         RealSrcs.push_back(DefMI->getOperand(1).getReg());
1434
1435       bool isKill = MI->getOperand(i).isKill();
1436       if (!Seen.insert(SrcReg) || MI->getParent() != DefMI->getParent() ||
1437           !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI)) {
1438         // REG_SEQUENCE cannot have duplicated operands, add a copy.
1439         // Also add an copy if the source is live-in the block. We don't want
1440         // to end up with a partial-redef of a livein, e.g.
1441         // BB0:
1442         // reg1051:10<def> =
1443         // ...
1444         // BB1:
1445         // ... = reg1051:10
1446         // BB2:
1447         // reg1051:9<def> =
1448         // LiveIntervalAnalysis won't like it.
1449         //
1450         // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1451         // correctly up to date becomes very difficult. Insert a copy.
1452
1453         // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1454         // might insert a COPY that uses SrcReg after is was killed.
1455         if (isKill)
1456           for (unsigned j = i + 2; j < e; j += 2)
1457             if (MI->getOperand(j).getReg() == SrcReg) {
1458               MI->getOperand(j).setIsKill();
1459               isKill = false;
1460               break;
1461             }
1462
1463         MachineBasicBlock::iterator InsertLoc = MI;
1464         MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1465                                 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1466             .addReg(DstReg, RegState::Define, MI->getOperand(i+1).getImm())
1467             .addReg(SrcReg, getKillRegState(isKill));
1468         MI->getOperand(i).setReg(0);
1469         if (LV && isKill)
1470           LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1471         DEBUG(dbgs() << "Inserted: " << *CopyMI);
1472       }
1473     }
1474
1475     for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1476       unsigned SrcReg = MI->getOperand(i).getReg();
1477       if (!SrcReg) continue;
1478       unsigned SubIdx = MI->getOperand(i+1).getImm();
1479       UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1480     }
1481
1482     if (IsImpDef) {
1483       DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1484       MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1485       for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1486         MI->RemoveOperand(j);      
1487     } else {
1488       DEBUG(dbgs() << "Eliminated: " << *MI);
1489       MI->eraseFromParent();
1490     }
1491
1492     // Try coalescing some EXTRACT_SUBREG instructions. This can create
1493     // INSERT_SUBREG instructions that must have <undef> flags added by
1494     // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1495     if (LV)
1496       CoalesceExtSubRegs(RealSrcs, DstReg);
1497   }
1498
1499   RegSequences.clear();
1500   return true;
1501 }