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