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