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