xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
496     const MachineOperand &MO = MI->getOperand(i);
497     if (MO.isRegMask()) {
498       removeMapRegEntry(MO, SrcRegMap, TRI);
499       continue;
500     }
501     if (!MO.isReg() || !MO.isDef())
502       continue;
503     Register Reg = MO.getReg();
504     if (!Reg || Reg.isVirtual())
505       continue;
506     removeMapRegEntry(MO, SrcRegMap, TRI);
507   }
508 }
509 
510 // Returns true if Reg is equal or aliased to at least one register in Set.
511 static bool regOverlapsSet(const SmallVectorImpl<Register> &Set, Register Reg,
512                            const TargetRegisterInfo *TRI) {
513   for (unsigned R : Set)
514     if (TRI->regsOverlap(R, Reg))
515       return true;
516 
517   return false;
518 }
519 
520 /// Return true if it's potentially profitable to commute the two-address
521 /// instruction that's being processed.
522 bool TwoAddressInstructionPass::isProfitableToCommute(Register RegA,
523                                                       Register RegB,
524                                                       Register RegC,
525                                                       MachineInstr *MI,
526                                                       unsigned Dist) {
527   if (OptLevel == CodeGenOpt::None)
528     return false;
529 
530   // Determine if it's profitable to commute this two address instruction. In
531   // general, we want no uses between this instruction and the definition of
532   // the two-address register.
533   // e.g.
534   // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
535   // %reg1029 = COPY %reg1028
536   // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
537   // insert => %reg1030 = COPY %reg1028
538   // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
539   // In this case, it might not be possible to coalesce the second COPY
540   // instruction if the first one is coalesced. So it would be profitable to
541   // commute it:
542   // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
543   // %reg1029 = COPY %reg1028
544   // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
545   // insert => %reg1030 = COPY %reg1029
546   // %reg1030 = ADD8rr killed %reg1029, killed %reg1028, implicit dead %eflags
547 
548   if (!isPlainlyKilled(MI, RegC, LIS))
549     return false;
550 
551   // Ok, we have something like:
552   // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
553   // let's see if it's worth commuting it.
554 
555   // Look for situations like this:
556   // %reg1024 = MOV r1
557   // %reg1025 = MOV r0
558   // %reg1026 = ADD %reg1024, %reg1025
559   // r0            = MOV %reg1026
560   // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
561   MCRegister ToRegA = getMappedReg(RegA, DstRegMap);
562   if (ToRegA) {
563     MCRegister FromRegB = getMappedReg(RegB, SrcRegMap);
564     MCRegister FromRegC = getMappedReg(RegC, SrcRegMap);
565     bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
566     bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
567 
568     // Compute if any of the following are true:
569     // -RegB is not tied to a register and RegC is compatible with RegA.
570     // -RegB is tied to the wrong physical register, but RegC is.
571     // -RegB is tied to the wrong physical register, and RegC isn't tied.
572     if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
573       return true;
574     // Don't compute if any of the following are true:
575     // -RegC is not tied to a register and RegB is compatible with RegA.
576     // -RegC is tied to the wrong physical register, but RegB is.
577     // -RegC is tied to the wrong physical register, and RegB isn't tied.
578     if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
579       return false;
580   }
581 
582   // If there is a use of RegC between its last def (could be livein) and this
583   // instruction, then bail.
584   unsigned LastDefC = 0;
585   if (!noUseAfterLastDef(RegC, Dist, LastDefC))
586     return false;
587 
588   // If there is a use of RegB between its last def (could be livein) and this
589   // instruction, then go ahead and make this transformation.
590   unsigned LastDefB = 0;
591   if (!noUseAfterLastDef(RegB, Dist, LastDefB))
592     return true;
593 
594   // Look for situation like this:
595   // %reg101 = MOV %reg100
596   // %reg102 = ...
597   // %reg103 = ADD %reg102, %reg101
598   // ... = %reg103 ...
599   // %reg100 = MOV %reg103
600   // If there is a reversed copy chain from reg101 to reg103, commute the ADD
601   // to eliminate an otherwise unavoidable copy.
602   // FIXME:
603   // We can extend the logic further: If an pair of operands in an insn has
604   // been merged, the insn could be regarded as a virtual copy, and the virtual
605   // copy could also be used to construct a copy chain.
606   // To more generally minimize register copies, ideally the logic of two addr
607   // instruction pass should be integrated with register allocation pass where
608   // interference graph is available.
609   if (isRevCopyChain(RegC, RegA, MaxDataFlowEdge))
610     return true;
611 
612   if (isRevCopyChain(RegB, RegA, MaxDataFlowEdge))
613     return false;
614 
615   // Look for other target specific commute preference.
616   bool Commute;
617   if (TII->hasCommutePreference(*MI, Commute))
618     return Commute;
619 
620   // Since there are no intervening uses for both registers, then commute
621   // if the def of RegC is closer. Its live interval is shorter.
622   return LastDefB && LastDefC && LastDefC > LastDefB;
623 }
624 
625 /// Commute a two-address instruction and update the basic block, distance map,
626 /// and live variables if needed. Return true if it is successful.
627 bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI,
628                                                    unsigned DstIdx,
629                                                    unsigned RegBIdx,
630                                                    unsigned RegCIdx,
631                                                    unsigned Dist) {
632   Register RegC = MI->getOperand(RegCIdx).getReg();
633   LLVM_DEBUG(dbgs() << "2addr: COMMUTING  : " << *MI);
634   MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
635 
636   if (NewMI == nullptr) {
637     LLVM_DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
638     return false;
639   }
640 
641   LLVM_DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
642   assert(NewMI == MI &&
643          "TargetInstrInfo::commuteInstruction() should not return a new "
644          "instruction unless it was requested.");
645 
646   // Update source register map.
647   MCRegister FromRegC = getMappedReg(RegC, SrcRegMap);
648   if (FromRegC) {
649     Register RegA = MI->getOperand(DstIdx).getReg();
650     SrcRegMap[RegA] = FromRegC;
651   }
652 
653   return true;
654 }
655 
656 /// Return true if it is profitable to convert the given 2-address instruction
657 /// to a 3-address one.
658 bool TwoAddressInstructionPass::isProfitableToConv3Addr(Register RegA,
659                                                         Register RegB) {
660   // Look for situations like this:
661   // %reg1024 = MOV r1
662   // %reg1025 = MOV r0
663   // %reg1026 = ADD %reg1024, %reg1025
664   // r2            = MOV %reg1026
665   // Turn ADD into a 3-address instruction to avoid a copy.
666   MCRegister FromRegB = getMappedReg(RegB, SrcRegMap);
667   if (!FromRegB)
668     return false;
669   MCRegister ToRegA = getMappedReg(RegA, DstRegMap);
670   return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
671 }
672 
673 /// Convert the specified two-address instruction into a three address one.
674 /// Return true if this transformation was successful.
675 bool TwoAddressInstructionPass::convertInstTo3Addr(
676     MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi,
677     Register RegA, Register RegB, unsigned &Dist) {
678   MachineInstrSpan MIS(mi, MBB);
679   MachineInstr *NewMI = TII->convertToThreeAddress(*mi, LV, LIS);
680   if (!NewMI)
681     return false;
682 
683   LLVM_DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
684   LLVM_DEBUG(dbgs() << "2addr:         TO 3-ADDR: " << *NewMI);
685 
686   // If the old instruction is debug value tracked, an update is required.
687   if (auto OldInstrNum = mi->peekDebugInstrNum()) {
688     // Sanity check.
689     assert(mi->getNumExplicitDefs() == 1);
690     assert(NewMI->getNumExplicitDefs() == 1);
691 
692     // Find the old and new def location.
693     auto OldIt = mi->defs().begin();
694     auto NewIt = NewMI->defs().begin();
695     unsigned OldIdx = mi->getOperandNo(OldIt);
696     unsigned NewIdx = NewMI->getOperandNo(NewIt);
697 
698     // Record that one def has been replaced by the other.
699     unsigned NewInstrNum = NewMI->getDebugInstrNum();
700     MF->makeDebugValueSubstitution(std::make_pair(OldInstrNum, OldIdx),
701                                    std::make_pair(NewInstrNum, NewIdx));
702   }
703 
704   MBB->erase(mi); // Nuke the old inst.
705 
706   for (MachineInstr &MI : MIS)
707     DistanceMap.insert(std::make_pair(&MI, Dist++));
708   Dist--;
709   mi = NewMI;
710   nmi = std::next(mi);
711 
712   // Update source and destination register maps.
713   SrcRegMap.erase(RegA);
714   DstRegMap.erase(RegB);
715   return true;
716 }
717 
718 /// Scan forward recursively for only uses, update maps if the use is a copy or
719 /// a two-address instruction.
720 void TwoAddressInstructionPass::scanUses(Register DstReg) {
721   SmallVector<Register, 4> VirtRegPairs;
722   bool IsDstPhys;
723   bool IsCopy = false;
724   Register NewReg;
725   Register Reg = DstReg;
726   while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
727                                                       NewReg, IsDstPhys)) {
728     if (IsCopy && !Processed.insert(UseMI).second)
729       break;
730 
731     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
732     if (DI != DistanceMap.end())
733       // Earlier in the same MBB.Reached via a back edge.
734       break;
735 
736     if (IsDstPhys) {
737       VirtRegPairs.push_back(NewReg);
738       break;
739     }
740     SrcRegMap[NewReg] = Reg;
741     VirtRegPairs.push_back(NewReg);
742     Reg = NewReg;
743   }
744 
745   if (!VirtRegPairs.empty()) {
746     unsigned ToReg = VirtRegPairs.back();
747     VirtRegPairs.pop_back();
748     while (!VirtRegPairs.empty()) {
749       unsigned FromReg = VirtRegPairs.pop_back_val();
750       bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
751       if (!isNew)
752         assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
753       ToReg = FromReg;
754     }
755     bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
756     if (!isNew)
757       assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
758   }
759 }
760 
761 /// If the specified instruction is not yet processed, process it if it's a
762 /// copy. For a copy instruction, we find the physical registers the
763 /// source and destination registers might be mapped to. These are kept in
764 /// point-to maps used to determine future optimizations. e.g.
765 /// v1024 = mov r0
766 /// v1025 = mov r1
767 /// v1026 = add v1024, v1025
768 /// r1    = mov r1026
769 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
770 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
771 /// potentially joined with r1 on the output side. It's worthwhile to commute
772 /// 'add' to eliminate a copy.
773 void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
774   if (Processed.count(MI))
775     return;
776 
777   bool IsSrcPhys, IsDstPhys;
778   Register SrcReg, DstReg;
779   if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
780     return;
781 
782   if (IsDstPhys && !IsSrcPhys) {
783     DstRegMap.insert(std::make_pair(SrcReg, DstReg));
784   } else if (!IsDstPhys && IsSrcPhys) {
785     bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
786     if (!isNew)
787       assert(SrcRegMap[DstReg] == SrcReg &&
788              "Can't map to two src physical registers!");
789 
790     scanUses(DstReg);
791   }
792 
793   Processed.insert(MI);
794 }
795 
796 /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
797 /// consider moving the instruction below the kill instruction in order to
798 /// eliminate the need for the copy.
799 bool TwoAddressInstructionPass::rescheduleMIBelowKill(
800     MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi,
801     Register Reg) {
802   // Bail immediately if we don't have LV or LIS available. We use them to find
803   // kills efficiently.
804   if (!LV && !LIS)
805     return false;
806 
807   MachineInstr *MI = &*mi;
808   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
809   if (DI == DistanceMap.end())
810     // Must be created from unfolded load. Don't waste time trying this.
811     return false;
812 
813   MachineInstr *KillMI = nullptr;
814   if (LIS) {
815     LiveInterval &LI = LIS->getInterval(Reg);
816     assert(LI.end() != LI.begin() &&
817            "Reg should not have empty live interval.");
818 
819     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
820     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
821     if (I != LI.end() && I->start < MBBEndIdx)
822       return false;
823 
824     --I;
825     KillMI = LIS->getInstructionFromIndex(I->end);
826   } else {
827     KillMI = LV->getVarInfo(Reg).findKill(MBB);
828   }
829   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
830     // Don't mess with copies, they may be coalesced later.
831     return false;
832 
833   if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
834       KillMI->isBranch() || KillMI->isTerminator())
835     // Don't move pass calls, etc.
836     return false;
837 
838   Register DstReg;
839   if (isTwoAddrUse(*KillMI, Reg, DstReg))
840     return false;
841 
842   bool SeenStore = true;
843   if (!MI->isSafeToMove(AA, SeenStore))
844     return false;
845 
846   if (TII->getInstrLatency(InstrItins, *MI) > 1)
847     // FIXME: Needs more sophisticated heuristics.
848     return false;
849 
850   SmallVector<Register, 2> Uses;
851   SmallVector<Register, 2> Kills;
852   SmallVector<Register, 2> Defs;
853   for (const MachineOperand &MO : MI->operands()) {
854     if (!MO.isReg())
855       continue;
856     Register MOReg = MO.getReg();
857     if (!MOReg)
858       continue;
859     if (MO.isDef())
860       Defs.push_back(MOReg);
861     else {
862       Uses.push_back(MOReg);
863       if (MOReg != Reg && (MO.isKill() ||
864                            (LIS && isPlainlyKilled(MI, MOReg, LIS))))
865         Kills.push_back(MOReg);
866     }
867   }
868 
869   // Move the copies connected to MI down as well.
870   MachineBasicBlock::iterator Begin = MI;
871   MachineBasicBlock::iterator AfterMI = std::next(Begin);
872   MachineBasicBlock::iterator End = AfterMI;
873   while (End != MBB->end()) {
874     End = skipDebugInstructionsForward(End, MBB->end());
875     if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg(), TRI))
876       Defs.push_back(End->getOperand(0).getReg());
877     else
878       break;
879     ++End;
880   }
881 
882   // Check if the reschedule will not break dependencies.
883   unsigned NumVisited = 0;
884   MachineBasicBlock::iterator KillPos = KillMI;
885   ++KillPos;
886   for (MachineInstr &OtherMI : make_range(End, KillPos)) {
887     // Debug or pseudo instructions cannot be counted against the limit.
888     if (OtherMI.isDebugOrPseudoInstr())
889       continue;
890     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
891       return false;
892     ++NumVisited;
893     if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
894         OtherMI.isBranch() || OtherMI.isTerminator())
895       // Don't move pass calls, etc.
896       return false;
897     for (const MachineOperand &MO : OtherMI.operands()) {
898       if (!MO.isReg())
899         continue;
900       Register MOReg = MO.getReg();
901       if (!MOReg)
902         continue;
903       if (MO.isDef()) {
904         if (regOverlapsSet(Uses, MOReg, TRI))
905           // Physical register use would be clobbered.
906           return false;
907         if (!MO.isDead() && regOverlapsSet(Defs, MOReg, TRI))
908           // May clobber a physical register def.
909           // FIXME: This may be too conservative. It's ok if the instruction
910           // is sunken completely below the use.
911           return false;
912       } else {
913         if (regOverlapsSet(Defs, MOReg, TRI))
914           return false;
915         bool isKill =
916             MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS));
917         if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg, TRI)) ||
918                              regOverlapsSet(Kills, MOReg, TRI)))
919           // Don't want to extend other live ranges and update kills.
920           return false;
921         if (MOReg == Reg && !isKill)
922           // We can't schedule across a use of the register in question.
923           return false;
924         // Ensure that if this is register in question, its the kill we expect.
925         assert((MOReg != Reg || &OtherMI == KillMI) &&
926                "Found multiple kills of a register in a basic block");
927       }
928     }
929   }
930 
931   // Move debug info as well.
932   while (Begin != MBB->begin() && std::prev(Begin)->isDebugInstr())
933     --Begin;
934 
935   nmi = End;
936   MachineBasicBlock::iterator InsertPos = KillPos;
937   if (LIS) {
938     // We have to move the copies (and any interleaved debug instructions)
939     // first so that the MBB is still well-formed when calling handleMove().
940     for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
941       auto CopyMI = MBBI++;
942       MBB->splice(InsertPos, MBB, CopyMI);
943       if (!CopyMI->isDebugOrPseudoInstr())
944         LIS->handleMove(*CopyMI);
945       InsertPos = CopyMI;
946     }
947     End = std::next(MachineBasicBlock::iterator(MI));
948   }
949 
950   // Copies following MI may have been moved as well.
951   MBB->splice(InsertPos, MBB, Begin, End);
952   DistanceMap.erase(DI);
953 
954   // Update live variables
955   if (LIS) {
956     LIS->handleMove(*MI);
957   } else {
958     LV->removeVirtualRegisterKilled(Reg, *KillMI);
959     LV->addVirtualRegisterKilled(Reg, *MI);
960   }
961 
962   LLVM_DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
963   return true;
964 }
965 
966 /// Return true if the re-scheduling will put the given instruction too close
967 /// to the defs of its register dependencies.
968 bool TwoAddressInstructionPass::isDefTooClose(Register Reg, unsigned Dist,
969                                               MachineInstr *MI) {
970   for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
971     if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
972       continue;
973     if (&DefMI == MI)
974       return true; // MI is defining something KillMI uses
975     DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
976     if (DDI == DistanceMap.end())
977       return true;  // Below MI
978     unsigned DefDist = DDI->second;
979     assert(Dist > DefDist && "Visited def already?");
980     if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
981       return true;
982   }
983   return false;
984 }
985 
986 /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
987 /// consider moving the kill instruction above the current two-address
988 /// instruction in order to eliminate the need for the copy.
989 bool TwoAddressInstructionPass::rescheduleKillAboveMI(
990     MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi,
991     Register Reg) {
992   // Bail immediately if we don't have LV or LIS available. We use them to find
993   // kills efficiently.
994   if (!LV && !LIS)
995     return false;
996 
997   MachineInstr *MI = &*mi;
998   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
999   if (DI == DistanceMap.end())
1000     // Must be created from unfolded load. Don't waste time trying this.
1001     return false;
1002 
1003   MachineInstr *KillMI = nullptr;
1004   if (LIS) {
1005     LiveInterval &LI = LIS->getInterval(Reg);
1006     assert(LI.end() != LI.begin() &&
1007            "Reg should not have empty live interval.");
1008 
1009     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1010     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1011     if (I != LI.end() && I->start < MBBEndIdx)
1012       return false;
1013 
1014     --I;
1015     KillMI = LIS->getInstructionFromIndex(I->end);
1016   } else {
1017     KillMI = LV->getVarInfo(Reg).findKill(MBB);
1018   }
1019   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1020     // Don't mess with copies, they may be coalesced later.
1021     return false;
1022 
1023   Register DstReg;
1024   if (isTwoAddrUse(*KillMI, Reg, DstReg))
1025     return false;
1026 
1027   bool SeenStore = true;
1028   if (!KillMI->isSafeToMove(AA, SeenStore))
1029     return false;
1030 
1031   SmallVector<Register, 2> Uses;
1032   SmallVector<Register, 2> Kills;
1033   SmallVector<Register, 2> Defs;
1034   SmallVector<Register, 2> LiveDefs;
1035   for (const MachineOperand &MO : KillMI->operands()) {
1036     if (!MO.isReg())
1037       continue;
1038     Register MOReg = MO.getReg();
1039     if (MO.isUse()) {
1040       if (!MOReg)
1041         continue;
1042       if (isDefTooClose(MOReg, DI->second, MI))
1043         return false;
1044       bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1045       if (MOReg == Reg && !isKill)
1046         return false;
1047       Uses.push_back(MOReg);
1048       if (isKill && MOReg != Reg)
1049         Kills.push_back(MOReg);
1050     } else if (MOReg.isPhysical()) {
1051       Defs.push_back(MOReg);
1052       if (!MO.isDead())
1053         LiveDefs.push_back(MOReg);
1054     }
1055   }
1056 
1057   // Check if the reschedule will not break depedencies.
1058   unsigned NumVisited = 0;
1059   for (MachineInstr &OtherMI :
1060        make_range(mi, MachineBasicBlock::iterator(KillMI))) {
1061     // Debug or pseudo instructions cannot be counted against the limit.
1062     if (OtherMI.isDebugOrPseudoInstr())
1063       continue;
1064     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
1065       return false;
1066     ++NumVisited;
1067     if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1068         OtherMI.isBranch() || OtherMI.isTerminator())
1069       // Don't move pass calls, etc.
1070       return false;
1071     SmallVector<Register, 2> OtherDefs;
1072     for (const MachineOperand &MO : OtherMI.operands()) {
1073       if (!MO.isReg())
1074         continue;
1075       Register MOReg = MO.getReg();
1076       if (!MOReg)
1077         continue;
1078       if (MO.isUse()) {
1079         if (regOverlapsSet(Defs, MOReg, TRI))
1080           // Moving KillMI can clobber the physical register if the def has
1081           // not been seen.
1082           return false;
1083         if (regOverlapsSet(Kills, MOReg, TRI))
1084           // Don't want to extend other live ranges and update kills.
1085           return false;
1086         if (&OtherMI != MI && MOReg == Reg &&
1087             !(MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))))
1088           // We can't schedule across a use of the register in question.
1089           return false;
1090       } else {
1091         OtherDefs.push_back(MOReg);
1092       }
1093     }
1094 
1095     for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1096       Register MOReg = OtherDefs[i];
1097       if (regOverlapsSet(Uses, MOReg, TRI))
1098         return false;
1099       if (MOReg.isPhysical() && regOverlapsSet(LiveDefs, MOReg, TRI))
1100         return false;
1101       // Physical register def is seen.
1102       llvm::erase_value(Defs, MOReg);
1103     }
1104   }
1105 
1106   // Move the old kill above MI, don't forget to move debug info as well.
1107   MachineBasicBlock::iterator InsertPos = mi;
1108   while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugInstr())
1109     --InsertPos;
1110   MachineBasicBlock::iterator From = KillMI;
1111   MachineBasicBlock::iterator To = std::next(From);
1112   while (std::prev(From)->isDebugInstr())
1113     --From;
1114   MBB->splice(InsertPos, MBB, From, To);
1115 
1116   nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
1117   DistanceMap.erase(DI);
1118 
1119   // Update live variables
1120   if (LIS) {
1121     LIS->handleMove(*KillMI);
1122   } else {
1123     LV->removeVirtualRegisterKilled(Reg, *KillMI);
1124     LV->addVirtualRegisterKilled(Reg, *MI);
1125   }
1126 
1127   LLVM_DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1128   return true;
1129 }
1130 
1131 /// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1132 /// given machine instruction to improve opportunities for coalescing and
1133 /// elimination of a register to register copy.
1134 ///
1135 /// 'DstOpIdx' specifies the index of MI def operand.
1136 /// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1137 /// operand is killed by the given instruction.
1138 /// The 'Dist' arguments provides the distance of MI from the start of the
1139 /// current basic block and it is used to determine if it is profitable
1140 /// to commute operands in the instruction.
1141 ///
1142 /// Returns true if the transformation happened. Otherwise, returns false.
1143 bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI,
1144                                                       unsigned DstOpIdx,
1145                                                       unsigned BaseOpIdx,
1146                                                       bool BaseOpKilled,
1147                                                       unsigned Dist) {
1148   if (!MI->isCommutable())
1149     return false;
1150 
1151   bool MadeChange = false;
1152   Register DstOpReg = MI->getOperand(DstOpIdx).getReg();
1153   Register BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1154   unsigned OpsNum = MI->getDesc().getNumOperands();
1155   unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1156   for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1157     // The call of findCommutedOpIndices below only checks if BaseOpIdx
1158     // and OtherOpIdx are commutable, it does not really search for
1159     // other commutable operands and does not change the values of passed
1160     // variables.
1161     if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() ||
1162         !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
1163       continue;
1164 
1165     Register OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1166     bool AggressiveCommute = false;
1167 
1168     // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1169     // operands. This makes the live ranges of DstOp and OtherOp joinable.
1170     bool OtherOpKilled = isKilled(*MI, OtherOpReg, MRI, TII, LIS, false);
1171     bool DoCommute = !BaseOpKilled && OtherOpKilled;
1172 
1173     if (!DoCommute &&
1174         isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1175       DoCommute = true;
1176       AggressiveCommute = true;
1177     }
1178 
1179     // If it's profitable to commute, try to do so.
1180     if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1181                                         Dist)) {
1182       MadeChange = true;
1183       ++NumCommuted;
1184       if (AggressiveCommute)
1185         ++NumAggrCommuted;
1186 
1187       // There might be more than two commutable operands, update BaseOp and
1188       // continue scanning.
1189       // FIXME: This assumes that the new instruction's operands are in the
1190       // same positions and were simply swapped.
1191       BaseOpReg = OtherOpReg;
1192       BaseOpKilled = OtherOpKilled;
1193       // Resamples OpsNum in case the number of operands was reduced. This
1194       // happens with X86.
1195       OpsNum = MI->getDesc().getNumOperands();
1196     }
1197   }
1198   return MadeChange;
1199 }
1200 
1201 /// For the case where an instruction has a single pair of tied register
1202 /// operands, attempt some transformations that may either eliminate the tied
1203 /// operands or improve the opportunities for coalescing away the register copy.
1204 /// Returns true if no copy needs to be inserted to untie mi's operands
1205 /// (either because they were untied, or because mi was rescheduled, and will
1206 /// be visited again later). If the shouldOnlyCommute flag is true, only
1207 /// instruction commutation is attempted.
1208 bool TwoAddressInstructionPass::
1209 tryInstructionTransform(MachineBasicBlock::iterator &mi,
1210                         MachineBasicBlock::iterator &nmi,
1211                         unsigned SrcIdx, unsigned DstIdx,
1212                         unsigned &Dist, bool shouldOnlyCommute) {
1213   if (OptLevel == CodeGenOpt::None)
1214     return false;
1215 
1216   MachineInstr &MI = *mi;
1217   Register regA = MI.getOperand(DstIdx).getReg();
1218   Register regB = MI.getOperand(SrcIdx).getReg();
1219 
1220   assert(regB.isVirtual() && "cannot make instruction into two-address form");
1221   bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1222 
1223   if (regA.isVirtual())
1224     scanUses(regA);
1225 
1226   bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
1227 
1228   // If the instruction is convertible to 3 Addr, instead
1229   // of returning try 3 Addr transformation aggressively and
1230   // use this variable to check later. Because it might be better.
1231   // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1232   // instead of the following code.
1233   //   addl     %esi, %edi
1234   //   movl     %edi, %eax
1235   //   ret
1236   if (Commuted && !MI.isConvertibleTo3Addr())
1237     return false;
1238 
1239   if (shouldOnlyCommute)
1240     return false;
1241 
1242   // If there is one more use of regB later in the same MBB, consider
1243   // re-schedule this MI below it.
1244   if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
1245     ++NumReSchedDowns;
1246     return true;
1247   }
1248 
1249   // If we commuted, regB may have changed so we should re-sample it to avoid
1250   // confusing the three address conversion below.
1251   if (Commuted) {
1252     regB = MI.getOperand(SrcIdx).getReg();
1253     regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1254   }
1255 
1256   if (MI.isConvertibleTo3Addr()) {
1257     // This instruction is potentially convertible to a true
1258     // three-address instruction.  Check if it is profitable.
1259     if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1260       // Try to convert it.
1261       if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1262         ++NumConvertedTo3Addr;
1263         return true; // Done with this instruction.
1264       }
1265     }
1266   }
1267 
1268   // Return if it is commuted but 3 addr conversion is failed.
1269   if (Commuted)
1270     return false;
1271 
1272   // If there is one more use of regB later in the same MBB, consider
1273   // re-schedule it before this MI if it's legal.
1274   if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
1275     ++NumReSchedUps;
1276     return true;
1277   }
1278 
1279   // If this is an instruction with a load folded into it, try unfolding
1280   // the load, e.g. avoid this:
1281   //   movq %rdx, %rcx
1282   //   addq (%rax), %rcx
1283   // in favor of this:
1284   //   movq (%rax), %rcx
1285   //   addq %rdx, %rcx
1286   // because it's preferable to schedule a load than a register copy.
1287   if (MI.mayLoad() && !regBKilled) {
1288     // Determine if a load can be unfolded.
1289     unsigned LoadRegIndex;
1290     unsigned NewOpc =
1291       TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1292                                       /*UnfoldLoad=*/true,
1293                                       /*UnfoldStore=*/false,
1294                                       &LoadRegIndex);
1295     if (NewOpc != 0) {
1296       const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1297       if (UnfoldMCID.getNumDefs() == 1) {
1298         // Unfold the load.
1299         LLVM_DEBUG(dbgs() << "2addr:   UNFOLDING: " << MI);
1300         const TargetRegisterClass *RC =
1301           TRI->getAllocatableClass(
1302             TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
1303         Register Reg = MRI->createVirtualRegister(RC);
1304         SmallVector<MachineInstr *, 2> NewMIs;
1305         if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
1306                                       /*UnfoldLoad=*/true,
1307                                       /*UnfoldStore=*/false, NewMIs)) {
1308           LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1309           return false;
1310         }
1311         assert(NewMIs.size() == 2 &&
1312                "Unfolded a load into multiple instructions!");
1313         // The load was previously folded, so this is the only use.
1314         NewMIs[1]->addRegisterKilled(Reg, TRI);
1315 
1316         // Tentatively insert the instructions into the block so that they
1317         // look "normal" to the transformation logic.
1318         MBB->insert(mi, NewMIs[0]);
1319         MBB->insert(mi, NewMIs[1]);
1320         DistanceMap.insert(std::make_pair(NewMIs[0], Dist++));
1321         DistanceMap.insert(std::make_pair(NewMIs[1], Dist));
1322 
1323         LLVM_DEBUG(dbgs() << "2addr:    NEW LOAD: " << *NewMIs[0]
1324                           << "2addr:    NEW INST: " << *NewMIs[1]);
1325 
1326         // Transform the instruction, now that it no longer has a load.
1327         unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1328         unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1329         MachineBasicBlock::iterator NewMI = NewMIs[1];
1330         bool TransformResult =
1331           tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
1332         (void)TransformResult;
1333         assert(!TransformResult &&
1334                "tryInstructionTransform() should return false.");
1335         if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1336           // Success, or at least we made an improvement. Keep the unfolded
1337           // instructions and discard the original.
1338           if (LV) {
1339             for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1340               MachineOperand &MO = MI.getOperand(i);
1341               if (MO.isReg() && MO.getReg().isVirtual()) {
1342                 if (MO.isUse()) {
1343                   if (MO.isKill()) {
1344                     if (NewMIs[0]->killsRegister(MO.getReg()))
1345                       LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
1346                     else {
1347                       assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1348                              "Kill missing after load unfold!");
1349                       LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
1350                     }
1351                   }
1352                 } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
1353                   if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1354                     LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
1355                   else {
1356                     assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1357                            "Dead flag missing after load unfold!");
1358                     LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
1359                   }
1360                 }
1361               }
1362             }
1363             LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
1364           }
1365 
1366           SmallVector<Register, 4> OrigRegs;
1367           if (LIS) {
1368             for (const MachineOperand &MO : MI.operands()) {
1369               if (MO.isReg())
1370                 OrigRegs.push_back(MO.getReg());
1371             }
1372 
1373             LIS->RemoveMachineInstrFromMaps(MI);
1374           }
1375 
1376           MI.eraseFromParent();
1377           DistanceMap.erase(&MI);
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           LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1392           NewMIs[0]->eraseFromParent();
1393           NewMIs[1]->eraseFromParent();
1394           DistanceMap.erase(NewMIs[0]);
1395           DistanceMap.erase(NewMIs[1]);
1396           Dist--;
1397         }
1398       }
1399     }
1400   }
1401 
1402   return false;
1403 }
1404 
1405 // Collect tied operands of MI that need to be handled.
1406 // Rewrite trivial cases immediately.
1407 // Return true if any tied operands where found, including the trivial ones.
1408 bool TwoAddressInstructionPass::
1409 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1410   bool AnyOps = false;
1411   unsigned NumOps = MI->getNumOperands();
1412 
1413   for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1414     unsigned DstIdx = 0;
1415     if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1416       continue;
1417     AnyOps = true;
1418     MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1419     MachineOperand &DstMO = MI->getOperand(DstIdx);
1420     Register SrcReg = SrcMO.getReg();
1421     Register DstReg = DstMO.getReg();
1422     // Tied constraint already satisfied?
1423     if (SrcReg == DstReg)
1424       continue;
1425 
1426     assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1427 
1428     // Deal with undef uses immediately - simply rewrite the src operand.
1429     if (SrcMO.isUndef() && !DstMO.getSubReg()) {
1430       // Constrain the DstReg register class if required.
1431       if (DstReg.isVirtual()) {
1432         const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
1433         MRI->constrainRegClass(DstReg, RC);
1434       }
1435       SrcMO.setReg(DstReg);
1436       SrcMO.setSubReg(0);
1437       LLVM_DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1438       continue;
1439     }
1440     TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1441   }
1442   return AnyOps;
1443 }
1444 
1445 // Process a list of tied MI operands that all use the same source register.
1446 // The tied pairs are of the form (SrcIdx, DstIdx).
1447 void
1448 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1449                                             TiedPairList &TiedPairs,
1450                                             unsigned &Dist) {
1451   bool IsEarlyClobber = llvm::find_if(TiedPairs, [MI](auto const &TP) {
1452                           return MI->getOperand(TP.second).isEarlyClobber();
1453                         }) != TiedPairs.end();
1454 
1455   bool RemovedKillFlag = false;
1456   bool AllUsesCopied = true;
1457   unsigned LastCopiedReg = 0;
1458   SlotIndex LastCopyIdx;
1459   Register RegB = 0;
1460   unsigned SubRegB = 0;
1461   for (auto &TP : TiedPairs) {
1462     unsigned SrcIdx = TP.first;
1463     unsigned DstIdx = TP.second;
1464 
1465     const MachineOperand &DstMO = MI->getOperand(DstIdx);
1466     Register 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(RegB.isVirtual() && "cannot make instruction into two-address form");
1483 
1484 #ifndef NDEBUG
1485     // First, verify that we don't have a use of "a" in the instruction
1486     // (a = b + a for example) because our transformation will not
1487     // work. This should never occur because we are in SSA form.
1488     for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1489       assert(i == DstIdx ||
1490              !MI->getOperand(i).isReg() ||
1491              MI->getOperand(i).getReg() != RegA);
1492 #endif
1493 
1494     // Emit a copy.
1495     MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1496                                       TII->get(TargetOpcode::COPY), RegA);
1497     // If this operand is folding a truncation, the truncation now moves to the
1498     // copy so that the register classes remain valid for the operands.
1499     MIB.addReg(RegB, 0, SubRegB);
1500     const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1501     if (SubRegB) {
1502       if (RegA.isVirtual()) {
1503         assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1504                                              SubRegB) &&
1505                "tied subregister must be a truncation");
1506         // The superreg class will not be used to constrain the subreg class.
1507         RC = nullptr;
1508       } else {
1509         assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1510                && "tied subregister must be a truncation");
1511       }
1512     }
1513 
1514     // Update DistanceMap.
1515     MachineBasicBlock::iterator PrevMI = MI;
1516     --PrevMI;
1517     DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
1518     DistanceMap[MI] = ++Dist;
1519 
1520     if (LIS) {
1521       LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
1522 
1523       SlotIndex endIdx =
1524           LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
1525       if (RegA.isVirtual()) {
1526         LiveInterval &LI = LIS->getInterval(RegA);
1527         VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1528         LI.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1529         for (auto &S : LI.subranges()) {
1530           VNI = S.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1531           S.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1532         }
1533       } else {
1534         for (MCRegUnitIterator Unit(RegA, TRI); Unit.isValid(); ++Unit) {
1535           if (LiveRange *LR = LIS->getCachedRegUnit(*Unit)) {
1536             VNInfo *VNI =
1537                 LR->getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1538             LR->addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1539           }
1540         }
1541       }
1542     }
1543 
1544     LLVM_DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
1545 
1546     MachineOperand &MO = MI->getOperand(SrcIdx);
1547     assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1548            "inconsistent operand info for 2-reg pass");
1549     if (MO.isKill()) {
1550       MO.setIsKill(false);
1551       RemovedKillFlag = true;
1552     }
1553 
1554     // Make sure regA is a legal regclass for the SrcIdx operand.
1555     if (RegA.isVirtual() && RegB.isVirtual())
1556       MRI->constrainRegClass(RegA, RC);
1557     MO.setReg(RegA);
1558     // The getMatchingSuper asserts guarantee that the register class projected
1559     // by SubRegB is compatible with RegA with no subregister. So regardless of
1560     // whether the dest oper writes a subreg, the source oper should not.
1561     MO.setSubReg(0);
1562   }
1563 
1564   if (AllUsesCopied) {
1565     LaneBitmask RemainingUses = LaneBitmask::getNone();
1566     // Replace other (un-tied) uses of regB with LastCopiedReg.
1567     for (MachineOperand &MO : MI->operands()) {
1568       if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1569         if (MO.getSubReg() == SubRegB && !IsEarlyClobber) {
1570           if (MO.isKill()) {
1571             MO.setIsKill(false);
1572             RemovedKillFlag = true;
1573           }
1574           MO.setReg(LastCopiedReg);
1575           MO.setSubReg(0);
1576         } else {
1577           RemainingUses |= TRI->getSubRegIndexLaneMask(MO.getSubReg());
1578         }
1579       }
1580     }
1581 
1582     // Update live variables for regB.
1583     if (RemovedKillFlag && RemainingUses.none() && LV &&
1584         LV->getVarInfo(RegB).removeKill(*MI)) {
1585       MachineBasicBlock::iterator PrevMI = MI;
1586       --PrevMI;
1587       LV->addVirtualRegisterKilled(RegB, *PrevMI);
1588     }
1589 
1590     if (RemovedKillFlag && RemainingUses.none())
1591       SrcRegMap[LastCopiedReg] = RegB;
1592 
1593     // Update LiveIntervals.
1594     if (LIS) {
1595       SlotIndex UseIdx = LIS->getInstructionIndex(*MI);
1596       auto Shrink = [=](LiveRange &LR, LaneBitmask LaneMask) {
1597         LiveRange::Segment *S = LR.getSegmentContaining(LastCopyIdx);
1598         if (!S)
1599           return true;
1600         if ((LaneMask & RemainingUses).any())
1601           return false;
1602         if (S->end.getBaseIndex() != UseIdx)
1603           return false;
1604         S->end = LastCopyIdx;
1605         return true;
1606       };
1607 
1608       LiveInterval &LI = LIS->getInterval(RegB);
1609       bool ShrinkLI = true;
1610       for (auto &S : LI.subranges())
1611         ShrinkLI &= Shrink(S, S.LaneMask);
1612       if (ShrinkLI)
1613         Shrink(LI, LaneBitmask::getAll());
1614     }
1615   } else if (RemovedKillFlag) {
1616     // Some tied uses of regB matched their destination registers, so
1617     // regB is still used in this instruction, but a kill flag was
1618     // removed from a different tied use of regB, so now we need to add
1619     // a kill flag to one of the remaining uses of regB.
1620     for (MachineOperand &MO : MI->operands()) {
1621       if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1622         MO.setIsKill(true);
1623         break;
1624       }
1625     }
1626   }
1627 }
1628 
1629 /// Reduce two-address instructions to two operands.
1630 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1631   MF = &Func;
1632   const TargetMachine &TM = MF->getTarget();
1633   MRI = &MF->getRegInfo();
1634   TII = MF->getSubtarget().getInstrInfo();
1635   TRI = MF->getSubtarget().getRegisterInfo();
1636   InstrItins = MF->getSubtarget().getInstrItineraryData();
1637   LV = getAnalysisIfAvailable<LiveVariables>();
1638   LIS = getAnalysisIfAvailable<LiveIntervals>();
1639   if (auto *AAPass = getAnalysisIfAvailable<AAResultsWrapperPass>())
1640     AA = &AAPass->getAAResults();
1641   else
1642     AA = nullptr;
1643   OptLevel = TM.getOptLevel();
1644   // Disable optimizations if requested. We cannot skip the whole pass as some
1645   // fixups are necessary for correctness.
1646   if (skipFunction(Func.getFunction()))
1647     OptLevel = CodeGenOpt::None;
1648 
1649   bool MadeChange = false;
1650 
1651   LLVM_DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1652   LLVM_DEBUG(dbgs() << "********** Function: " << MF->getName() << '\n');
1653 
1654   // This pass takes the function out of SSA form.
1655   MRI->leaveSSA();
1656 
1657   // This pass will rewrite the tied-def to meet the RegConstraint.
1658   MF->getProperties()
1659       .set(MachineFunctionProperties::Property::TiedOpsRewritten);
1660 
1661   TiedOperandMap TiedOperands;
1662   for (MachineBasicBlock &MBBI : *MF) {
1663     MBB = &MBBI;
1664     unsigned Dist = 0;
1665     DistanceMap.clear();
1666     SrcRegMap.clear();
1667     DstRegMap.clear();
1668     Processed.clear();
1669     for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1670          mi != me; ) {
1671       MachineBasicBlock::iterator nmi = std::next(mi);
1672       // Skip debug instructions.
1673       if (mi->isDebugInstr()) {
1674         mi = nmi;
1675         continue;
1676       }
1677 
1678       // Expand REG_SEQUENCE instructions. This will position mi at the first
1679       // expanded instruction.
1680       if (mi->isRegSequence())
1681         eliminateRegSequence(mi);
1682 
1683       DistanceMap.insert(std::make_pair(&*mi, ++Dist));
1684 
1685       processCopy(&*mi);
1686 
1687       // First scan through all the tied register uses in this instruction
1688       // and record a list of pairs of tied operands for each register.
1689       if (!collectTiedOperands(&*mi, TiedOperands)) {
1690         removeClobberedSrcRegMap(&*mi);
1691         mi = nmi;
1692         continue;
1693       }
1694 
1695       ++NumTwoAddressInstrs;
1696       MadeChange = true;
1697       LLVM_DEBUG(dbgs() << '\t' << *mi);
1698 
1699       // If the instruction has a single pair of tied operands, try some
1700       // transformations that may either eliminate the tied operands or
1701       // improve the opportunities for coalescing away the register copy.
1702       if (TiedOperands.size() == 1) {
1703         SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs
1704           = TiedOperands.begin()->second;
1705         if (TiedPairs.size() == 1) {
1706           unsigned SrcIdx = TiedPairs[0].first;
1707           unsigned DstIdx = TiedPairs[0].second;
1708           Register SrcReg = mi->getOperand(SrcIdx).getReg();
1709           Register DstReg = mi->getOperand(DstIdx).getReg();
1710           if (SrcReg != DstReg &&
1711               tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
1712             // The tied operands have been eliminated or shifted further down
1713             // the block to ease elimination. Continue processing with 'nmi'.
1714             TiedOperands.clear();
1715             removeClobberedSrcRegMap(&*mi);
1716             mi = nmi;
1717             continue;
1718           }
1719         }
1720       }
1721 
1722       // Now iterate over the information collected above.
1723       for (auto &TO : TiedOperands) {
1724         processTiedPairs(&*mi, TO.second, Dist);
1725         LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1726       }
1727 
1728       // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1729       if (mi->isInsertSubreg()) {
1730         // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1731         // To   %reg:subidx = COPY %subreg
1732         unsigned SubIdx = mi->getOperand(3).getImm();
1733         mi->RemoveOperand(3);
1734         assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1735         mi->getOperand(0).setSubReg(SubIdx);
1736         mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1737         mi->RemoveOperand(1);
1738         mi->setDesc(TII->get(TargetOpcode::COPY));
1739         LLVM_DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1740 
1741         // Update LiveIntervals.
1742         if (LIS) {
1743           Register Reg = mi->getOperand(0).getReg();
1744           LiveInterval &LI = LIS->getInterval(Reg);
1745           if (LI.hasSubRanges()) {
1746             // The COPY no longer defines subregs of %reg except for
1747             // %reg.subidx.
1748             LaneBitmask LaneMask =
1749                 TRI->getSubRegIndexLaneMask(mi->getOperand(0).getSubReg());
1750             SlotIndex Idx = LIS->getInstructionIndex(*mi);
1751             for (auto &S : LI.subranges()) {
1752               if ((S.LaneMask & LaneMask).none()) {
1753                 LiveRange::iterator UseSeg = S.FindSegmentContaining(Idx);
1754                 LiveRange::iterator DefSeg = std::next(UseSeg);
1755                 S.MergeValueNumberInto(DefSeg->valno, UseSeg->valno);
1756               }
1757             }
1758 
1759             // The COPY no longer has a use of %reg.
1760             LIS->shrinkToUses(&LI);
1761           } else {
1762             // The live interval for Reg did not have subranges but now it needs
1763             // them because we have introduced a subreg def. Recompute it.
1764             LIS->removeInterval(Reg);
1765             LIS->createAndComputeVirtRegInterval(Reg);
1766           }
1767         }
1768       }
1769 
1770       // Clear TiedOperands here instead of at the top of the loop
1771       // since most instructions do not have tied operands.
1772       TiedOperands.clear();
1773       removeClobberedSrcRegMap(&*mi);
1774       mi = nmi;
1775     }
1776   }
1777 
1778   return MadeChange;
1779 }
1780 
1781 /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
1782 ///
1783 /// The instruction is turned into a sequence of sub-register copies:
1784 ///
1785 ///   %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1786 ///
1787 /// Becomes:
1788 ///
1789 ///   undef %dst:ssub0 = COPY %v1
1790 ///   %dst:ssub1 = COPY %v2
1791 void TwoAddressInstructionPass::
1792 eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1793   MachineInstr &MI = *MBBI;
1794   Register DstReg = MI.getOperand(0).getReg();
1795   if (MI.getOperand(0).getSubReg() || DstReg.isPhysical() ||
1796       !(MI.getNumOperands() & 1)) {
1797     LLVM_DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << MI);
1798     llvm_unreachable(nullptr);
1799   }
1800 
1801   SmallVector<Register, 4> OrigRegs;
1802   if (LIS) {
1803     OrigRegs.push_back(MI.getOperand(0).getReg());
1804     for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
1805       OrigRegs.push_back(MI.getOperand(i).getReg());
1806   }
1807 
1808   bool DefEmitted = false;
1809   for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
1810     MachineOperand &UseMO = MI.getOperand(i);
1811     Register SrcReg = UseMO.getReg();
1812     unsigned SubIdx = MI.getOperand(i+1).getImm();
1813     // Nothing needs to be inserted for undef operands.
1814     if (UseMO.isUndef())
1815       continue;
1816 
1817     // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1818     // might insert a COPY that uses SrcReg after is was killed.
1819     bool isKill = UseMO.isKill();
1820     if (isKill)
1821       for (unsigned j = i + 2; j < e; j += 2)
1822         if (MI.getOperand(j).getReg() == SrcReg) {
1823           MI.getOperand(j).setIsKill();
1824           UseMO.setIsKill(false);
1825           isKill = false;
1826           break;
1827         }
1828 
1829     // Insert the sub-register copy.
1830     MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1831                                    TII->get(TargetOpcode::COPY))
1832                                .addReg(DstReg, RegState::Define, SubIdx)
1833                                .add(UseMO);
1834 
1835     // The first def needs an undef flag because there is no live register
1836     // before it.
1837     if (!DefEmitted) {
1838       CopyMI->getOperand(0).setIsUndef(true);
1839       // Return an iterator pointing to the first inserted instr.
1840       MBBI = CopyMI;
1841     }
1842     DefEmitted = true;
1843 
1844     // Update LiveVariables' kill info.
1845     if (LV && isKill && !SrcReg.isPhysical())
1846       LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
1847 
1848     LLVM_DEBUG(dbgs() << "Inserted: " << *CopyMI);
1849   }
1850 
1851   MachineBasicBlock::iterator EndMBBI =
1852       std::next(MachineBasicBlock::iterator(MI));
1853 
1854   if (!DefEmitted) {
1855     LLVM_DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
1856     MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1857     for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
1858       MI.RemoveOperand(j);
1859   } else {
1860     if (LIS)
1861       LIS->RemoveMachineInstrFromMaps(MI);
1862 
1863     LLVM_DEBUG(dbgs() << "Eliminated: " << MI);
1864     MI.eraseFromParent();
1865   }
1866 
1867   // Udpate LiveIntervals.
1868   if (LIS)
1869     LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
1870 }
1871