blob: b50d53ce59bc28e0feea533bd85fa2da24be161c [file] [log] [blame]
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001//===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00007//
8//===----------------------------------------------------------------------===//
9//
Alkis Evlogimenos50c047d2004-01-04 23:09:24 +000010// 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
Alkis Evlogimenos14be6402004-02-04 22:17:40 +000019// A op= C
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000020//
Alkis Evlogimenos14be6402004-02-04 22:17:40 +000021// 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.
Chris Lattnerbd91c1c2004-01-31 21:07:15 +000027//
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000028//===----------------------------------------------------------------------===//
29
30#define DEBUG_TYPE "twoaddrinstr"
Chris Lattnerbd91c1c2004-01-31 21:07:15 +000031#include "llvm/CodeGen/Passes.h"
Chris Lattner1e313632004-07-21 23:17:57 +000032#include "llvm/Function.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000033#include "llvm/CodeGen/LiveVariables.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
35#include "llvm/CodeGen/MachineInstr.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000037#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000038#include "llvm/Target/TargetInstrInfo.h"
39#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000040#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000041#include "llvm/Support/Compiler.h"
Evan Cheng875357d2008-03-13 06:37:55 +000042#include "llvm/Support/Debug.h"
Evan Cheng7543e582008-06-18 07:49:14 +000043#include "llvm/ADT/BitVector.h"
44#include "llvm/ADT/DenseMap.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000045#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000046#include "llvm/ADT/Statistic.h"
47#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000048using namespace llvm;
49
Chris Lattnercd3245a2006-12-19 22:41:21 +000050STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
51STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengd498c8f2009-01-25 03:53:59 +000052STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattnercd3245a2006-12-19 22:41:21 +000053STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng875357d2008-03-13 06:37:55 +000054STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng7543e582008-06-18 07:49:14 +000055STATISTIC(NumReMats, "Number of instructions re-materialized");
Evan Cheng28c7ce32009-02-21 03:14:25 +000056STATISTIC(NumDeletes, "Number of dead instructions deleted");
Evan Cheng875357d2008-03-13 06:37:55 +000057
58namespace {
Bill Wendling637980e2008-05-10 00:12:52 +000059 class VISIBILITY_HIDDEN TwoAddressInstructionPass
60 : public MachineFunctionPass {
Evan Cheng875357d2008-03-13 06:37:55 +000061 const TargetInstrInfo *TII;
62 const TargetRegisterInfo *TRI;
63 MachineRegisterInfo *MRI;
64 LiveVariables *LV;
65
Evan Cheng870b8072009-03-01 02:03:43 +000066 // 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
Bill Wendling637980e2008-05-10 00:12:52 +000080 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
81 unsigned Reg,
82 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000083
Evan Cheng7543e582008-06-18 07:49:14 +000084 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
Evan Cheng601ca4b2008-06-25 01:16:38 +000085 MachineInstr *MI, MachineInstr *DefMI,
Evan Cheng870b8072009-03-01 02:03:43 +000086 MachineBasicBlock *MBB, unsigned Loc);
Evan Cheng81913712009-01-23 23:27:33 +000087
Evan Chengd498c8f2009-01-25 03:53:59 +000088 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
Evan Chengd498c8f2009-01-25 03:53:59 +000089 unsigned &LastDef);
90
Evan Chenge9ccb3a2009-04-28 02:12:36 +000091 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
92 unsigned Dist);
93
Evan Chengd498c8f2009-01-25 03:53:59 +000094 bool isProfitableToCommute(unsigned regB, unsigned regC,
95 MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng870b8072009-03-01 02:03:43 +000096 unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +000097
Evan Cheng81913712009-01-23 23:27:33 +000098 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
99 MachineFunction::iterator &mbbi,
Evan Cheng870b8072009-03-01 02:03:43 +0000100 unsigned RegB, unsigned RegC, unsigned Dist);
101
Evan Chenge6f350d2009-03-30 21:34:07 +0000102 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
Bob Wilson326f4382009-09-01 22:51:08 +0000109 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
110 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
111 SmallVector<NewKill, 4> &NewKills,
112 MachineBasicBlock *MBB, unsigned Dist);
113 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
114 MachineBasicBlock::iterator &nmi,
115 MachineFunction::iterator &mbbi,
116 unsigned regB, unsigned regBIdx, unsigned Dist);
117
Evan Cheng870b8072009-03-01 02:03:43 +0000118 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
119 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000120
Evan Cheng875357d2008-03-13 06:37:55 +0000121 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000122 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000123 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000124
Bill Wendling637980e2008-05-10 00:12:52 +0000125 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000126 AU.setPreservesCFG();
Bill Wendling637980e2008-05-10 00:12:52 +0000127 AU.addPreserved<LiveVariables>();
128 AU.addPreservedID(MachineLoopInfoID);
129 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +0000130 if (StrongPHIElim)
131 AU.addPreservedID(StrongPHIEliminationID);
132 else
133 AU.addPreservedID(PHIEliminationID);
Bill Wendling637980e2008-05-10 00:12:52 +0000134 MachineFunctionPass::getAnalysisUsage(AU);
135 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000136
Bill Wendling637980e2008-05-10 00:12:52 +0000137 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000138 bool runOnMachineFunction(MachineFunction&);
139 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000140}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000141
Dan Gohman844731a2008-05-13 00:00:25 +0000142char TwoAddressInstructionPass::ID = 0;
143static RegisterPass<TwoAddressInstructionPass>
144X("twoaddressinstruction", "Two-Address instruction pass");
145
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000146const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000147
Evan Cheng875357d2008-03-13 06:37:55 +0000148/// Sink3AddrInstruction - A two-address instruction has been converted to a
149/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000150/// past the instruction that would kill the above mentioned register to reduce
151/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000152bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
153 MachineInstr *MI, unsigned SavedReg,
154 MachineBasicBlock::iterator OldPos) {
155 // Check if it's safe to move this instruction.
156 bool SeenStore = true; // Be conservative.
157 if (!MI->isSafeToMove(TII, SeenStore))
158 return false;
159
160 unsigned DefReg = 0;
161 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000162
Evan Cheng875357d2008-03-13 06:37:55 +0000163 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
164 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000165 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000166 continue;
167 unsigned MOReg = MO.getReg();
168 if (!MOReg)
169 continue;
170 if (MO.isUse() && MOReg != SavedReg)
171 UseRegs.insert(MO.getReg());
172 if (!MO.isDef())
173 continue;
174 if (MO.isImplicit())
175 // Don't try to move it if it implicitly defines a register.
176 return false;
177 if (DefReg)
178 // For now, don't move any instructions that define multiple registers.
179 return false;
180 DefReg = MO.getReg();
181 }
182
183 // Find the instruction that kills SavedReg.
184 MachineInstr *KillMI = NULL;
185 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
186 UE = MRI->use_end(); UI != UE; ++UI) {
187 MachineOperand &UseMO = UI.getOperand();
188 if (!UseMO.isKill())
189 continue;
190 KillMI = UseMO.getParent();
191 break;
192 }
Bill Wendling637980e2008-05-10 00:12:52 +0000193
Dan Gohman97121ba2009-04-08 00:15:30 +0000194 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
Evan Cheng875357d2008-03-13 06:37:55 +0000195 return false;
196
Bill Wendling637980e2008-05-10 00:12:52 +0000197 // If any of the definitions are used by another instruction between the
198 // position and the kill use, then it's not safe to sink it.
199 //
200 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000201 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000202 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000203 MachineOperand *KillMO = NULL;
204 MachineBasicBlock::iterator KillPos = KillMI;
205 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000206
Evan Cheng7543e582008-06-18 07:49:14 +0000207 unsigned NumVisited = 0;
Evan Cheng875357d2008-03-13 06:37:55 +0000208 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
209 MachineInstr *OtherMI = I;
Evan Cheng7543e582008-06-18 07:49:14 +0000210 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
211 return false;
212 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000213 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
214 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000215 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000216 continue;
217 unsigned MOReg = MO.getReg();
218 if (!MOReg)
219 continue;
220 if (DefReg == MOReg)
221 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000222
Evan Cheng875357d2008-03-13 06:37:55 +0000223 if (MO.isKill()) {
224 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000225 // Save the operand that kills the register. We want to unset the kill
226 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000227 KillMO = &MO;
228 else if (UseRegs.count(MOReg))
229 // One of the uses is killed before the destination.
230 return false;
231 }
232 }
233 }
234
Evan Cheng875357d2008-03-13 06:37:55 +0000235 // Update kill and LV information.
236 KillMO->setIsKill(false);
237 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
238 KillMO->setIsKill(true);
Owen Anderson802af112008-07-02 21:28:58 +0000239
Evan Cheng9f1c8312008-07-03 09:09:37 +0000240 if (LV)
241 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000242
243 // Move instruction to its destination.
244 MBB->remove(MI);
245 MBB->insert(KillPos, MI);
246
247 ++Num3AddrSunk;
248 return true;
249}
250
Evan Cheng7543e582008-06-18 07:49:14 +0000251/// isTwoAddrUse - Return true if the specified MI is using the specified
252/// register as a two-address operand.
253static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
254 const TargetInstrDesc &TID = UseMI->getDesc();
255 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
256 MachineOperand &MO = UseMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000257 if (MO.isReg() && MO.getReg() == Reg &&
Evan Chenga24752f2009-03-19 20:30:06 +0000258 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
Evan Cheng7543e582008-06-18 07:49:14 +0000259 // Earlier use is a two-address one.
260 return true;
261 }
262 return false;
263}
264
265/// isProfitableToReMat - Return true if the heuristics determines it is likely
266/// to be profitable to re-materialize the definition of Reg rather than copy
267/// the register.
268bool
269TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000270 const TargetRegisterClass *RC,
271 MachineInstr *MI, MachineInstr *DefMI,
272 MachineBasicBlock *MBB, unsigned Loc) {
Evan Cheng7543e582008-06-18 07:49:14 +0000273 bool OtherUse = false;
274 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
275 UE = MRI->use_end(); UI != UE; ++UI) {
276 MachineOperand &UseMO = UI.getOperand();
Evan Cheng7543e582008-06-18 07:49:14 +0000277 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng601ca4b2008-06-25 01:16:38 +0000278 MachineBasicBlock *UseMBB = UseMI->getParent();
279 if (UseMBB == MBB) {
280 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
281 if (DI != DistanceMap.end() && DI->second == Loc)
282 continue; // Current use.
283 OtherUse = true;
284 // There is at least one other use in the MBB that will clobber the
285 // register.
286 if (isTwoAddrUse(UseMI, Reg))
287 return true;
288 }
Evan Cheng7543e582008-06-18 07:49:14 +0000289 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000290
291 // If other uses in MBB are not two-address uses, then don't remat.
292 if (OtherUse)
293 return false;
294
295 // No other uses in the same block, remat if it's defined in the same
296 // block so it does not unnecessarily extend the live range.
297 return MBB == DefMI->getParent();
Evan Cheng7543e582008-06-18 07:49:14 +0000298}
299
Evan Chengd498c8f2009-01-25 03:53:59 +0000300/// NoUseAfterLastDef - Return true if there are no intervening uses between the
301/// last instruction in the MBB that defines the specified register and the
302/// two-address instruction which is being processed. It also returns the last
303/// def location by reference
304bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000305 MachineBasicBlock *MBB, unsigned Dist,
306 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000307 LastDef = 0;
308 unsigned LastUse = Dist;
309 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
310 E = MRI->reg_end(); I != E; ++I) {
311 MachineOperand &MO = I.getOperand();
312 MachineInstr *MI = MO.getParent();
313 if (MI->getParent() != MBB)
314 continue;
315 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
316 if (DI == DistanceMap.end())
317 continue;
318 if (MO.isUse() && DI->second < LastUse)
319 LastUse = DI->second;
320 if (MO.isDef() && DI->second > LastDef)
321 LastDef = DI->second;
322 }
323
324 return !(LastUse > LastDef && LastUse < Dist);
325}
326
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000327MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
328 MachineBasicBlock *MBB,
329 unsigned Dist) {
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000330 unsigned LastUseDist = 0;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000331 MachineInstr *LastUse = 0;
332 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
333 E = MRI->reg_end(); I != E; ++I) {
334 MachineOperand &MO = I.getOperand();
335 MachineInstr *MI = MO.getParent();
336 if (MI->getParent() != MBB)
337 continue;
338 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
339 if (DI == DistanceMap.end())
340 continue;
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000341 if (DI->second >= Dist)
342 continue;
343
344 if (MO.isUse() && DI->second > LastUseDist) {
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000345 LastUse = DI->first;
346 LastUseDist = DI->second;
347 }
348 }
349 return LastUse;
350}
351
Evan Cheng870b8072009-03-01 02:03:43 +0000352/// isCopyToReg - Return true if the specified MI is a copy instruction or
353/// a extract_subreg instruction. It also returns the source and destination
354/// registers and whether they are physical registers by reference.
355static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
356 unsigned &SrcReg, unsigned &DstReg,
357 bool &IsSrcPhys, bool &IsDstPhys) {
358 SrcReg = 0;
359 DstReg = 0;
360 unsigned SrcSubIdx, DstSubIdx;
361 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
362 if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
363 DstReg = MI.getOperand(0).getReg();
364 SrcReg = MI.getOperand(1).getReg();
365 } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
366 DstReg = MI.getOperand(0).getReg();
367 SrcReg = MI.getOperand(2).getReg();
Dan Gohman97121ba2009-04-08 00:15:30 +0000368 } else if (MI.getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
369 DstReg = MI.getOperand(0).getReg();
370 SrcReg = MI.getOperand(2).getReg();
Evan Cheng870b8072009-03-01 02:03:43 +0000371 }
372 }
373
374 if (DstReg) {
375 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
376 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
377 return true;
378 }
379 return false;
380}
381
Dan Gohman97121ba2009-04-08 00:15:30 +0000382/// isKilled - Test if the given register value, which is used by the given
383/// instruction, is killed by the given instruction. This looks through
384/// coalescable copies to see if the original value is potentially not killed.
385///
386/// For example, in this code:
387///
388/// %reg1034 = copy %reg1024
389/// %reg1035 = copy %reg1025<kill>
390/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
391///
392/// %reg1034 is not considered to be killed, since it is copied from a
393/// register which is not killed. Treating it as not killed lets the
394/// normal heuristics commute the (two-address) add, which lets
395/// coalescing eliminate the extra copy.
396///
397static bool isKilled(MachineInstr &MI, unsigned Reg,
398 const MachineRegisterInfo *MRI,
399 const TargetInstrInfo *TII) {
400 MachineInstr *DefMI = &MI;
401 for (;;) {
402 if (!DefMI->killsRegister(Reg))
403 return false;
404 if (TargetRegisterInfo::isPhysicalRegister(Reg))
405 return true;
406 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
407 // If there are multiple defs, we can't do a simple analysis, so just
408 // go with what the kill flag says.
409 if (next(Begin) != MRI->def_end())
410 return true;
411 DefMI = &*Begin;
412 bool IsSrcPhys, IsDstPhys;
413 unsigned SrcReg, DstReg;
414 // If the def is something other than a copy, then it isn't going to
415 // be coalesced, so follow the kill flag.
416 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
417 return true;
418 Reg = SrcReg;
419 }
420}
421
Evan Cheng870b8072009-03-01 02:03:43 +0000422/// isTwoAddrUse - Return true if the specified MI uses the specified register
423/// as a two-address use. If so, return the destination register by reference.
424static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
425 const TargetInstrDesc &TID = MI.getDesc();
Evan Chenge6f350d2009-03-30 21:34:07 +0000426 unsigned NumOps = (MI.getOpcode() == TargetInstrInfo::INLINEASM)
427 ? MI.getNumOperands() : TID.getNumOperands();
428 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000429 const MachineOperand &MO = MI.getOperand(i);
430 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
431 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000432 unsigned ti;
433 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000434 DstReg = MI.getOperand(ti).getReg();
435 return true;
436 }
437 }
438 return false;
439}
440
441/// findOnlyInterestingUse - Given a register, if has a single in-basic block
442/// use, return the use instruction if it's a copy or a two-address use.
443static
444MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
445 MachineRegisterInfo *MRI,
446 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000447 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000448 unsigned &DstReg, bool &IsDstPhys) {
449 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
450 if (UI == MRI->use_end())
451 return 0;
452 MachineInstr &UseMI = *UI;
453 if (++UI != MRI->use_end())
454 // More than one use.
455 return 0;
456 if (UseMI.getParent() != MBB)
457 return 0;
458 unsigned SrcReg;
459 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000460 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
461 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000462 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000463 }
Evan Cheng870b8072009-03-01 02:03:43 +0000464 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000465 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
466 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000467 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000468 }
Evan Cheng870b8072009-03-01 02:03:43 +0000469 return 0;
470}
471
472/// getMappedReg - Return the physical register the specified virtual register
473/// might be mapped to.
474static unsigned
475getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
476 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
477 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
478 if (SI == RegMap.end())
479 return 0;
480 Reg = SI->second;
481 }
482 if (TargetRegisterInfo::isPhysicalRegister(Reg))
483 return Reg;
484 return 0;
485}
486
487/// regsAreCompatible - Return true if the two registers are equal or aliased.
488///
489static bool
490regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
491 if (RegA == RegB)
492 return true;
493 if (!RegA || !RegB)
494 return false;
495 return TRI->regsOverlap(RegA, RegB);
496}
497
498
Evan Chengd498c8f2009-01-25 03:53:59 +0000499/// isProfitableToReMat - Return true if it's potentially profitable to commute
500/// the two-address instruction that's being processed.
501bool
502TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000503 MachineInstr *MI, MachineBasicBlock *MBB,
504 unsigned Dist) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000505 // Determine if it's profitable to commute this two address instruction. In
506 // general, we want no uses between this instruction and the definition of
507 // the two-address register.
508 // e.g.
509 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
510 // %reg1029<def> = MOV8rr %reg1028
511 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
512 // insert => %reg1030<def> = MOV8rr %reg1028
513 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
514 // In this case, it might not be possible to coalesce the second MOV8rr
515 // instruction if the first one is coalesced. So it would be profitable to
516 // commute it:
517 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
518 // %reg1029<def> = MOV8rr %reg1028
519 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
520 // insert => %reg1030<def> = MOV8rr %reg1029
521 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
522
523 if (!MI->killsRegister(regC))
524 return false;
525
526 // Ok, we have something like:
527 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
528 // let's see if it's worth commuting it.
529
Evan Cheng870b8072009-03-01 02:03:43 +0000530 // Look for situations like this:
531 // %reg1024<def> = MOV r1
532 // %reg1025<def> = MOV r0
533 // %reg1026<def> = ADD %reg1024, %reg1025
534 // r0 = MOV %reg1026
535 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
536 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
537 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
538 unsigned ToRegB = getMappedReg(regB, DstRegMap);
539 unsigned ToRegC = getMappedReg(regC, DstRegMap);
540 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
541 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
542 regsAreCompatible(FromRegC, ToRegB, TRI)))
543 return true;
544
Evan Chengd498c8f2009-01-25 03:53:59 +0000545 // If there is a use of regC between its last def (could be livein) and this
546 // instruction, then bail.
547 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000548 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000549 return false;
550
551 // If there is a use of regB between its last def (could be livein) and this
552 // instruction, then go ahead and make this transformation.
553 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000554 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000555 return true;
556
557 // Since there are no intervening uses for both registers, then commute
558 // if the def of regC is closer. Its live interval is shorter.
559 return LastDefB && LastDefC && LastDefC > LastDefB;
560}
561
Evan Cheng81913712009-01-23 23:27:33 +0000562/// CommuteInstruction - Commute a two-address instruction and update the basic
563/// block, distance map, and live variables if needed. Return true if it is
564/// successful.
565bool
566TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000567 MachineFunction::iterator &mbbi,
568 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000569 MachineInstr *MI = mi;
Chris Lattner6456d382009-08-23 03:20:44 +0000570 DEBUG(errs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000571 MachineInstr *NewMI = TII->commuteInstruction(MI);
572
573 if (NewMI == 0) {
Chris Lattner6456d382009-08-23 03:20:44 +0000574 DEBUG(errs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000575 return false;
576 }
577
Chris Lattner6456d382009-08-23 03:20:44 +0000578 DEBUG(errs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000579 // If the instruction changed to commute it, update livevar.
580 if (NewMI != MI) {
581 if (LV)
582 // Update live variables
583 LV->replaceKillInstruction(RegC, MI, NewMI);
584
585 mbbi->insert(mi, NewMI); // Insert the new inst
586 mbbi->erase(mi); // Nuke the old inst.
587 mi = NewMI;
588 DistanceMap.insert(std::make_pair(NewMI, Dist));
589 }
Evan Cheng870b8072009-03-01 02:03:43 +0000590
591 // Update source register map.
592 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
593 if (FromRegC) {
594 unsigned RegA = MI->getOperand(0).getReg();
595 SrcRegMap[RegA] = FromRegC;
596 }
597
Evan Cheng81913712009-01-23 23:27:33 +0000598 return true;
599}
600
Evan Chenge6f350d2009-03-30 21:34:07 +0000601/// isProfitableToConv3Addr - Return true if it is profitable to convert the
602/// given 2-address instruction to a 3-address one.
603bool
604TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
605 // Look for situations like this:
606 // %reg1024<def> = MOV r1
607 // %reg1025<def> = MOV r0
608 // %reg1026<def> = ADD %reg1024, %reg1025
609 // r2 = MOV %reg1026
610 // Turn ADD into a 3-address instruction to avoid a copy.
611 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
612 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
613 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
614}
615
616/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
617/// three address one. Return true if this transformation was successful.
618bool
619TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
620 MachineBasicBlock::iterator &nmi,
621 MachineFunction::iterator &mbbi,
622 unsigned RegB, unsigned Dist) {
623 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
624 if (NewMI) {
Chris Lattner6456d382009-08-23 03:20:44 +0000625 DEBUG(errs() << "2addr: CONVERTING 2-ADDR: " << *mi);
626 DEBUG(errs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000627 bool Sunk = false;
628
629 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
630 // FIXME: Temporary workaround. If the new instruction doesn't
631 // uses RegB, convertToThreeAddress must have created more
632 // then one instruction.
633 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
634
635 mbbi->erase(mi); // Nuke the old inst.
636
637 if (!Sunk) {
638 DistanceMap.insert(std::make_pair(NewMI, Dist));
639 mi = NewMI;
640 nmi = next(mi);
641 }
642 return true;
643 }
644
645 return false;
646}
647
Evan Cheng870b8072009-03-01 02:03:43 +0000648/// ProcessCopy - If the specified instruction is not yet processed, process it
649/// if it's a copy. For a copy instruction, we find the physical registers the
650/// source and destination registers might be mapped to. These are kept in
651/// point-to maps used to determine future optimizations. e.g.
652/// v1024 = mov r0
653/// v1025 = mov r1
654/// v1026 = add v1024, v1025
655/// r1 = mov r1026
656/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
657/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
658/// potentially joined with r1 on the output side. It's worthwhile to commute
659/// 'add' to eliminate a copy.
660void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
661 MachineBasicBlock *MBB,
662 SmallPtrSet<MachineInstr*, 8> &Processed) {
663 if (Processed.count(MI))
664 return;
665
666 bool IsSrcPhys, IsDstPhys;
667 unsigned SrcReg, DstReg;
668 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
669 return;
670
671 if (IsDstPhys && !IsSrcPhys)
672 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
673 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000674 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
675 if (!isNew)
676 assert(SrcRegMap[DstReg] == SrcReg &&
677 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000678
679 SmallVector<unsigned, 4> VirtRegPairs;
Evan Cheng87d696a2009-04-14 00:32:25 +0000680 bool IsCopy = false;
Evan Cheng870b8072009-03-01 02:03:43 +0000681 unsigned NewReg = 0;
682 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000683 IsCopy, NewReg, IsDstPhys)) {
684 if (IsCopy) {
685 if (!Processed.insert(UseMI))
Evan Cheng870b8072009-03-01 02:03:43 +0000686 break;
687 }
688
689 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
690 if (DI != DistanceMap.end())
691 // Earlier in the same MBB.Reached via a back edge.
692 break;
693
694 if (IsDstPhys) {
695 VirtRegPairs.push_back(NewReg);
696 break;
697 }
698 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000699 if (!isNew)
Evan Cheng87d696a2009-04-14 00:32:25 +0000700 assert(SrcRegMap[NewReg] == DstReg &&
701 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000702 VirtRegPairs.push_back(NewReg);
703 DstReg = NewReg;
704 }
705
706 if (!VirtRegPairs.empty()) {
707 unsigned ToReg = VirtRegPairs.back();
708 VirtRegPairs.pop_back();
709 while (!VirtRegPairs.empty()) {
710 unsigned FromReg = VirtRegPairs.back();
711 VirtRegPairs.pop_back();
712 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000713 if (!isNew)
714 assert(DstRegMap[FromReg] == ToReg &&
715 "Can't map to two dst physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000716 ToReg = FromReg;
717 }
718 }
719 }
720
721 Processed.insert(MI);
722}
723
Evan Cheng28c7ce32009-02-21 03:14:25 +0000724/// isSafeToDelete - If the specified instruction does not produce any side
725/// effects and all of its defs are dead, then it's safe to delete.
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000726static bool isSafeToDelete(MachineInstr *MI, unsigned Reg,
727 const TargetInstrInfo *TII,
728 SmallVector<unsigned, 4> &Kills) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000729 const TargetInstrDesc &TID = MI->getDesc();
730 if (TID.mayStore() || TID.isCall())
731 return false;
732 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
733 return false;
734
735 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
736 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000737 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000738 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000739 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000740 return false;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000741 if (MO.isUse() && MO.getReg() != Reg && MO.isKill())
742 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000743 }
744
745 return true;
746}
747
Bob Wilson326f4382009-09-01 22:51:08 +0000748/// canUpdateDeletedKills - Check if all the registers listed in Kills are
749/// killed by instructions in MBB preceding the current instruction at
750/// position Dist. If so, return true and record information about the
751/// preceding kills in NewKills.
752bool TwoAddressInstructionPass::
753canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
754 SmallVector<NewKill, 4> &NewKills,
755 MachineBasicBlock *MBB, unsigned Dist) {
756 while (!Kills.empty()) {
757 unsigned Kill = Kills.back();
758 Kills.pop_back();
759 if (TargetRegisterInfo::isPhysicalRegister(Kill))
760 return false;
761
762 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
763 if (!LastKill)
764 return false;
765
766 bool isModRef = LastKill->modifiesRegister(Kill);
767 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
768 LastKill));
769 }
770 return true;
771}
772
773/// DeleteUnusedInstr - If an instruction with a tied register operand can
774/// be safely deleted, just delete it.
775bool
776TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
777 MachineBasicBlock::iterator &nmi,
778 MachineFunction::iterator &mbbi,
779 unsigned regB, unsigned regBIdx,
780 unsigned Dist) {
781 // Check if the instruction has no side effects and if all its defs are dead.
782 SmallVector<unsigned, 4> Kills;
783 if (!isSafeToDelete(mi, regB, TII, Kills))
784 return false;
785
786 // If this instruction kills some virtual registers, we need to
787 // update the kill information. If it's not possible to do so,
788 // then bail out.
789 SmallVector<NewKill, 4> NewKills;
790 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
791 return false;
792
793 if (LV) {
794 while (!NewKills.empty()) {
795 MachineInstr *NewKill = NewKills.back().second;
796 unsigned Kill = NewKills.back().first.first;
797 bool isDead = NewKills.back().first.second;
798 NewKills.pop_back();
799 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
800 if (isDead)
801 LV->addVirtualRegisterDead(Kill, NewKill);
802 else
803 LV->addVirtualRegisterKilled(Kill, NewKill);
804 }
805 }
806
807 // If regB was marked as a kill, update its Kills list.
808 if (mi->getOperand(regBIdx).isKill())
809 LV->removeVirtualRegisterKilled(regB, mi);
810 }
811
812 mbbi->erase(mi); // Nuke the old inst.
813 mi = nmi;
814 return true;
815}
816
Bill Wendling637980e2008-05-10 00:12:52 +0000817/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000818///
Chris Lattner163c1e72004-01-31 21:14:04 +0000819bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner6456d382009-08-23 03:20:44 +0000820 DEBUG(errs() << "Machine Function\n");
Misha Brukman75fa4e42004-07-22 15:26:23 +0000821 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +0000822 MRI = &MF.getRegInfo();
823 TII = TM.getInstrInfo();
824 TRI = TM.getRegisterInfo();
Duncan Sands1465d612009-01-28 13:14:17 +0000825 LV = getAnalysisIfAvailable<LiveVariables>();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000826
Misha Brukman75fa4e42004-07-22 15:26:23 +0000827 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000828
Chris Lattner6456d382009-08-23 03:20:44 +0000829 DEBUG(errs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000830 DEBUG(errs() << "********** Function: "
831 << MF.getFunction()->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +0000832
Evan Cheng7543e582008-06-18 07:49:14 +0000833 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
834 BitVector ReMatRegs;
835 ReMatRegs.resize(MRI->getLastVirtReg()+1);
836
Evan Cheng870b8072009-03-01 02:03:43 +0000837 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +0000838 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
839 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +0000840 unsigned Dist = 0;
841 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +0000842 SrcRegMap.clear();
843 DstRegMap.clear();
844 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +0000845 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +0000846 mi != me; ) {
847 MachineBasicBlock::iterator nmi = next(mi);
Chris Lattner749c6f62008-01-07 07:27:27 +0000848 const TargetInstrDesc &TID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +0000849 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +0000850
Evan Cheng7543e582008-06-18 07:49:14 +0000851 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +0000852
853 ProcessCopy(&*mi, &*mbbi, Processed);
854
Evan Chengfb112882009-03-23 08:01:15 +0000855 unsigned NumOps = (mi->getOpcode() == TargetInstrInfo::INLINEASM)
856 ? mi->getNumOperands() : TID.getNumOperands();
857 for (unsigned si = 0; si < NumOps; ++si) {
Evan Chenga24752f2009-03-19 20:30:06 +0000858 unsigned ti = 0;
859 if (!mi->isRegTiedToDefOperand(si, &ti))
Evan Cheng360c2dd2006-11-01 23:06:55 +0000860 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000861
Evan Cheng360c2dd2006-11-01 23:06:55 +0000862 if (FirstTied) {
863 ++NumTwoAddressInstrs;
Chris Lattner6456d382009-08-23 03:20:44 +0000864 DEBUG(errs() << '\t' << *mi);
Evan Cheng360c2dd2006-11-01 23:06:55 +0000865 }
Bill Wendling637980e2008-05-10 00:12:52 +0000866
Evan Cheng360c2dd2006-11-01 23:06:55 +0000867 FirstTied = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000868
Dan Gohmand735b802008-10-03 15:45:36 +0000869 assert(mi->getOperand(si).isReg() && mi->getOperand(si).getReg() &&
Evan Cheng360c2dd2006-11-01 23:06:55 +0000870 mi->getOperand(si).isUse() && "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000871
Bob Wilson43449792009-08-31 21:54:55 +0000872 // If the two operands are the same, nothing needs to be done.
873 if (mi->getOperand(ti).getReg() == mi->getOperand(si).getReg())
874 continue;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000875
Bob Wilson43449792009-08-31 21:54:55 +0000876 // Rewrite:
877 // a = b op c
878 // to:
879 // a = b
880 // a = a op c
881 unsigned regA = mi->getOperand(ti).getReg();
882 unsigned regB = mi->getOperand(si).getReg();
883 unsigned regASubIdx = mi->getOperand(ti).getSubReg();
884
885 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
886 "cannot make instruction into two-address form");
Chris Lattner6b507672004-01-31 21:21:43 +0000887
Chris Lattner1e313632004-07-21 23:17:57 +0000888#ifndef NDEBUG
Bob Wilson43449792009-08-31 21:54:55 +0000889 // First, verify that we don't have a use of a in the instruction (a =
890 // b + a for example) because our transformation will not work. This
891 // should never occur because we are in SSA form.
892 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
893 assert(i == ti ||
894 !mi->getOperand(i).isReg() ||
895 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +0000896#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +0000897
Bob Wilson43449792009-08-31 21:54:55 +0000898 // If this instruction is not the killing user of B, see if we can
899 // rearrange the code to make it so. Making it the killing user will
900 // allow us to coalesce A and B together, eliminating the copy we are
901 // about to insert.
902 if (!isKilled(*mi, regB, MRI, TII)) {
Bob Wilson326f4382009-09-01 22:51:08 +0000903
Bob Wilson43449792009-08-31 21:54:55 +0000904 // If regA is dead and the instruction can be deleted, just delete
905 // it so it doesn't clobber regB.
Bob Wilson43449792009-08-31 21:54:55 +0000906 if (mi->getOperand(ti).isDead() &&
Bob Wilson326f4382009-09-01 22:51:08 +0000907 DeleteUnusedInstr(mi, nmi, mbbi, regB, si, Dist)) {
908 ++NumDeletes;
909 break; // Done with this instruction.
Chris Lattnercfa0f2e2005-01-02 02:34:12 +0000910 }
Evan Cheng360c2dd2006-11-01 23:06:55 +0000911
Bob Wilson43449792009-08-31 21:54:55 +0000912 // If this instruction is commutative, check to see if C dies. If
913 // so, swap the B and C operands. This makes the live ranges of A
914 // and C joinable.
915 // FIXME: This code also works for A := B op C instructions.
Evan Chengebfc1772009-07-11 00:04:23 +0000916 unsigned SrcOp1, SrcOp2;
917 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
918 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
919 unsigned regC = 0;
920 if (si == SrcOp1)
921 regC = mi->getOperand(SrcOp2).getReg();
922 else if (si == SrcOp2)
923 regC = mi->getOperand(SrcOp1).getReg();
Bob Wilson43449792009-08-31 21:54:55 +0000924 if (isKilled(*mi, regC, MRI, TII)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000925 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000926 ++NumCommuted;
927 regB = regC;
Evan Chenge6f350d2009-03-30 21:34:07 +0000928 goto InstructionRearranged;
Evan Chengd498c8f2009-01-25 03:53:59 +0000929 }
Bob Wilson43449792009-08-31 21:54:55 +0000930 }
Evan Chengd498c8f2009-01-25 03:53:59 +0000931 }
932
Bob Wilson43449792009-08-31 21:54:55 +0000933 // If this instruction is potentially convertible to a true
934 // three-address instruction,
935 if (TID.isConvertibleTo3Addr()) {
936 // FIXME: This assumes there are no more operands which are tied
937 // to another register.
938#ifndef NDEBUG
939 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
940 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
941#endif
942
Evan Chenge6f350d2009-03-30 21:34:07 +0000943 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
944 ++NumConvertedTo3Addr;
945 break; // Done with this instruction.
946 }
947 }
Chris Lattnercfa0f2e2005-01-02 02:34:12 +0000948 }
Bob Wilson43449792009-08-31 21:54:55 +0000949
950 // If it's profitable to commute the instruction, do so.
951 unsigned SrcOp1, SrcOp2;
952 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
953 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
954 unsigned regC = 0;
955 if (si == SrcOp1)
956 regC = mi->getOperand(SrcOp2).getReg();
957 else if (si == SrcOp2)
958 regC = mi->getOperand(SrcOp1).getReg();
959
960 if (regC && isProfitableToCommute(regB, regC, mi, mbbi, Dist))
961 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
962 ++NumAggrCommuted;
963 ++NumCommuted;
964 regB = regC;
965 goto InstructionRearranged;
966 }
967 }
968
969 // If it's profitable to convert the 2-address instruction to a
970 // 3-address one, do so.
971 if (TID.isConvertibleTo3Addr() && isProfitableToConv3Addr(regA)) {
972 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
973 ++NumConvertedTo3Addr;
974 break; // Done with this instruction.
975 }
976 }
977
978 InstructionRearranged:
979 const TargetRegisterClass* rc = MRI->getRegClass(regB);
980 MachineInstr *DefMI = MRI->getVRegDef(regB);
981 // If it's safe and profitable, remat the definition instead of
982 // copying it.
983 if (DefMI &&
984 DefMI->getDesc().isAsCheapAsAMove() &&
985 DefMI->isSafeToReMat(TII, regB) &&
986 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
987 DEBUG(errs() << "2addr: REMATTING : " << *DefMI << "\n");
988 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI);
989 ReMatRegs.set(regB);
990 ++NumReMats;
991 } else {
992 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
993 (void)Emitted;
994 assert(Emitted && "Unable to issue a copy instruction!\n");
995 }
996
997 MachineBasicBlock::iterator prevMI = prior(mi);
998 // Update DistanceMap.
999 DistanceMap.insert(std::make_pair(prevMI, Dist));
1000 DistanceMap[mi] = ++Dist;
Bob Wilson71124f62009-09-01 04:18:40 +00001001
1002 // Scan the operands to find: (1) the use operand that kills regB (if
1003 // any); (2) whether the kill operand is being replaced by regA on
1004 // this iteration; and (3) the first use of regB that is not being
1005 // replaced on this iteration. A use of regB will not replaced if it
1006 // is tied to a different destination register and will be handled on
1007 // a later iteration.
1008 MachineOperand *KillMO = NULL;
1009 MachineOperand *FirstKeptMO = NULL;
1010 bool KillMOKept = false;
1011 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1012 MachineOperand &MO = mi->getOperand(i);
1013 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1014
1015 // Check if this operand is tied to a different destination.
1016 bool isKept = false;
1017 unsigned dsti = 0;
1018 if (mi->isRegTiedToDefOperand(i, &dsti) && dsti != ti) {
1019 isKept = true;
1020 if (!FirstKeptMO)
1021 FirstKeptMO = &MO;
1022 }
1023
1024 if (MO.isKill()) {
1025 KillMO = &MO;
1026 KillMOKept = isKept;
1027 }
1028 }
1029 }
Bob Wilson43449792009-08-31 21:54:55 +00001030
1031 // Update live variables for regB.
Bob Wilson71124f62009-09-01 04:18:40 +00001032 if (KillMO) {
1033 if (!FirstKeptMO) {
1034 // All uses of regB are being replaced; move the kill to prevMI.
1035 if (LV && LV->removeVirtualRegisterKilled(regB, mi))
1036 LV->addVirtualRegisterKilled(regB, prevMI);
1037 } else {
1038 if (!KillMOKept) {
1039 // The kill marker is on an operand being replaced, but there
1040 // are other uses of regB remaining. Move the kill marker to
1041 // one of them.
1042 KillMO->setIsKill(false);
1043 FirstKeptMO->setIsKill(true);
1044 }
1045 }
Bob Wilson43449792009-08-31 21:54:55 +00001046 }
1047
1048 DEBUG(errs() << "\t\tprepend:\t" << *prevMI);
Bob Wilson71124f62009-09-01 04:18:40 +00001049
1050 // Replace uses of regB with regA.
Bob Wilson43449792009-08-31 21:54:55 +00001051 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
Bob Wilson71124f62009-09-01 04:18:40 +00001052 MachineOperand &MO = mi->getOperand(i);
1053 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1054
1055 // Skip operands that are tied to other register definitions.
1056 unsigned dsti = 0;
1057 if (mi->isRegTiedToDefOperand(i, &dsti) && dsti != ti)
1058 continue;
1059
1060 MO.setReg(regA);
1061 }
Bob Wilson43449792009-08-31 21:54:55 +00001062 }
1063
1064 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
1065 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
1066 MadeChange = true;
1067
1068 DEBUG(errs() << "\t\trewrite to:\t" << *mi);
Misha Brukman75fa4e42004-07-22 15:26:23 +00001069 }
Bill Wendling637980e2008-05-10 00:12:52 +00001070
Evan Cheng7a963fa2008-03-27 01:27:25 +00001071 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001072 }
1073 }
1074
Evan Cheng601ca4b2008-06-25 01:16:38 +00001075 // Some remat'ed instructions are dead.
1076 int VReg = ReMatRegs.find_first();
1077 while (VReg != -1) {
1078 if (MRI->use_empty(VReg)) {
1079 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1080 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +00001081 }
Evan Cheng601ca4b2008-06-25 01:16:38 +00001082 VReg = ReMatRegs.find_next(VReg);
Bill Wendling48f7f232008-05-26 05:18:34 +00001083 }
1084
Misha Brukman75fa4e42004-07-22 15:26:23 +00001085 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001086}