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