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