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 #define DEBUG_TYPE "twoaddrinstr"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Function.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/SmallSet.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/STLExtras.h"
48 using namespace llvm;
49 
50 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
51 STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
52 STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
53 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
54 STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
55 STATISTIC(NumReMats,           "Number of instructions re-materialized");
56 STATISTIC(NumDeletes,          "Number of dead instructions deleted");
57 
58 namespace {
59   class VISIBILITY_HIDDEN TwoAddressInstructionPass
60     : public MachineFunctionPass {
61     const TargetInstrInfo *TII;
62     const TargetRegisterInfo *TRI;
63     MachineRegisterInfo *MRI;
64     LiveVariables *LV;
65 
66     // DistanceMap - Keep track the distance of a MI from the start of the
67     // current basic block.
68     DenseMap<MachineInstr*, unsigned> DistanceMap;
69 
70     // SrcRegMap - A map from virtual registers to physical registers which
71     // are likely targets to be coalesced to due to copies from physical
72     // registers to virtual registers. e.g. v1024 = move r0.
73     DenseMap<unsigned, unsigned> SrcRegMap;
74 
75     // DstRegMap - A map from virtual registers to physical registers which
76     // are likely targets to be coalesced to due to copies to physical
77     // registers from virtual registers. e.g. r1 = move v1024.
78     DenseMap<unsigned, unsigned> DstRegMap;
79 
80     bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
81                               unsigned Reg,
82                               MachineBasicBlock::iterator OldPos);
83 
84     bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
85                              MachineInstr *MI, MachineInstr *DefMI,
86                              MachineBasicBlock *MBB, unsigned Loc);
87 
88     bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
89                            unsigned &LastDef);
90 
91     MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
92                                    unsigned Dist);
93 
94     bool isProfitableToCommute(unsigned regB, unsigned regC,
95                                MachineInstr *MI, MachineBasicBlock *MBB,
96                                unsigned Dist);
97 
98     bool CommuteInstruction(MachineBasicBlock::iterator &mi,
99                             MachineFunction::iterator &mbbi,
100                             unsigned RegB, unsigned RegC, unsigned Dist);
101 
102     bool isProfitableToConv3Addr(unsigned RegA);
103 
104     bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
105                             MachineBasicBlock::iterator &nmi,
106                             MachineFunction::iterator &mbbi,
107                             unsigned RegB, unsigned Dist);
108 
109     void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
110                      SmallPtrSet<MachineInstr*, 8> &Processed);
111   public:
112     static char ID; // Pass identification, replacement for typeid
113     TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
114 
115     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116       AU.setPreservesCFG();
117       AU.addPreserved<LiveVariables>();
118       AU.addPreservedID(MachineLoopInfoID);
119       AU.addPreservedID(MachineDominatorsID);
120       if (StrongPHIElim)
121         AU.addPreservedID(StrongPHIEliminationID);
122       else
123         AU.addPreservedID(PHIEliminationID);
124       MachineFunctionPass::getAnalysisUsage(AU);
125     }
126 
127     /// runOnMachineFunction - Pass entry point.
128     bool runOnMachineFunction(MachineFunction&);
129   };
130 }
131 
132 char TwoAddressInstructionPass::ID = 0;
133 static RegisterPass<TwoAddressInstructionPass>
134 X("twoaddressinstruction", "Two-Address instruction pass");
135 
136 const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
137 
138 /// Sink3AddrInstruction - A two-address instruction has been converted to a
139 /// three-address instruction to avoid clobbering a register. Try to sink it
140 /// past the instruction that would kill the above mentioned register to reduce
141 /// register pressure.
142 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
143                                            MachineInstr *MI, unsigned SavedReg,
144                                            MachineBasicBlock::iterator OldPos) {
145   // Check if it's safe to move this instruction.
146   bool SeenStore = true; // Be conservative.
147   if (!MI->isSafeToMove(TII, SeenStore))
148     return false;
149 
150   unsigned DefReg = 0;
151   SmallSet<unsigned, 4> UseRegs;
152 
153   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
154     const MachineOperand &MO = MI->getOperand(i);
155     if (!MO.isReg())
156       continue;
157     unsigned MOReg = MO.getReg();
158     if (!MOReg)
159       continue;
160     if (MO.isUse() && MOReg != SavedReg)
161       UseRegs.insert(MO.getReg());
162     if (!MO.isDef())
163       continue;
164     if (MO.isImplicit())
165       // Don't try to move it if it implicitly defines a register.
166       return false;
167     if (DefReg)
168       // For now, don't move any instructions that define multiple registers.
169       return false;
170     DefReg = MO.getReg();
171   }
172 
173   // Find the instruction that kills SavedReg.
174   MachineInstr *KillMI = NULL;
175   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
176          UE = MRI->use_end(); UI != UE; ++UI) {
177     MachineOperand &UseMO = UI.getOperand();
178     if (!UseMO.isKill())
179       continue;
180     KillMI = UseMO.getParent();
181     break;
182   }
183 
184   if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
185     return false;
186 
187   // If any of the definitions are used by another instruction between the
188   // position and the kill use, then it's not safe to sink it.
189   //
190   // FIXME: This can be sped up if there is an easy way to query whether an
191   // instruction is before or after another instruction. Then we can use
192   // MachineRegisterInfo def / use instead.
193   MachineOperand *KillMO = NULL;
194   MachineBasicBlock::iterator KillPos = KillMI;
195   ++KillPos;
196 
197   unsigned NumVisited = 0;
198   for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
199     MachineInstr *OtherMI = I;
200     if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
201       return false;
202     ++NumVisited;
203     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
204       MachineOperand &MO = OtherMI->getOperand(i);
205       if (!MO.isReg())
206         continue;
207       unsigned MOReg = MO.getReg();
208       if (!MOReg)
209         continue;
210       if (DefReg == MOReg)
211         return false;
212 
213       if (MO.isKill()) {
214         if (OtherMI == KillMI && MOReg == SavedReg)
215           // Save the operand that kills the register. We want to unset the kill
216           // marker if we can sink MI past it.
217           KillMO = &MO;
218         else if (UseRegs.count(MOReg))
219           // One of the uses is killed before the destination.
220           return false;
221       }
222     }
223   }
224 
225   // Update kill and LV information.
226   KillMO->setIsKill(false);
227   KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
228   KillMO->setIsKill(true);
229 
230   if (LV)
231     LV->replaceKillInstruction(SavedReg, KillMI, MI);
232 
233   // Move instruction to its destination.
234   MBB->remove(MI);
235   MBB->insert(KillPos, MI);
236 
237   ++Num3AddrSunk;
238   return true;
239 }
240 
241 /// isTwoAddrUse - Return true if the specified MI is using the specified
242 /// register as a two-address operand.
243 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
244   const TargetInstrDesc &TID = UseMI->getDesc();
245   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
246     MachineOperand &MO = UseMI->getOperand(i);
247     if (MO.isReg() && MO.getReg() == Reg &&
248         (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
249       // Earlier use is a two-address one.
250       return true;
251   }
252   return false;
253 }
254 
255 /// isProfitableToReMat - Return true if the heuristics determines it is likely
256 /// to be profitable to re-materialize the definition of Reg rather than copy
257 /// the register.
258 bool
259 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
260                                          const TargetRegisterClass *RC,
261                                          MachineInstr *MI, MachineInstr *DefMI,
262                                          MachineBasicBlock *MBB, unsigned Loc) {
263   bool OtherUse = false;
264   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
265          UE = MRI->use_end(); UI != UE; ++UI) {
266     MachineOperand &UseMO = UI.getOperand();
267     MachineInstr *UseMI = UseMO.getParent();
268     MachineBasicBlock *UseMBB = UseMI->getParent();
269     if (UseMBB == MBB) {
270       DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
271       if (DI != DistanceMap.end() && DI->second == Loc)
272         continue;  // Current use.
273       OtherUse = true;
274       // There is at least one other use in the MBB that will clobber the
275       // register.
276       if (isTwoAddrUse(UseMI, Reg))
277         return true;
278     }
279   }
280 
281   // If other uses in MBB are not two-address uses, then don't remat.
282   if (OtherUse)
283     return false;
284 
285   // No other uses in the same block, remat if it's defined in the same
286   // block so it does not unnecessarily extend the live range.
287   return MBB == DefMI->getParent();
288 }
289 
290 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
291 /// last instruction in the MBB that defines the specified register and the
292 /// two-address instruction which is being processed. It also returns the last
293 /// def location by reference
294 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
295                                            MachineBasicBlock *MBB, unsigned Dist,
296                                            unsigned &LastDef) {
297   LastDef = 0;
298   unsigned LastUse = Dist;
299   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
300          E = MRI->reg_end(); I != E; ++I) {
301     MachineOperand &MO = I.getOperand();
302     MachineInstr *MI = MO.getParent();
303     if (MI->getParent() != MBB)
304       continue;
305     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
306     if (DI == DistanceMap.end())
307       continue;
308     if (MO.isUse() && DI->second < LastUse)
309       LastUse = DI->second;
310     if (MO.isDef() && DI->second > LastDef)
311       LastDef = DI->second;
312   }
313 
314   return !(LastUse > LastDef && LastUse < Dist);
315 }
316 
317 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
318                                                          MachineBasicBlock *MBB,
319                                                          unsigned Dist) {
320   unsigned LastUseDist = 0;
321   MachineInstr *LastUse = 0;
322   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
323          E = MRI->reg_end(); I != E; ++I) {
324     MachineOperand &MO = I.getOperand();
325     MachineInstr *MI = MO.getParent();
326     if (MI->getParent() != MBB)
327       continue;
328     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
329     if (DI == DistanceMap.end())
330       continue;
331     if (DI->second >= Dist)
332       continue;
333 
334     if (MO.isUse() && DI->second > LastUseDist) {
335       LastUse = DI->first;
336       LastUseDist = DI->second;
337     }
338   }
339   return LastUse;
340 }
341 
342 /// isCopyToReg - Return true if the specified MI is a copy instruction or
343 /// a extract_subreg instruction. It also returns the source and destination
344 /// registers and whether they are physical registers by reference.
345 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
346                         unsigned &SrcReg, unsigned &DstReg,
347                         bool &IsSrcPhys, bool &IsDstPhys) {
348   SrcReg = 0;
349   DstReg = 0;
350   unsigned SrcSubIdx, DstSubIdx;
351   if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
352     if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
353       DstReg = MI.getOperand(0).getReg();
354       SrcReg = MI.getOperand(1).getReg();
355     } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
356       DstReg = MI.getOperand(0).getReg();
357       SrcReg = MI.getOperand(2).getReg();
358     } else if (MI.getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
359       DstReg = MI.getOperand(0).getReg();
360       SrcReg = MI.getOperand(2).getReg();
361     }
362   }
363 
364   if (DstReg) {
365     IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
366     IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
367     return true;
368   }
369   return false;
370 }
371 
372 /// isKilled - Test if the given register value, which is used by the given
373 /// instruction, is killed by the given instruction. This looks through
374 /// coalescable copies to see if the original value is potentially not killed.
375 ///
376 /// For example, in this code:
377 ///
378 ///   %reg1034 = copy %reg1024
379 ///   %reg1035 = copy %reg1025<kill>
380 ///   %reg1036 = add %reg1034<kill>, %reg1035<kill>
381 ///
382 /// %reg1034 is not considered to be killed, since it is copied from a
383 /// register which is not killed. Treating it as not killed lets the
384 /// normal heuristics commute the (two-address) add, which lets
385 /// coalescing eliminate the extra copy.
386 ///
387 static bool isKilled(MachineInstr &MI, unsigned Reg,
388                      const MachineRegisterInfo *MRI,
389                      const TargetInstrInfo *TII) {
390   MachineInstr *DefMI = &MI;
391   for (;;) {
392     if (!DefMI->killsRegister(Reg))
393       return false;
394     if (TargetRegisterInfo::isPhysicalRegister(Reg))
395       return true;
396     MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
397     // If there are multiple defs, we can't do a simple analysis, so just
398     // go with what the kill flag says.
399     if (next(Begin) != MRI->def_end())
400       return true;
401     DefMI = &*Begin;
402     bool IsSrcPhys, IsDstPhys;
403     unsigned SrcReg,  DstReg;
404     // If the def is something other than a copy, then it isn't going to
405     // be coalesced, so follow the kill flag.
406     if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
407       return true;
408     Reg = SrcReg;
409   }
410 }
411 
412 /// isTwoAddrUse - Return true if the specified MI uses the specified register
413 /// as a two-address use. If so, return the destination register by reference.
414 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
415   const TargetInstrDesc &TID = MI.getDesc();
416   unsigned NumOps = (MI.getOpcode() == TargetInstrInfo::INLINEASM)
417     ? MI.getNumOperands() : TID.getNumOperands();
418   for (unsigned i = 0; i != NumOps; ++i) {
419     const MachineOperand &MO = MI.getOperand(i);
420     if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
421       continue;
422     unsigned ti;
423     if (MI.isRegTiedToDefOperand(i, &ti)) {
424       DstReg = MI.getOperand(ti).getReg();
425       return true;
426     }
427   }
428   return false;
429 }
430 
431 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
432 /// use, return the use instruction if it's a copy or a two-address use.
433 static
434 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
435                                      MachineRegisterInfo *MRI,
436                                      const TargetInstrInfo *TII,
437                                      bool &IsCopy,
438                                      unsigned &DstReg, bool &IsDstPhys) {
439   MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
440   if (UI == MRI->use_end())
441     return 0;
442   MachineInstr &UseMI = *UI;
443   if (++UI != MRI->use_end())
444     // More than one use.
445     return 0;
446   if (UseMI.getParent() != MBB)
447     return 0;
448   unsigned SrcReg;
449   bool IsSrcPhys;
450   if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
451     IsCopy = true;
452     return &UseMI;
453   }
454   IsDstPhys = false;
455   if (isTwoAddrUse(UseMI, Reg, DstReg)) {
456     IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
457     return &UseMI;
458   }
459   return 0;
460 }
461 
462 /// getMappedReg - Return the physical register the specified virtual register
463 /// might be mapped to.
464 static unsigned
465 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
466   while (TargetRegisterInfo::isVirtualRegister(Reg))  {
467     DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
468     if (SI == RegMap.end())
469       return 0;
470     Reg = SI->second;
471   }
472   if (TargetRegisterInfo::isPhysicalRegister(Reg))
473     return Reg;
474   return 0;
475 }
476 
477 /// regsAreCompatible - Return true if the two registers are equal or aliased.
478 ///
479 static bool
480 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
481   if (RegA == RegB)
482     return true;
483   if (!RegA || !RegB)
484     return false;
485   return TRI->regsOverlap(RegA, RegB);
486 }
487 
488 
489 /// isProfitableToReMat - Return true if it's potentially profitable to commute
490 /// the two-address instruction that's being processed.
491 bool
492 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
493                                        MachineInstr *MI, MachineBasicBlock *MBB,
494                                        unsigned Dist) {
495   // Determine if it's profitable to commute this two address instruction. In
496   // general, we want no uses between this instruction and the definition of
497   // the two-address register.
498   // e.g.
499   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
500   // %reg1029<def> = MOV8rr %reg1028
501   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
502   // insert => %reg1030<def> = MOV8rr %reg1028
503   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
504   // In this case, it might not be possible to coalesce the second MOV8rr
505   // instruction if the first one is coalesced. So it would be profitable to
506   // commute it:
507   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
508   // %reg1029<def> = MOV8rr %reg1028
509   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
510   // insert => %reg1030<def> = MOV8rr %reg1029
511   // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
512 
513   if (!MI->killsRegister(regC))
514     return false;
515 
516   // Ok, we have something like:
517   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
518   // let's see if it's worth commuting it.
519 
520   // Look for situations like this:
521   // %reg1024<def> = MOV r1
522   // %reg1025<def> = MOV r0
523   // %reg1026<def> = ADD %reg1024, %reg1025
524   // r0            = MOV %reg1026
525   // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
526   unsigned FromRegB = getMappedReg(regB, SrcRegMap);
527   unsigned FromRegC = getMappedReg(regC, SrcRegMap);
528   unsigned ToRegB = getMappedReg(regB, DstRegMap);
529   unsigned ToRegC = getMappedReg(regC, DstRegMap);
530   if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
531       (regsAreCompatible(FromRegB, ToRegC, TRI) ||
532        regsAreCompatible(FromRegC, ToRegB, TRI)))
533     return true;
534 
535   // If there is a use of regC between its last def (could be livein) and this
536   // instruction, then bail.
537   unsigned LastDefC = 0;
538   if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
539     return false;
540 
541   // If there is a use of regB between its last def (could be livein) and this
542   // instruction, then go ahead and make this transformation.
543   unsigned LastDefB = 0;
544   if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
545     return true;
546 
547   // Since there are no intervening uses for both registers, then commute
548   // if the def of regC is closer. Its live interval is shorter.
549   return LastDefB && LastDefC && LastDefC > LastDefB;
550 }
551 
552 /// CommuteInstruction - Commute a two-address instruction and update the basic
553 /// block, distance map, and live variables if needed. Return true if it is
554 /// successful.
555 bool
556 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
557                                MachineFunction::iterator &mbbi,
558                                unsigned RegB, unsigned RegC, unsigned Dist) {
559   MachineInstr *MI = mi;
560   DOUT << "2addr: COMMUTING  : " << *MI;
561   MachineInstr *NewMI = TII->commuteInstruction(MI);
562 
563   if (NewMI == 0) {
564     DOUT << "2addr: COMMUTING FAILED!\n";
565     return false;
566   }
567 
568   DOUT << "2addr: COMMUTED TO: " << *NewMI;
569   // If the instruction changed to commute it, update livevar.
570   if (NewMI != MI) {
571     if (LV)
572       // Update live variables
573       LV->replaceKillInstruction(RegC, MI, NewMI);
574 
575     mbbi->insert(mi, NewMI);           // Insert the new inst
576     mbbi->erase(mi);                   // Nuke the old inst.
577     mi = NewMI;
578     DistanceMap.insert(std::make_pair(NewMI, Dist));
579   }
580 
581   // Update source register map.
582   unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
583   if (FromRegC) {
584     unsigned RegA = MI->getOperand(0).getReg();
585     SrcRegMap[RegA] = FromRegC;
586   }
587 
588   return true;
589 }
590 
591 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
592 /// given 2-address instruction to a 3-address one.
593 bool
594 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
595   // Look for situations like this:
596   // %reg1024<def> = MOV r1
597   // %reg1025<def> = MOV r0
598   // %reg1026<def> = ADD %reg1024, %reg1025
599   // r2            = MOV %reg1026
600   // Turn ADD into a 3-address instruction to avoid a copy.
601   unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
602   unsigned ToRegA = getMappedReg(RegA, DstRegMap);
603   return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
604 }
605 
606 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
607 /// three address one. Return true if this transformation was successful.
608 bool
609 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
610                                               MachineBasicBlock::iterator &nmi,
611                                               MachineFunction::iterator &mbbi,
612                                               unsigned RegB, unsigned Dist) {
613   MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
614   if (NewMI) {
615     DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
616     DOUT << "2addr:         TO 3-ADDR: " << *NewMI;
617     bool Sunk = false;
618 
619     if (NewMI->findRegisterUseOperand(RegB, false, TRI))
620       // FIXME: Temporary workaround. If the new instruction doesn't
621       // uses RegB, convertToThreeAddress must have created more
622       // then one instruction.
623       Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
624 
625     mbbi->erase(mi); // Nuke the old inst.
626 
627     if (!Sunk) {
628       DistanceMap.insert(std::make_pair(NewMI, Dist));
629       mi = NewMI;
630       nmi = next(mi);
631     }
632     return true;
633   }
634 
635   return false;
636 }
637 
638 /// ProcessCopy - If the specified instruction is not yet processed, process it
639 /// if it's a copy. For a copy instruction, we find the physical registers the
640 /// source and destination registers might be mapped to. These are kept in
641 /// point-to maps used to determine future optimizations. e.g.
642 /// v1024 = mov r0
643 /// v1025 = mov r1
644 /// v1026 = add v1024, v1025
645 /// r1    = mov r1026
646 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
647 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
648 /// potentially joined with r1 on the output side. It's worthwhile to commute
649 /// 'add' to eliminate a copy.
650 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
651                                      MachineBasicBlock *MBB,
652                                      SmallPtrSet<MachineInstr*, 8> &Processed) {
653   if (Processed.count(MI))
654     return;
655 
656   bool IsSrcPhys, IsDstPhys;
657   unsigned SrcReg, DstReg;
658   if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
659     return;
660 
661   if (IsDstPhys && !IsSrcPhys)
662     DstRegMap.insert(std::make_pair(SrcReg, DstReg));
663   else if (!IsDstPhys && IsSrcPhys) {
664     bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
665     if (!isNew)
666       assert(SrcRegMap[DstReg] == SrcReg &&
667              "Can't map to two src physical registers!");
668 
669     SmallVector<unsigned, 4> VirtRegPairs;
670     bool IsCopy = false;
671     unsigned NewReg = 0;
672     while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
673                                                    IsCopy, NewReg, IsDstPhys)) {
674       if (IsCopy) {
675         if (!Processed.insert(UseMI))
676           break;
677       }
678 
679       DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
680       if (DI != DistanceMap.end())
681         // Earlier in the same MBB.Reached via a back edge.
682         break;
683 
684       if (IsDstPhys) {
685         VirtRegPairs.push_back(NewReg);
686         break;
687       }
688       bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
689       if (!isNew)
690         assert(SrcRegMap[NewReg] == DstReg &&
691                "Can't map to two src physical registers!");
692       VirtRegPairs.push_back(NewReg);
693       DstReg = NewReg;
694     }
695 
696     if (!VirtRegPairs.empty()) {
697       unsigned ToReg = VirtRegPairs.back();
698       VirtRegPairs.pop_back();
699       while (!VirtRegPairs.empty()) {
700         unsigned FromReg = VirtRegPairs.back();
701         VirtRegPairs.pop_back();
702         bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
703         if (!isNew)
704           assert(DstRegMap[FromReg] == ToReg &&
705                  "Can't map to two dst physical registers!");
706         ToReg = FromReg;
707       }
708     }
709   }
710 
711   Processed.insert(MI);
712 }
713 
714 /// isSafeToDelete - If the specified instruction does not produce any side
715 /// effects and all of its defs are dead, then it's safe to delete.
716 static bool isSafeToDelete(MachineInstr *MI, unsigned Reg,
717                            const TargetInstrInfo *TII,
718                            SmallVector<unsigned, 4> &Kills) {
719   const TargetInstrDesc &TID = MI->getDesc();
720   if (TID.mayStore() || TID.isCall())
721     return false;
722   if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
723     return false;
724 
725   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
726     MachineOperand &MO = MI->getOperand(i);
727     if (!MO.isReg())
728       continue;
729     if (MO.isDef() && !MO.isDead())
730       return false;
731     if (MO.isUse() && MO.getReg() != Reg && MO.isKill())
732       Kills.push_back(MO.getReg());
733   }
734 
735   return true;
736 }
737 
738 /// runOnMachineFunction - Reduce two-address instructions to two operands.
739 ///
740 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
741   DOUT << "Machine Function\n";
742   const TargetMachine &TM = MF.getTarget();
743   MRI = &MF.getRegInfo();
744   TII = TM.getInstrInfo();
745   TRI = TM.getRegisterInfo();
746   LV = getAnalysisIfAvailable<LiveVariables>();
747 
748   bool MadeChange = false;
749 
750   DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
751   DEBUG(errs() << "********** Function: "
752         << MF.getFunction()->getName() << '\n');
753 
754   // ReMatRegs - Keep track of the registers whose def's are remat'ed.
755   BitVector ReMatRegs;
756   ReMatRegs.resize(MRI->getLastVirtReg()+1);
757 
758   SmallPtrSet<MachineInstr*, 8> Processed;
759   for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
760        mbbi != mbbe; ++mbbi) {
761     unsigned Dist = 0;
762     DistanceMap.clear();
763     SrcRegMap.clear();
764     DstRegMap.clear();
765     Processed.clear();
766     for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
767          mi != me; ) {
768       MachineBasicBlock::iterator nmi = next(mi);
769       const TargetInstrDesc &TID = mi->getDesc();
770       bool FirstTied = true;
771 
772       DistanceMap.insert(std::make_pair(mi, ++Dist));
773 
774       ProcessCopy(&*mi, &*mbbi, Processed);
775 
776       unsigned NumOps = (mi->getOpcode() == TargetInstrInfo::INLINEASM)
777         ? mi->getNumOperands() : TID.getNumOperands();
778       for (unsigned si = 0; si < NumOps; ++si) {
779         unsigned ti = 0;
780         if (!mi->isRegTiedToDefOperand(si, &ti))
781           continue;
782 
783         if (FirstTied) {
784           ++NumTwoAddressInstrs;
785           DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
786         }
787 
788         FirstTied = false;
789 
790         assert(mi->getOperand(si).isReg() && mi->getOperand(si).getReg() &&
791                mi->getOperand(si).isUse() && "two address instruction invalid");
792 
793         // If the two operands are the same we just remove the use
794         // and mark the def as def&use, otherwise we have to insert a copy.
795         if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
796           // Rewrite:
797           //     a = b op c
798           // to:
799           //     a = b
800           //     a = a op c
801           unsigned regA = mi->getOperand(ti).getReg();
802           unsigned regB = mi->getOperand(si).getReg();
803           unsigned regASubIdx = mi->getOperand(ti).getSubReg();
804 
805           assert(TargetRegisterInfo::isVirtualRegister(regB) &&
806                  "cannot update physical register live information");
807 
808 #ifndef NDEBUG
809           // First, verify that we don't have a use of a in the instruction (a =
810           // b + a for example) because our transformation will not work. This
811           // should never occur because we are in SSA form.
812           for (unsigned i = 0; i != mi->getNumOperands(); ++i)
813             assert(i == ti ||
814                    !mi->getOperand(i).isReg() ||
815                    mi->getOperand(i).getReg() != regA);
816 #endif
817 
818           // If this instruction is not the killing user of B, see if we can
819           // rearrange the code to make it so.  Making it the killing user will
820           // allow us to coalesce A and B together, eliminating the copy we are
821           // about to insert.
822           if (!isKilled(*mi, regB, MRI, TII)) {
823             // If regA is dead and the instruction can be deleted, just delete
824             // it so it doesn't clobber regB.
825             SmallVector<unsigned, 4> Kills;
826             if (mi->getOperand(ti).isDead() &&
827                 isSafeToDelete(mi, regB, TII, Kills)) {
828               SmallVector<std::pair<std::pair<unsigned, bool>
829                 ,MachineInstr*>, 4> NewKills;
830               bool ReallySafe = true;
831               // If this instruction kills some virtual registers, we need
832               // update the kill information. If it's not possible to do so,
833               // then bail out.
834               while (!Kills.empty()) {
835                 unsigned Kill = Kills.back();
836                 Kills.pop_back();
837                 if (TargetRegisterInfo::isPhysicalRegister(Kill)) {
838                   ReallySafe = false;
839                   break;
840                 }
841                 MachineInstr *LastKill = FindLastUseInMBB(Kill, &*mbbi, Dist);
842                 if (LastKill) {
843                   bool isModRef = LastKill->modifiesRegister(Kill);
844                   NewKills.push_back(std::make_pair(std::make_pair(Kill,isModRef),
845                                                     LastKill));
846                 } else {
847                   ReallySafe = false;
848                   break;
849                 }
850               }
851 
852               if (ReallySafe) {
853                 if (LV) {
854                   while (!NewKills.empty()) {
855                     MachineInstr *NewKill = NewKills.back().second;
856                     unsigned Kill = NewKills.back().first.first;
857                     bool isDead = NewKills.back().first.second;
858                     NewKills.pop_back();
859                     if (LV->removeVirtualRegisterKilled(Kill,  mi)) {
860                       if (isDead)
861                         LV->addVirtualRegisterDead(Kill, NewKill);
862                       else
863                         LV->addVirtualRegisterKilled(Kill, NewKill);
864                     }
865                   }
866                 }
867 
868                 // We're really going to nuke the old inst. If regB was marked
869                 // as a kill we need to update its Kills list.
870                 if (mi->getOperand(si).isKill())
871                   LV->removeVirtualRegisterKilled(regB, mi);
872 
873                 mbbi->erase(mi); // Nuke the old inst.
874                 mi = nmi;
875                 ++NumDeletes;
876                 break; // Done with this instruction.
877               }
878             }
879 
880             // If this instruction is commutative, check to see if C dies.  If
881             // so, swap the B and C operands.  This makes the live ranges of A
882             // and C joinable.
883             // FIXME: This code also works for A := B op C instructions.
884             unsigned SrcOp1, SrcOp2;
885             if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
886                 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
887               unsigned regC = 0;
888               if (si == SrcOp1)
889                 regC = mi->getOperand(SrcOp2).getReg();
890               else if (si == SrcOp2)
891                 regC = mi->getOperand(SrcOp1).getReg();
892               if (isKilled(*mi, regC, MRI, TII)) {
893                 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
894                   ++NumCommuted;
895                   regB = regC;
896                   goto InstructionRearranged;
897                 }
898               }
899             }
900 
901             // If this instruction is potentially convertible to a true
902             // three-address instruction,
903             if (TID.isConvertibleTo3Addr()) {
904               // FIXME: This assumes there are no more operands which are tied
905               // to another register.
906 #ifndef NDEBUG
907               for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
908                 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
909 #endif
910 
911               if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
912                 ++NumConvertedTo3Addr;
913                 break; // Done with this instruction.
914               }
915             }
916           }
917 
918           // If it's profitable to commute the instruction, do so.
919           unsigned SrcOp1, SrcOp2;
920           if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
921               TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
922             unsigned regC = 0;
923             if (si == SrcOp1)
924               regC = mi->getOperand(SrcOp2).getReg();
925             else if (si == SrcOp2)
926               regC = mi->getOperand(SrcOp1).getReg();
927 
928             if (regC && isProfitableToCommute(regB, regC, mi, mbbi, Dist))
929               if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
930                 ++NumAggrCommuted;
931                 ++NumCommuted;
932                 regB = regC;
933                 goto InstructionRearranged;
934               }
935           }
936 
937           // If it's profitable to convert the 2-address instruction to a
938           // 3-address one, do so.
939           if (TID.isConvertibleTo3Addr() && isProfitableToConv3Addr(regA)) {
940             if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
941               ++NumConvertedTo3Addr;
942               break; // Done with this instruction.
943             }
944           }
945 
946         InstructionRearranged:
947           const TargetRegisterClass* rc = MRI->getRegClass(regB);
948           MachineInstr *DefMI = MRI->getVRegDef(regB);
949           // If it's safe and profitable, remat the definition instead of
950           // copying it.
951           if (DefMI &&
952               DefMI->getDesc().isAsCheapAsAMove() &&
953               DefMI->isSafeToReMat(TII, regB) &&
954               isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
955             DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
956             TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI);
957             ReMatRegs.set(regB);
958             ++NumReMats;
959           } else {
960             bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
961             (void)Emitted;
962             assert(Emitted && "Unable to issue a copy instruction!\n");
963           }
964 
965           MachineBasicBlock::iterator prevMI = prior(mi);
966           // Update DistanceMap.
967           DistanceMap.insert(std::make_pair(prevMI, Dist));
968           DistanceMap[mi] = ++Dist;
969 
970           // Update live variables for regB.
971           if (LV) {
972             if (LV->removeVirtualRegisterKilled(regB,  mi))
973               LV->addVirtualRegisterKilled(regB, prevMI);
974 
975             if (LV->removeVirtualRegisterDead(regB, mi))
976               LV->addVirtualRegisterDead(regB, prevMI);
977           }
978 
979           DOUT << "\t\tprepend:\t"; DEBUG(prevMI->print(*cerr.stream(), &TM));
980 
981           // Replace all occurences of regB with regA.
982           for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
983             if (mi->getOperand(i).isReg() &&
984                 mi->getOperand(i).getReg() == regB)
985               mi->getOperand(i).setReg(regA);
986           }
987         }
988 
989         assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
990         mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
991         MadeChange = true;
992 
993         DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
994       }
995 
996       mi = nmi;
997     }
998   }
999 
1000   // Some remat'ed instructions are dead.
1001   int VReg = ReMatRegs.find_first();
1002   while (VReg != -1) {
1003     if (MRI->use_empty(VReg)) {
1004       MachineInstr *DefMI = MRI->getVRegDef(VReg);
1005       DefMI->eraseFromParent();
1006     }
1007     VReg = ReMatRegs.find_next(VReg);
1008   }
1009 
1010   return MadeChange;
1011 }
1012