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