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