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