blob: 6c7c1a1305e3f774fe316fc7f00b4f773c915020 [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 Gohmana70dca12009-10-09 23:27:56 +000037#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000038#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000039#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000041#include "llvm/Target/TargetOptions.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 {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000059 class TwoAddressInstructionPass : public MachineFunctionPass {
Evan Cheng875357d2008-03-13 06:37:55 +000060 const TargetInstrInfo *TII;
61 const TargetRegisterInfo *TRI;
62 MachineRegisterInfo *MRI;
63 LiveVariables *LV;
Dan Gohmana70dca12009-10-09 23:27:56 +000064 AliasAnalysis *AA;
Evan Cheng875357d2008-03-13 06:37:55 +000065
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,
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000115 MachineFunction::iterator &mbbi, unsigned Dist);
Bob Wilson326f4382009-09-01 22:51:08 +0000116
Bob Wilsoncc80df92009-09-03 20:58:42 +0000117 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
118 MachineBasicBlock::iterator &nmi,
119 MachineFunction::iterator &mbbi,
120 unsigned SrcIdx, unsigned DstIdx,
121 unsigned Dist);
122
Evan Cheng870b8072009-03-01 02:03:43 +0000123 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
124 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000125
Evan Cheng875357d2008-03-13 06:37:55 +0000126 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000127 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000128 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000129
Bill Wendling637980e2008-05-10 00:12:52 +0000130 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000131 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +0000132 AU.addRequired<AliasAnalysis>();
Bill Wendling637980e2008-05-10 00:12:52 +0000133 AU.addPreserved<LiveVariables>();
134 AU.addPreservedID(MachineLoopInfoID);
135 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +0000136 if (StrongPHIElim)
137 AU.addPreservedID(StrongPHIEliminationID);
138 else
139 AU.addPreservedID(PHIEliminationID);
Bill Wendling637980e2008-05-10 00:12:52 +0000140 MachineFunctionPass::getAnalysisUsage(AU);
141 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000142
Bill Wendling637980e2008-05-10 00:12:52 +0000143 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000144 bool runOnMachineFunction(MachineFunction&);
145 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000146}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000147
Dan Gohman844731a2008-05-13 00:00:25 +0000148char TwoAddressInstructionPass::ID = 0;
149static RegisterPass<TwoAddressInstructionPass>
150X("twoaddressinstruction", "Two-Address instruction pass");
151
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000152const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000153
Evan Cheng875357d2008-03-13 06:37:55 +0000154/// Sink3AddrInstruction - A two-address instruction has been converted to a
155/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000156/// past the instruction that would kill the above mentioned register to reduce
157/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000158bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
159 MachineInstr *MI, unsigned SavedReg,
160 MachineBasicBlock::iterator OldPos) {
161 // Check if it's safe to move this instruction.
162 bool SeenStore = true; // Be conservative.
Dan Gohmana70dca12009-10-09 23:27:56 +0000163 if (!MI->isSafeToMove(TII, SeenStore, AA))
Evan Cheng875357d2008-03-13 06:37:55 +0000164 return false;
165
166 unsigned DefReg = 0;
167 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000168
Evan Cheng875357d2008-03-13 06:37:55 +0000169 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
170 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000171 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000172 continue;
173 unsigned MOReg = MO.getReg();
174 if (!MOReg)
175 continue;
176 if (MO.isUse() && MOReg != SavedReg)
177 UseRegs.insert(MO.getReg());
178 if (!MO.isDef())
179 continue;
180 if (MO.isImplicit())
181 // Don't try to move it if it implicitly defines a register.
182 return false;
183 if (DefReg)
184 // For now, don't move any instructions that define multiple registers.
185 return false;
186 DefReg = MO.getReg();
187 }
188
189 // Find the instruction that kills SavedReg.
190 MachineInstr *KillMI = NULL;
191 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
192 UE = MRI->use_end(); UI != UE; ++UI) {
193 MachineOperand &UseMO = UI.getOperand();
194 if (!UseMO.isKill())
195 continue;
196 KillMI = UseMO.getParent();
197 break;
198 }
Bill Wendling637980e2008-05-10 00:12:52 +0000199
Dan Gohman97121ba2009-04-08 00:15:30 +0000200 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
Evan Cheng875357d2008-03-13 06:37:55 +0000201 return false;
202
Bill Wendling637980e2008-05-10 00:12:52 +0000203 // If any of the definitions are used by another instruction between the
204 // position and the kill use, then it's not safe to sink it.
205 //
206 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000207 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000208 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000209 MachineOperand *KillMO = NULL;
210 MachineBasicBlock::iterator KillPos = KillMI;
211 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000212
Evan Cheng7543e582008-06-18 07:49:14 +0000213 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000214 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000215 MachineInstr *OtherMI = I;
Evan Cheng7543e582008-06-18 07:49:14 +0000216 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
217 return false;
218 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000219 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
220 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000221 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000222 continue;
223 unsigned MOReg = MO.getReg();
224 if (!MOReg)
225 continue;
226 if (DefReg == MOReg)
227 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000228
Evan Cheng875357d2008-03-13 06:37:55 +0000229 if (MO.isKill()) {
230 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000231 // Save the operand that kills the register. We want to unset the kill
232 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000233 KillMO = &MO;
234 else if (UseRegs.count(MOReg))
235 // One of the uses is killed before the destination.
236 return false;
237 }
238 }
239 }
240
Evan Cheng875357d2008-03-13 06:37:55 +0000241 // Update kill and LV information.
242 KillMO->setIsKill(false);
243 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
244 KillMO->setIsKill(true);
Owen Anderson802af112008-07-02 21:28:58 +0000245
Evan Cheng9f1c8312008-07-03 09:09:37 +0000246 if (LV)
247 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000248
249 // Move instruction to its destination.
250 MBB->remove(MI);
251 MBB->insert(KillPos, MI);
252
253 ++Num3AddrSunk;
254 return true;
255}
256
Evan Cheng7543e582008-06-18 07:49:14 +0000257/// isTwoAddrUse - Return true if the specified MI is using the specified
258/// register as a two-address operand.
259static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
260 const TargetInstrDesc &TID = UseMI->getDesc();
261 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
262 MachineOperand &MO = UseMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000263 if (MO.isReg() && MO.getReg() == Reg &&
Evan Chenga24752f2009-03-19 20:30:06 +0000264 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
Evan Cheng7543e582008-06-18 07:49:14 +0000265 // Earlier use is a two-address one.
266 return true;
267 }
268 return false;
269}
270
271/// isProfitableToReMat - Return true if the heuristics determines it is likely
272/// to be profitable to re-materialize the definition of Reg rather than copy
273/// the register.
274bool
275TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000276 const TargetRegisterClass *RC,
277 MachineInstr *MI, MachineInstr *DefMI,
278 MachineBasicBlock *MBB, unsigned Loc) {
Evan Cheng7543e582008-06-18 07:49:14 +0000279 bool OtherUse = false;
280 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
281 UE = MRI->use_end(); UI != UE; ++UI) {
282 MachineOperand &UseMO = UI.getOperand();
Evan Cheng7543e582008-06-18 07:49:14 +0000283 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng601ca4b2008-06-25 01:16:38 +0000284 MachineBasicBlock *UseMBB = UseMI->getParent();
285 if (UseMBB == MBB) {
286 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
287 if (DI != DistanceMap.end() && DI->second == Loc)
288 continue; // Current use.
289 OtherUse = true;
290 // There is at least one other use in the MBB that will clobber the
291 // register.
292 if (isTwoAddrUse(UseMI, Reg))
293 return true;
294 }
Evan Cheng7543e582008-06-18 07:49:14 +0000295 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000296
297 // If other uses in MBB are not two-address uses, then don't remat.
298 if (OtherUse)
299 return false;
300
301 // No other uses in the same block, remat if it's defined in the same
302 // block so it does not unnecessarily extend the live range.
303 return MBB == DefMI->getParent();
Evan Cheng7543e582008-06-18 07:49:14 +0000304}
305
Evan Chengd498c8f2009-01-25 03:53:59 +0000306/// NoUseAfterLastDef - Return true if there are no intervening uses between the
307/// last instruction in the MBB that defines the specified register and the
308/// two-address instruction which is being processed. It also returns the last
309/// def location by reference
310bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000311 MachineBasicBlock *MBB, unsigned Dist,
312 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000313 LastDef = 0;
314 unsigned LastUse = Dist;
315 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
316 E = MRI->reg_end(); I != E; ++I) {
317 MachineOperand &MO = I.getOperand();
318 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000319 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000320 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000321 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
322 if (DI == DistanceMap.end())
323 continue;
324 if (MO.isUse() && DI->second < LastUse)
325 LastUse = DI->second;
326 if (MO.isDef() && DI->second > LastDef)
327 LastDef = DI->second;
328 }
329
330 return !(LastUse > LastDef && LastUse < Dist);
331}
332
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000333MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
334 MachineBasicBlock *MBB,
335 unsigned Dist) {
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000336 unsigned LastUseDist = 0;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000337 MachineInstr *LastUse = 0;
338 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
339 E = MRI->reg_end(); I != E; ++I) {
340 MachineOperand &MO = I.getOperand();
341 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000342 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000343 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000344 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
345 if (DI == DistanceMap.end())
346 continue;
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000347 if (DI->second >= Dist)
348 continue;
349
350 if (MO.isUse() && DI->second > LastUseDist) {
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000351 LastUse = DI->first;
352 LastUseDist = DI->second;
353 }
354 }
355 return LastUse;
356}
357
Evan Cheng870b8072009-03-01 02:03:43 +0000358/// isCopyToReg - Return true if the specified MI is a copy instruction or
359/// a extract_subreg instruction. It also returns the source and destination
360/// registers and whether they are physical registers by reference.
361static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
362 unsigned &SrcReg, unsigned &DstReg,
363 bool &IsSrcPhys, bool &IsDstPhys) {
364 SrcReg = 0;
365 DstReg = 0;
366 unsigned SrcSubIdx, DstSubIdx;
367 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Chris Lattner518bb532010-02-09 19:54:29 +0000368 if (MI.isExtractSubreg()) {
Evan Cheng870b8072009-03-01 02:03:43 +0000369 DstReg = MI.getOperand(0).getReg();
370 SrcReg = MI.getOperand(1).getReg();
Chris Lattner518bb532010-02-09 19:54:29 +0000371 } else if (MI.isInsertSubreg()) {
Evan Cheng870b8072009-03-01 02:03:43 +0000372 DstReg = MI.getOperand(0).getReg();
373 SrcReg = MI.getOperand(2).getReg();
Chris Lattner518bb532010-02-09 19:54:29 +0000374 } else if (MI.isSubregToReg()) {
Dan Gohman97121ba2009-04-08 00:15:30 +0000375 DstReg = MI.getOperand(0).getReg();
376 SrcReg = MI.getOperand(2).getReg();
Evan Cheng870b8072009-03-01 02:03:43 +0000377 }
378 }
379
380 if (DstReg) {
381 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
382 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
383 return true;
384 }
385 return false;
386}
387
Dan Gohman97121ba2009-04-08 00:15:30 +0000388/// isKilled - Test if the given register value, which is used by the given
389/// instruction, is killed by the given instruction. This looks through
390/// coalescable copies to see if the original value is potentially not killed.
391///
392/// For example, in this code:
393///
394/// %reg1034 = copy %reg1024
395/// %reg1035 = copy %reg1025<kill>
396/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
397///
398/// %reg1034 is not considered to be killed, since it is copied from a
399/// register which is not killed. Treating it as not killed lets the
400/// normal heuristics commute the (two-address) add, which lets
401/// coalescing eliminate the extra copy.
402///
403static bool isKilled(MachineInstr &MI, unsigned Reg,
404 const MachineRegisterInfo *MRI,
405 const TargetInstrInfo *TII) {
406 MachineInstr *DefMI = &MI;
407 for (;;) {
408 if (!DefMI->killsRegister(Reg))
409 return false;
410 if (TargetRegisterInfo::isPhysicalRegister(Reg))
411 return true;
412 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
413 // If there are multiple defs, we can't do a simple analysis, so just
414 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000415 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000416 return true;
417 DefMI = &*Begin;
418 bool IsSrcPhys, IsDstPhys;
419 unsigned SrcReg, DstReg;
420 // If the def is something other than a copy, then it isn't going to
421 // be coalesced, so follow the kill flag.
422 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
423 return true;
424 Reg = SrcReg;
425 }
426}
427
Evan Cheng870b8072009-03-01 02:03:43 +0000428/// isTwoAddrUse - Return true if the specified MI uses the specified register
429/// as a two-address use. If so, return the destination register by reference.
430static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
431 const TargetInstrDesc &TID = MI.getDesc();
Chris Lattner518bb532010-02-09 19:54:29 +0000432 unsigned NumOps = MI.isInlineAsm() ? MI.getNumOperands():TID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000433 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000434 const MachineOperand &MO = MI.getOperand(i);
435 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
436 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000437 unsigned ti;
438 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000439 DstReg = MI.getOperand(ti).getReg();
440 return true;
441 }
442 }
443 return false;
444}
445
446/// findOnlyInterestingUse - Given a register, if has a single in-basic block
447/// use, return the use instruction if it's a copy or a two-address use.
448static
449MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
450 MachineRegisterInfo *MRI,
451 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000452 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000453 unsigned &DstReg, bool &IsDstPhys) {
454 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
455 if (UI == MRI->use_end())
456 return 0;
457 MachineInstr &UseMI = *UI;
458 if (++UI != MRI->use_end())
459 // More than one use.
460 return 0;
461 if (UseMI.getParent() != MBB)
462 return 0;
463 unsigned SrcReg;
464 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000465 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
466 IsCopy = true;
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 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000470 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
471 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000472 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000473 }
Evan Cheng870b8072009-03-01 02:03:43 +0000474 return 0;
475}
476
477/// getMappedReg - Return the physical register the specified virtual register
478/// might be mapped to.
479static unsigned
480getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
481 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
482 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
483 if (SI == RegMap.end())
484 return 0;
485 Reg = SI->second;
486 }
487 if (TargetRegisterInfo::isPhysicalRegister(Reg))
488 return Reg;
489 return 0;
490}
491
492/// regsAreCompatible - Return true if the two registers are equal or aliased.
493///
494static bool
495regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
496 if (RegA == RegB)
497 return true;
498 if (!RegA || !RegB)
499 return false;
500 return TRI->regsOverlap(RegA, RegB);
501}
502
503
Evan Chengd498c8f2009-01-25 03:53:59 +0000504/// isProfitableToReMat - Return true if it's potentially profitable to commute
505/// the two-address instruction that's being processed.
506bool
507TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000508 MachineInstr *MI, MachineBasicBlock *MBB,
509 unsigned Dist) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000510 // Determine if it's profitable to commute this two address instruction. In
511 // general, we want no uses between this instruction and the definition of
512 // the two-address register.
513 // e.g.
514 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
515 // %reg1029<def> = MOV8rr %reg1028
516 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
517 // insert => %reg1030<def> = MOV8rr %reg1028
518 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
519 // In this case, it might not be possible to coalesce the second MOV8rr
520 // instruction if the first one is coalesced. So it would be profitable to
521 // commute it:
522 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
523 // %reg1029<def> = MOV8rr %reg1028
524 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
525 // insert => %reg1030<def> = MOV8rr %reg1029
526 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
527
528 if (!MI->killsRegister(regC))
529 return false;
530
531 // Ok, we have something like:
532 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
533 // let's see if it's worth commuting it.
534
Evan Cheng870b8072009-03-01 02:03:43 +0000535 // Look for situations like this:
536 // %reg1024<def> = MOV r1
537 // %reg1025<def> = MOV r0
538 // %reg1026<def> = ADD %reg1024, %reg1025
539 // r0 = MOV %reg1026
540 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
541 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
542 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
543 unsigned ToRegB = getMappedReg(regB, DstRegMap);
544 unsigned ToRegC = getMappedReg(regC, DstRegMap);
545 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
546 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
547 regsAreCompatible(FromRegC, ToRegB, TRI)))
548 return true;
549
Evan Chengd498c8f2009-01-25 03:53:59 +0000550 // If there is a use of regC between its last def (could be livein) and this
551 // instruction, then bail.
552 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000553 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000554 return false;
555
556 // If there is a use of regB between its last def (could be livein) and this
557 // instruction, then go ahead and make this transformation.
558 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000559 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000560 return true;
561
562 // Since there are no intervening uses for both registers, then commute
563 // if the def of regC is closer. Its live interval is shorter.
564 return LastDefB && LastDefC && LastDefC > LastDefB;
565}
566
Evan Cheng81913712009-01-23 23:27:33 +0000567/// CommuteInstruction - Commute a two-address instruction and update the basic
568/// block, distance map, and live variables if needed. Return true if it is
569/// successful.
570bool
571TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000572 MachineFunction::iterator &mbbi,
573 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000574 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000575 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000576 MachineInstr *NewMI = TII->commuteInstruction(MI);
577
578 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000579 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000580 return false;
581 }
582
David Greeneeb00b182010-01-05 01:24:21 +0000583 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000584 // If the instruction changed to commute it, update livevar.
585 if (NewMI != MI) {
586 if (LV)
587 // Update live variables
588 LV->replaceKillInstruction(RegC, MI, NewMI);
589
590 mbbi->insert(mi, NewMI); // Insert the new inst
591 mbbi->erase(mi); // Nuke the old inst.
592 mi = NewMI;
593 DistanceMap.insert(std::make_pair(NewMI, Dist));
594 }
Evan Cheng870b8072009-03-01 02:03:43 +0000595
596 // Update source register map.
597 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
598 if (FromRegC) {
599 unsigned RegA = MI->getOperand(0).getReg();
600 SrcRegMap[RegA] = FromRegC;
601 }
602
Evan Cheng81913712009-01-23 23:27:33 +0000603 return true;
604}
605
Evan Chenge6f350d2009-03-30 21:34:07 +0000606/// isProfitableToConv3Addr - Return true if it is profitable to convert the
607/// given 2-address instruction to a 3-address one.
608bool
609TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
610 // Look for situations like this:
611 // %reg1024<def> = MOV r1
612 // %reg1025<def> = MOV r0
613 // %reg1026<def> = ADD %reg1024, %reg1025
614 // r2 = MOV %reg1026
615 // Turn ADD into a 3-address instruction to avoid a copy.
616 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
617 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
618 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
619}
620
621/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
622/// three address one. Return true if this transformation was successful.
623bool
624TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
625 MachineBasicBlock::iterator &nmi,
626 MachineFunction::iterator &mbbi,
627 unsigned RegB, unsigned Dist) {
628 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
629 if (NewMI) {
David Greeneeb00b182010-01-05 01:24:21 +0000630 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
631 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000632 bool Sunk = false;
633
634 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
635 // FIXME: Temporary workaround. If the new instruction doesn't
636 // uses RegB, convertToThreeAddress must have created more
637 // then one instruction.
638 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
639
640 mbbi->erase(mi); // Nuke the old inst.
641
642 if (!Sunk) {
643 DistanceMap.insert(std::make_pair(NewMI, Dist));
644 mi = NewMI;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000645 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000646 }
647 return true;
648 }
649
650 return false;
651}
652
Evan Cheng870b8072009-03-01 02:03:43 +0000653/// ProcessCopy - If the specified instruction is not yet processed, process it
654/// if it's a copy. For a copy instruction, we find the physical registers the
655/// source and destination registers might be mapped to. These are kept in
656/// point-to maps used to determine future optimizations. e.g.
657/// v1024 = mov r0
658/// v1025 = mov r1
659/// v1026 = add v1024, v1025
660/// r1 = mov r1026
661/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
662/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
663/// potentially joined with r1 on the output side. It's worthwhile to commute
664/// 'add' to eliminate a copy.
665void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
666 MachineBasicBlock *MBB,
667 SmallPtrSet<MachineInstr*, 8> &Processed) {
668 if (Processed.count(MI))
669 return;
670
671 bool IsSrcPhys, IsDstPhys;
672 unsigned SrcReg, DstReg;
673 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
674 return;
675
676 if (IsDstPhys && !IsSrcPhys)
677 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
678 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000679 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
680 if (!isNew)
681 assert(SrcRegMap[DstReg] == SrcReg &&
682 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000683
684 SmallVector<unsigned, 4> VirtRegPairs;
Evan Cheng87d696a2009-04-14 00:32:25 +0000685 bool IsCopy = false;
Evan Cheng870b8072009-03-01 02:03:43 +0000686 unsigned NewReg = 0;
687 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000688 IsCopy, NewReg, IsDstPhys)) {
689 if (IsCopy) {
690 if (!Processed.insert(UseMI))
Evan Cheng870b8072009-03-01 02:03:43 +0000691 break;
692 }
693
694 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
695 if (DI != DistanceMap.end())
696 // Earlier in the same MBB.Reached via a back edge.
697 break;
698
699 if (IsDstPhys) {
700 VirtRegPairs.push_back(NewReg);
701 break;
702 }
703 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000704 if (!isNew)
Evan Cheng87d696a2009-04-14 00:32:25 +0000705 assert(SrcRegMap[NewReg] == DstReg &&
706 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000707 VirtRegPairs.push_back(NewReg);
708 DstReg = NewReg;
709 }
710
711 if (!VirtRegPairs.empty()) {
712 unsigned ToReg = VirtRegPairs.back();
713 VirtRegPairs.pop_back();
714 while (!VirtRegPairs.empty()) {
715 unsigned FromReg = VirtRegPairs.back();
716 VirtRegPairs.pop_back();
717 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000718 if (!isNew)
719 assert(DstRegMap[FromReg] == ToReg &&
720 "Can't map to two dst physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000721 ToReg = FromReg;
722 }
723 }
724 }
725
726 Processed.insert(MI);
727}
728
Evan Cheng28c7ce32009-02-21 03:14:25 +0000729/// isSafeToDelete - If the specified instruction does not produce any side
730/// effects and all of its defs are dead, then it's safe to delete.
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000731static bool isSafeToDelete(MachineInstr *MI,
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000732 const TargetInstrInfo *TII,
733 SmallVector<unsigned, 4> &Kills) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000734 const TargetInstrDesc &TID = MI->getDesc();
735 if (TID.mayStore() || TID.isCall())
736 return false;
737 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
738 return false;
739
740 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
741 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000742 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000743 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000744 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000745 return false;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000746 if (MO.isUse() && MO.isKill())
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000747 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000748 }
Evan Cheng28c7ce32009-02-21 03:14:25 +0000749 return true;
750}
751
Bob Wilson326f4382009-09-01 22:51:08 +0000752/// canUpdateDeletedKills - Check if all the registers listed in Kills are
753/// killed by instructions in MBB preceding the current instruction at
754/// position Dist. If so, return true and record information about the
755/// preceding kills in NewKills.
756bool TwoAddressInstructionPass::
757canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
758 SmallVector<NewKill, 4> &NewKills,
759 MachineBasicBlock *MBB, unsigned Dist) {
760 while (!Kills.empty()) {
761 unsigned Kill = Kills.back();
762 Kills.pop_back();
763 if (TargetRegisterInfo::isPhysicalRegister(Kill))
764 return false;
765
766 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
767 if (!LastKill)
768 return false;
769
770 bool isModRef = LastKill->modifiesRegister(Kill);
771 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
772 LastKill));
773 }
774 return true;
775}
776
777/// DeleteUnusedInstr - If an instruction with a tied register operand can
778/// be safely deleted, just delete it.
779bool
780TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
781 MachineBasicBlock::iterator &nmi,
782 MachineFunction::iterator &mbbi,
Bob Wilson326f4382009-09-01 22:51:08 +0000783 unsigned Dist) {
784 // Check if the instruction has no side effects and if all its defs are dead.
785 SmallVector<unsigned, 4> Kills;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000786 if (!isSafeToDelete(mi, TII, Kills))
Bob Wilson326f4382009-09-01 22:51:08 +0000787 return false;
788
789 // If this instruction kills some virtual registers, we need to
790 // update the kill information. If it's not possible to do so,
791 // then bail out.
792 SmallVector<NewKill, 4> NewKills;
793 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
794 return false;
795
796 if (LV) {
797 while (!NewKills.empty()) {
798 MachineInstr *NewKill = NewKills.back().second;
799 unsigned Kill = NewKills.back().first.first;
800 bool isDead = NewKills.back().first.second;
801 NewKills.pop_back();
802 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
803 if (isDead)
804 LV->addVirtualRegisterDead(Kill, NewKill);
805 else
806 LV->addVirtualRegisterKilled(Kill, NewKill);
807 }
808 }
Bob Wilson326f4382009-09-01 22:51:08 +0000809 }
810
811 mbbi->erase(mi); // Nuke the old inst.
812 mi = nmi;
813 return true;
814}
815
Bob Wilsoncc80df92009-09-03 20:58:42 +0000816/// TryInstructionTransform - For the case where an instruction has a single
817/// pair of tied register operands, attempt some transformations that may
818/// either eliminate the tied operands or improve the opportunities for
819/// coalescing away the register copy. Returns true if the tied operands
820/// are eliminated altogether.
821bool TwoAddressInstructionPass::
822TryInstructionTransform(MachineBasicBlock::iterator &mi,
823 MachineBasicBlock::iterator &nmi,
824 MachineFunction::iterator &mbbi,
825 unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
826 const TargetInstrDesc &TID = mi->getDesc();
827 unsigned regA = mi->getOperand(DstIdx).getReg();
828 unsigned regB = mi->getOperand(SrcIdx).getReg();
829
830 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
831 "cannot make instruction into two-address form");
832
833 // If regA is dead and the instruction can be deleted, just delete
834 // it so it doesn't clobber regB.
835 bool regBKilled = isKilled(*mi, regB, MRI, TII);
836 if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000837 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +0000838 ++NumDeletes;
839 return true; // Done with this instruction.
840 }
841
842 // Check if it is profitable to commute the operands.
843 unsigned SrcOp1, SrcOp2;
844 unsigned regC = 0;
845 unsigned regCIdx = ~0U;
846 bool TryCommute = false;
847 bool AggressiveCommute = false;
848 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
849 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
850 if (SrcIdx == SrcOp1)
851 regCIdx = SrcOp2;
852 else if (SrcIdx == SrcOp2)
853 regCIdx = SrcOp1;
854
855 if (regCIdx != ~0U) {
856 regC = mi->getOperand(regCIdx).getReg();
857 if (!regBKilled && isKilled(*mi, regC, MRI, TII))
858 // If C dies but B does not, swap the B and C operands.
859 // This makes the live ranges of A and C joinable.
860 TryCommute = true;
861 else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
862 TryCommute = true;
863 AggressiveCommute = true;
864 }
865 }
866 }
867
868 // If it's profitable to commute, try to do so.
869 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
870 ++NumCommuted;
871 if (AggressiveCommute)
872 ++NumAggrCommuted;
873 return false;
874 }
875
876 if (TID.isConvertibleTo3Addr()) {
877 // This instruction is potentially convertible to a true
878 // three-address instruction. Check if it is profitable.
879 if (!regBKilled || isProfitableToConv3Addr(regA)) {
880 // Try to convert it.
881 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
882 ++NumConvertedTo3Addr;
883 return true; // Done with this instruction.
884 }
885 }
886 }
887 return false;
888}
889
Bill Wendling637980e2008-05-10 00:12:52 +0000890/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000891///
Chris Lattner163c1e72004-01-31 21:14:04 +0000892bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
David Greeneeb00b182010-01-05 01:24:21 +0000893 DEBUG(dbgs() << "Machine Function\n");
Misha Brukman75fa4e42004-07-22 15:26:23 +0000894 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +0000895 MRI = &MF.getRegInfo();
896 TII = TM.getInstrInfo();
897 TRI = TM.getRegisterInfo();
Duncan Sands1465d612009-01-28 13:14:17 +0000898 LV = getAnalysisIfAvailable<LiveVariables>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000899 AA = &getAnalysis<AliasAnalysis>();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000900
Misha Brukman75fa4e42004-07-22 15:26:23 +0000901 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000902
David Greeneeb00b182010-01-05 01:24:21 +0000903 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
904 DEBUG(dbgs() << "********** Function: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000905 << MF.getFunction()->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +0000906
Evan Cheng7543e582008-06-18 07:49:14 +0000907 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
908 BitVector ReMatRegs;
909 ReMatRegs.resize(MRI->getLastVirtReg()+1);
910
Bob Wilsoncc80df92009-09-03 20:58:42 +0000911 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
912 TiedOperandMap;
913 TiedOperandMap TiedOperands(4);
914
Evan Cheng870b8072009-03-01 02:03:43 +0000915 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +0000916 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
917 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +0000918 unsigned Dist = 0;
919 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +0000920 SrcRegMap.clear();
921 DstRegMap.clear();
922 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +0000923 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +0000924 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +0000925 MachineBasicBlock::iterator nmi = llvm::next(mi);
Chris Lattner749c6f62008-01-07 07:27:27 +0000926 const TargetInstrDesc &TID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +0000927 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +0000928
Evan Cheng7543e582008-06-18 07:49:14 +0000929 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +0000930
931 ProcessCopy(&*mi, &*mbbi, Processed);
932
Bob Wilsoncc80df92009-09-03 20:58:42 +0000933 // First scan through all the tied register uses in this instruction
934 // and record a list of pairs of tied operands for each register.
Chris Lattner518bb532010-02-09 19:54:29 +0000935 unsigned NumOps = mi->isInlineAsm()
Evan Chengfb112882009-03-23 08:01:15 +0000936 ? mi->getNumOperands() : TID.getNumOperands();
Bob Wilsoncc80df92009-09-03 20:58:42 +0000937 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
938 unsigned DstIdx = 0;
939 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
Evan Cheng360c2dd2006-11-01 23:06:55 +0000940 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000941
Evan Cheng360c2dd2006-11-01 23:06:55 +0000942 if (FirstTied) {
Bob Wilsoncc80df92009-09-03 20:58:42 +0000943 FirstTied = false;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000944 ++NumTwoAddressInstrs;
David Greeneeb00b182010-01-05 01:24:21 +0000945 DEBUG(dbgs() << '\t' << *mi);
Evan Cheng360c2dd2006-11-01 23:06:55 +0000946 }
Bill Wendling637980e2008-05-10 00:12:52 +0000947
Bob Wilsoncc80df92009-09-03 20:58:42 +0000948 assert(mi->getOperand(SrcIdx).isReg() &&
949 mi->getOperand(SrcIdx).getReg() &&
950 mi->getOperand(SrcIdx).isUse() &&
951 "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000952
Bob Wilsoncc80df92009-09-03 20:58:42 +0000953 unsigned regB = mi->getOperand(SrcIdx).getReg();
954 TiedOperandMap::iterator OI = TiedOperands.find(regB);
955 if (OI == TiedOperands.end()) {
956 SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
957 OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
958 }
959 OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
960 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000961
Bob Wilsoncc80df92009-09-03 20:58:42 +0000962 // Now iterate over the information collected above.
963 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
964 OE = TiedOperands.end(); OI != OE; ++OI) {
965 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000966
Bob Wilsoncc80df92009-09-03 20:58:42 +0000967 // If the instruction has a single pair of tied operands, try some
968 // transformations that may either eliminate the tied operands or
969 // improve the opportunities for coalescing away the register copy.
970 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
971 unsigned SrcIdx = TiedPairs[0].first;
972 unsigned DstIdx = TiedPairs[0].second;
Bob Wilson43449792009-08-31 21:54:55 +0000973
Bob Wilsoncc80df92009-09-03 20:58:42 +0000974 // If the registers are already equal, nothing needs to be done.
975 if (mi->getOperand(SrcIdx).getReg() ==
976 mi->getOperand(DstIdx).getReg())
977 break; // Done with this instruction.
978
979 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
980 break; // The tied operands have been eliminated.
981 }
982
983 bool RemovedKillFlag = false;
984 bool AllUsesCopied = true;
985 unsigned LastCopiedReg = 0;
986 unsigned regB = OI->first;
987 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
988 unsigned SrcIdx = TiedPairs[tpi].first;
989 unsigned DstIdx = TiedPairs[tpi].second;
990 unsigned regA = mi->getOperand(DstIdx).getReg();
991 // Grab regB from the instruction because it may have changed if the
992 // instruction was commuted.
993 regB = mi->getOperand(SrcIdx).getReg();
994
995 if (regA == regB) {
996 // The register is tied to multiple destinations (or else we would
997 // not have continued this far), but this use of the register
998 // already matches the tied destination. Leave it.
999 AllUsesCopied = false;
1000 continue;
1001 }
1002 LastCopiedReg = regA;
1003
1004 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1005 "cannot make instruction into two-address form");
Chris Lattner6b507672004-01-31 21:21:43 +00001006
Chris Lattner1e313632004-07-21 23:17:57 +00001007#ifndef NDEBUG
Bob Wilsoncc80df92009-09-03 20:58:42 +00001008 // First, verify that we don't have a use of "a" in the instruction
1009 // (a = b + a for example) because our transformation will not
1010 // work. This should never occur because we are in SSA form.
1011 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1012 assert(i == DstIdx ||
1013 !mi->getOperand(i).isReg() ||
1014 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +00001015#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +00001016
Bob Wilsoncc80df92009-09-03 20:58:42 +00001017 // Emit a copy or rematerialize the definition.
1018 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1019 MachineInstr *DefMI = MRI->getVRegDef(regB);
1020 // If it's safe and profitable, remat the definition instead of
1021 // copying it.
1022 if (DefMI &&
1023 DefMI->getDesc().isAsCheapAsAMove() &&
Dan Gohmana70dca12009-10-09 23:27:56 +00001024 DefMI->isSafeToReMat(TII, regB, AA) &&
Bob Wilsoncc80df92009-09-03 20:58:42 +00001025 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
David Greeneeb00b182010-01-05 01:24:21 +00001026 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
Bob Wilsoncc80df92009-09-03 20:58:42 +00001027 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
Evan Chengd57cdd52009-11-14 02:55:43 +00001028 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, TRI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001029 ReMatRegs.set(regB);
1030 ++NumReMats;
Bob Wilson71124f62009-09-01 04:18:40 +00001031 } else {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001032 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
1033 (void)Emitted;
1034 assert(Emitted && "Unable to issue a copy instruction!\n");
1035 }
1036
1037 MachineBasicBlock::iterator prevMI = prior(mi);
1038 // Update DistanceMap.
1039 DistanceMap.insert(std::make_pair(prevMI, Dist));
1040 DistanceMap[mi] = ++Dist;
1041
David Greeneeb00b182010-01-05 01:24:21 +00001042 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001043
1044 MachineOperand &MO = mi->getOperand(SrcIdx);
1045 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1046 "inconsistent operand info for 2-reg pass");
1047 if (MO.isKill()) {
1048 MO.setIsKill(false);
1049 RemovedKillFlag = true;
1050 }
1051 MO.setReg(regA);
1052 }
1053
1054 if (AllUsesCopied) {
1055 // Replace other (un-tied) uses of regB with LastCopiedReg.
1056 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1057 MachineOperand &MO = mi->getOperand(i);
1058 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1059 if (MO.isKill()) {
1060 MO.setIsKill(false);
1061 RemovedKillFlag = true;
1062 }
1063 MO.setReg(LastCopiedReg);
1064 }
1065 }
1066
1067 // Update live variables for regB.
1068 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1069 LV->addVirtualRegisterKilled(regB, prior(mi));
1070
1071 } else if (RemovedKillFlag) {
1072 // Some tied uses of regB matched their destination registers, so
1073 // regB is still used in this instruction, but a kill flag was
1074 // removed from a different tied use of regB, so now we need to add
1075 // a kill flag to one of the remaining uses of regB.
1076 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1077 MachineOperand &MO = mi->getOperand(i);
1078 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1079 MO.setIsKill(true);
1080 break;
Bob Wilson71124f62009-09-01 04:18:40 +00001081 }
1082 }
Bob Wilson43449792009-08-31 21:54:55 +00001083 }
Bob Wilsoncc80df92009-09-03 20:58:42 +00001084
Bob Wilson43449792009-08-31 21:54:55 +00001085 MadeChange = true;
1086
David Greeneeb00b182010-01-05 01:24:21 +00001087 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Misha Brukman75fa4e42004-07-22 15:26:23 +00001088 }
Bill Wendling637980e2008-05-10 00:12:52 +00001089
Bob Wilsoncc80df92009-09-03 20:58:42 +00001090 // Clear TiedOperands here instead of at the top of the loop
1091 // since most instructions do not have tied operands.
1092 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001093 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001094 }
1095 }
1096
Evan Cheng601ca4b2008-06-25 01:16:38 +00001097 // Some remat'ed instructions are dead.
1098 int VReg = ReMatRegs.find_first();
1099 while (VReg != -1) {
1100 if (MRI->use_empty(VReg)) {
1101 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1102 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +00001103 }
Evan Cheng601ca4b2008-06-25 01:16:38 +00001104 VReg = ReMatRegs.find_next(VReg);
Bill Wendling48f7f232008-05-26 05:18:34 +00001105 }
1106
Misha Brukman75fa4e42004-07-22 15:26:23 +00001107 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001108}