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