blob: 2ec0c712222e4ef022266a05572f04a19154a5b5 [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
Evan Cheng870b8072009-03-01 02:03:43 +0000109 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
110 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng875357d2008-03-13 06:37:55 +0000111 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000112 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000113 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000114
Bill Wendling637980e2008-05-10 00:12:52 +0000115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling637980e2008-05-10 00:12:52 +0000116 AU.addPreserved<LiveVariables>();
117 AU.addPreservedID(MachineLoopInfoID);
118 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +0000119 if (StrongPHIElim)
120 AU.addPreservedID(StrongPHIEliminationID);
121 else
122 AU.addPreservedID(PHIEliminationID);
Bill Wendling637980e2008-05-10 00:12:52 +0000123 MachineFunctionPass::getAnalysisUsage(AU);
124 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000125
Bill Wendling637980e2008-05-10 00:12:52 +0000126 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000127 bool runOnMachineFunction(MachineFunction&);
128 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000129}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000130
Dan Gohman844731a2008-05-13 00:00:25 +0000131char TwoAddressInstructionPass::ID = 0;
132static RegisterPass<TwoAddressInstructionPass>
133X("twoaddressinstruction", "Two-Address instruction pass");
134
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000135const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000136
Evan Cheng875357d2008-03-13 06:37:55 +0000137/// Sink3AddrInstruction - A two-address instruction has been converted to a
138/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000139/// past the instruction that would kill the above mentioned register to reduce
140/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000141bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
142 MachineInstr *MI, unsigned SavedReg,
143 MachineBasicBlock::iterator OldPos) {
144 // Check if it's safe to move this instruction.
145 bool SeenStore = true; // Be conservative.
146 if (!MI->isSafeToMove(TII, SeenStore))
147 return false;
148
149 unsigned DefReg = 0;
150 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000151
Evan Cheng875357d2008-03-13 06:37:55 +0000152 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
153 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000154 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000155 continue;
156 unsigned MOReg = MO.getReg();
157 if (!MOReg)
158 continue;
159 if (MO.isUse() && MOReg != SavedReg)
160 UseRegs.insert(MO.getReg());
161 if (!MO.isDef())
162 continue;
163 if (MO.isImplicit())
164 // Don't try to move it if it implicitly defines a register.
165 return false;
166 if (DefReg)
167 // For now, don't move any instructions that define multiple registers.
168 return false;
169 DefReg = MO.getReg();
170 }
171
172 // Find the instruction that kills SavedReg.
173 MachineInstr *KillMI = NULL;
174 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
175 UE = MRI->use_end(); UI != UE; ++UI) {
176 MachineOperand &UseMO = UI.getOperand();
177 if (!UseMO.isKill())
178 continue;
179 KillMI = UseMO.getParent();
180 break;
181 }
Bill Wendling637980e2008-05-10 00:12:52 +0000182
Dan Gohman97121ba2009-04-08 00:15:30 +0000183 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
Evan Cheng875357d2008-03-13 06:37:55 +0000184 return false;
185
Bill Wendling637980e2008-05-10 00:12:52 +0000186 // If any of the definitions are used by another instruction between the
187 // position and the kill use, then it's not safe to sink it.
188 //
189 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000190 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000191 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000192 MachineOperand *KillMO = NULL;
193 MachineBasicBlock::iterator KillPos = KillMI;
194 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000195
Evan Cheng7543e582008-06-18 07:49:14 +0000196 unsigned NumVisited = 0;
Evan Cheng875357d2008-03-13 06:37:55 +0000197 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
198 MachineInstr *OtherMI = I;
Evan Cheng7543e582008-06-18 07:49:14 +0000199 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
200 return false;
201 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000202 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
203 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000204 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000205 continue;
206 unsigned MOReg = MO.getReg();
207 if (!MOReg)
208 continue;
209 if (DefReg == MOReg)
210 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000211
Evan Cheng875357d2008-03-13 06:37:55 +0000212 if (MO.isKill()) {
213 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000214 // Save the operand that kills the register. We want to unset the kill
215 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000216 KillMO = &MO;
217 else if (UseRegs.count(MOReg))
218 // One of the uses is killed before the destination.
219 return false;
220 }
221 }
222 }
223
Evan Cheng875357d2008-03-13 06:37:55 +0000224 // Update kill and LV information.
225 KillMO->setIsKill(false);
226 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
227 KillMO->setIsKill(true);
Owen Anderson802af112008-07-02 21:28:58 +0000228
Evan Cheng9f1c8312008-07-03 09:09:37 +0000229 if (LV)
230 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000231
232 // Move instruction to its destination.
233 MBB->remove(MI);
234 MBB->insert(KillPos, MI);
235
236 ++Num3AddrSunk;
237 return true;
238}
239
Evan Cheng7543e582008-06-18 07:49:14 +0000240/// isTwoAddrUse - Return true if the specified MI is using the specified
241/// register as a two-address operand.
242static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
243 const TargetInstrDesc &TID = UseMI->getDesc();
244 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
245 MachineOperand &MO = UseMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000246 if (MO.isReg() && MO.getReg() == Reg &&
Evan Chenga24752f2009-03-19 20:30:06 +0000247 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
Evan Cheng7543e582008-06-18 07:49:14 +0000248 // Earlier use is a two-address one.
249 return true;
250 }
251 return false;
252}
253
254/// isProfitableToReMat - Return true if the heuristics determines it is likely
255/// to be profitable to re-materialize the definition of Reg rather than copy
256/// the register.
257bool
258TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000259 const TargetRegisterClass *RC,
260 MachineInstr *MI, MachineInstr *DefMI,
261 MachineBasicBlock *MBB, unsigned Loc) {
Evan Cheng7543e582008-06-18 07:49:14 +0000262 bool OtherUse = false;
263 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
264 UE = MRI->use_end(); UI != UE; ++UI) {
265 MachineOperand &UseMO = UI.getOperand();
Evan Cheng7543e582008-06-18 07:49:14 +0000266 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng601ca4b2008-06-25 01:16:38 +0000267 MachineBasicBlock *UseMBB = UseMI->getParent();
268 if (UseMBB == MBB) {
269 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
270 if (DI != DistanceMap.end() && DI->second == Loc)
271 continue; // Current use.
272 OtherUse = true;
273 // There is at least one other use in the MBB that will clobber the
274 // register.
275 if (isTwoAddrUse(UseMI, Reg))
276 return true;
277 }
Evan Cheng7543e582008-06-18 07:49:14 +0000278 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000279
280 // If other uses in MBB are not two-address uses, then don't remat.
281 if (OtherUse)
282 return false;
283
284 // No other uses in the same block, remat if it's defined in the same
285 // block so it does not unnecessarily extend the live range.
286 return MBB == DefMI->getParent();
Evan Cheng7543e582008-06-18 07:49:14 +0000287}
288
Evan Chengd498c8f2009-01-25 03:53:59 +0000289/// NoUseAfterLastDef - Return true if there are no intervening uses between the
290/// last instruction in the MBB that defines the specified register and the
291/// two-address instruction which is being processed. It also returns the last
292/// def location by reference
293bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000294 MachineBasicBlock *MBB, unsigned Dist,
295 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000296 LastDef = 0;
297 unsigned LastUse = Dist;
298 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
299 E = MRI->reg_end(); I != E; ++I) {
300 MachineOperand &MO = I.getOperand();
301 MachineInstr *MI = MO.getParent();
302 if (MI->getParent() != MBB)
303 continue;
304 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
305 if (DI == DistanceMap.end())
306 continue;
307 if (MO.isUse() && DI->second < LastUse)
308 LastUse = DI->second;
309 if (MO.isDef() && DI->second > LastDef)
310 LastDef = DI->second;
311 }
312
313 return !(LastUse > LastDef && LastUse < Dist);
314}
315
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000316MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
317 MachineBasicBlock *MBB,
318 unsigned Dist) {
319 unsigned LastUseDist = Dist;
320 MachineInstr *LastUse = 0;
321 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
322 E = MRI->reg_end(); I != E; ++I) {
323 MachineOperand &MO = I.getOperand();
324 MachineInstr *MI = MO.getParent();
325 if (MI->getParent() != MBB)
326 continue;
327 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
328 if (DI == DistanceMap.end())
329 continue;
330 if (MO.isUse() && DI->second < LastUseDist) {
331 LastUse = DI->first;
332 LastUseDist = DI->second;
333 }
334 }
335 return LastUse;
336}
337
Evan Cheng870b8072009-03-01 02:03:43 +0000338/// isCopyToReg - Return true if the specified MI is a copy instruction or
339/// a extract_subreg instruction. It also returns the source and destination
340/// registers and whether they are physical registers by reference.
341static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
342 unsigned &SrcReg, unsigned &DstReg,
343 bool &IsSrcPhys, bool &IsDstPhys) {
344 SrcReg = 0;
345 DstReg = 0;
346 unsigned SrcSubIdx, DstSubIdx;
347 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
348 if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
349 DstReg = MI.getOperand(0).getReg();
350 SrcReg = MI.getOperand(1).getReg();
351 } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
352 DstReg = MI.getOperand(0).getReg();
353 SrcReg = MI.getOperand(2).getReg();
Dan Gohman97121ba2009-04-08 00:15:30 +0000354 } else if (MI.getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
355 DstReg = MI.getOperand(0).getReg();
356 SrcReg = MI.getOperand(2).getReg();
Evan Cheng870b8072009-03-01 02:03:43 +0000357 }
358 }
359
360 if (DstReg) {
361 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
362 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
363 return true;
364 }
365 return false;
366}
367
Dan Gohman97121ba2009-04-08 00:15:30 +0000368/// isKilled - Test if the given register value, which is used by the given
369/// instruction, is killed by the given instruction. This looks through
370/// coalescable copies to see if the original value is potentially not killed.
371///
372/// For example, in this code:
373///
374/// %reg1034 = copy %reg1024
375/// %reg1035 = copy %reg1025<kill>
376/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
377///
378/// %reg1034 is not considered to be killed, since it is copied from a
379/// register which is not killed. Treating it as not killed lets the
380/// normal heuristics commute the (two-address) add, which lets
381/// coalescing eliminate the extra copy.
382///
383static bool isKilled(MachineInstr &MI, unsigned Reg,
384 const MachineRegisterInfo *MRI,
385 const TargetInstrInfo *TII) {
386 MachineInstr *DefMI = &MI;
387 for (;;) {
388 if (!DefMI->killsRegister(Reg))
389 return false;
390 if (TargetRegisterInfo::isPhysicalRegister(Reg))
391 return true;
392 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
393 // If there are multiple defs, we can't do a simple analysis, so just
394 // go with what the kill flag says.
395 if (next(Begin) != MRI->def_end())
396 return true;
397 DefMI = &*Begin;
398 bool IsSrcPhys, IsDstPhys;
399 unsigned SrcReg, DstReg;
400 // If the def is something other than a copy, then it isn't going to
401 // be coalesced, so follow the kill flag.
402 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
403 return true;
404 Reg = SrcReg;
405 }
406}
407
Evan Cheng870b8072009-03-01 02:03:43 +0000408/// isTwoAddrUse - Return true if the specified MI uses the specified register
409/// as a two-address use. If so, return the destination register by reference.
410static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
411 const TargetInstrDesc &TID = MI.getDesc();
Evan Chenge6f350d2009-03-30 21:34:07 +0000412 unsigned NumOps = (MI.getOpcode() == TargetInstrInfo::INLINEASM)
413 ? MI.getNumOperands() : TID.getNumOperands();
414 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000415 const MachineOperand &MO = MI.getOperand(i);
416 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
417 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000418 unsigned ti;
419 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000420 DstReg = MI.getOperand(ti).getReg();
421 return true;
422 }
423 }
424 return false;
425}
426
427/// findOnlyInterestingUse - Given a register, if has a single in-basic block
428/// use, return the use instruction if it's a copy or a two-address use.
429static
430MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
431 MachineRegisterInfo *MRI,
432 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000433 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000434 unsigned &DstReg, bool &IsDstPhys) {
435 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
436 if (UI == MRI->use_end())
437 return 0;
438 MachineInstr &UseMI = *UI;
439 if (++UI != MRI->use_end())
440 // More than one use.
441 return 0;
442 if (UseMI.getParent() != MBB)
443 return 0;
444 unsigned SrcReg;
445 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000446 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
447 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000448 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000449 }
Evan Cheng870b8072009-03-01 02:03:43 +0000450 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000451 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
452 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000453 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000454 }
Evan Cheng870b8072009-03-01 02:03:43 +0000455 return 0;
456}
457
458/// getMappedReg - Return the physical register the specified virtual register
459/// might be mapped to.
460static unsigned
461getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
462 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
463 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
464 if (SI == RegMap.end())
465 return 0;
466 Reg = SI->second;
467 }
468 if (TargetRegisterInfo::isPhysicalRegister(Reg))
469 return Reg;
470 return 0;
471}
472
473/// regsAreCompatible - Return true if the two registers are equal or aliased.
474///
475static bool
476regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
477 if (RegA == RegB)
478 return true;
479 if (!RegA || !RegB)
480 return false;
481 return TRI->regsOverlap(RegA, RegB);
482}
483
484
Evan Chengd498c8f2009-01-25 03:53:59 +0000485/// isProfitableToReMat - Return true if it's potentially profitable to commute
486/// the two-address instruction that's being processed.
487bool
488TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000489 MachineInstr *MI, MachineBasicBlock *MBB,
490 unsigned Dist) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000491 // Determine if it's profitable to commute this two address instruction. In
492 // general, we want no uses between this instruction and the definition of
493 // the two-address register.
494 // e.g.
495 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
496 // %reg1029<def> = MOV8rr %reg1028
497 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
498 // insert => %reg1030<def> = MOV8rr %reg1028
499 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
500 // In this case, it might not be possible to coalesce the second MOV8rr
501 // instruction if the first one is coalesced. So it would be profitable to
502 // commute it:
503 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
504 // %reg1029<def> = MOV8rr %reg1028
505 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
506 // insert => %reg1030<def> = MOV8rr %reg1029
507 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
508
509 if (!MI->killsRegister(regC))
510 return false;
511
512 // Ok, we have something like:
513 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
514 // let's see if it's worth commuting it.
515
Evan Cheng870b8072009-03-01 02:03:43 +0000516 // Look for situations like this:
517 // %reg1024<def> = MOV r1
518 // %reg1025<def> = MOV r0
519 // %reg1026<def> = ADD %reg1024, %reg1025
520 // r0 = MOV %reg1026
521 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
522 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
523 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
524 unsigned ToRegB = getMappedReg(regB, DstRegMap);
525 unsigned ToRegC = getMappedReg(regC, DstRegMap);
526 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
527 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
528 regsAreCompatible(FromRegC, ToRegB, TRI)))
529 return true;
530
Evan Chengd498c8f2009-01-25 03:53:59 +0000531 // If there is a use of regC between its last def (could be livein) and this
532 // instruction, then bail.
533 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000534 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000535 return false;
536
537 // If there is a use of regB between its last def (could be livein) and this
538 // instruction, then go ahead and make this transformation.
539 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000540 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000541 return true;
542
543 // Since there are no intervening uses for both registers, then commute
544 // if the def of regC is closer. Its live interval is shorter.
545 return LastDefB && LastDefC && LastDefC > LastDefB;
546}
547
Evan Cheng81913712009-01-23 23:27:33 +0000548/// CommuteInstruction - Commute a two-address instruction and update the basic
549/// block, distance map, and live variables if needed. Return true if it is
550/// successful.
551bool
552TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000553 MachineFunction::iterator &mbbi,
554 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000555 MachineInstr *MI = mi;
556 DOUT << "2addr: COMMUTING : " << *MI;
557 MachineInstr *NewMI = TII->commuteInstruction(MI);
558
559 if (NewMI == 0) {
560 DOUT << "2addr: COMMUTING FAILED!\n";
561 return false;
562 }
563
564 DOUT << "2addr: COMMUTED TO: " << *NewMI;
565 // If the instruction changed to commute it, update livevar.
566 if (NewMI != MI) {
567 if (LV)
568 // Update live variables
569 LV->replaceKillInstruction(RegC, MI, NewMI);
570
571 mbbi->insert(mi, NewMI); // Insert the new inst
572 mbbi->erase(mi); // Nuke the old inst.
573 mi = NewMI;
574 DistanceMap.insert(std::make_pair(NewMI, Dist));
575 }
Evan Cheng870b8072009-03-01 02:03:43 +0000576
577 // Update source register map.
578 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
579 if (FromRegC) {
580 unsigned RegA = MI->getOperand(0).getReg();
581 SrcRegMap[RegA] = FromRegC;
582 }
583
Evan Cheng81913712009-01-23 23:27:33 +0000584 return true;
585}
586
Evan Chenge6f350d2009-03-30 21:34:07 +0000587/// isProfitableToConv3Addr - Return true if it is profitable to convert the
588/// given 2-address instruction to a 3-address one.
589bool
590TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
591 // Look for situations like this:
592 // %reg1024<def> = MOV r1
593 // %reg1025<def> = MOV r0
594 // %reg1026<def> = ADD %reg1024, %reg1025
595 // r2 = MOV %reg1026
596 // Turn ADD into a 3-address instruction to avoid a copy.
597 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
598 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
599 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
600}
601
602/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
603/// three address one. Return true if this transformation was successful.
604bool
605TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
606 MachineBasicBlock::iterator &nmi,
607 MachineFunction::iterator &mbbi,
608 unsigned RegB, unsigned Dist) {
609 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
610 if (NewMI) {
611 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
612 DOUT << "2addr: TO 3-ADDR: " << *NewMI;
613 bool Sunk = false;
614
615 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
616 // FIXME: Temporary workaround. If the new instruction doesn't
617 // uses RegB, convertToThreeAddress must have created more
618 // then one instruction.
619 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
620
621 mbbi->erase(mi); // Nuke the old inst.
622
623 if (!Sunk) {
624 DistanceMap.insert(std::make_pair(NewMI, Dist));
625 mi = NewMI;
626 nmi = next(mi);
627 }
628 return true;
629 }
630
631 return false;
632}
633
Evan Cheng870b8072009-03-01 02:03:43 +0000634/// ProcessCopy - If the specified instruction is not yet processed, process it
635/// if it's a copy. For a copy instruction, we find the physical registers the
636/// source and destination registers might be mapped to. These are kept in
637/// point-to maps used to determine future optimizations. e.g.
638/// v1024 = mov r0
639/// v1025 = mov r1
640/// v1026 = add v1024, v1025
641/// r1 = mov r1026
642/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
643/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
644/// potentially joined with r1 on the output side. It's worthwhile to commute
645/// 'add' to eliminate a copy.
646void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
647 MachineBasicBlock *MBB,
648 SmallPtrSet<MachineInstr*, 8> &Processed) {
649 if (Processed.count(MI))
650 return;
651
652 bool IsSrcPhys, IsDstPhys;
653 unsigned SrcReg, DstReg;
654 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
655 return;
656
657 if (IsDstPhys && !IsSrcPhys)
658 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
659 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000660 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
661 if (!isNew)
662 assert(SrcRegMap[DstReg] == SrcReg &&
663 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000664
665 SmallVector<unsigned, 4> VirtRegPairs;
Evan Cheng87d696a2009-04-14 00:32:25 +0000666 bool IsCopy = false;
Evan Cheng870b8072009-03-01 02:03:43 +0000667 unsigned NewReg = 0;
668 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000669 IsCopy, NewReg, IsDstPhys)) {
670 if (IsCopy) {
671 if (!Processed.insert(UseMI))
Evan Cheng870b8072009-03-01 02:03:43 +0000672 break;
673 }
674
675 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
676 if (DI != DistanceMap.end())
677 // Earlier in the same MBB.Reached via a back edge.
678 break;
679
680 if (IsDstPhys) {
681 VirtRegPairs.push_back(NewReg);
682 break;
683 }
684 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000685 if (!isNew)
Evan Cheng87d696a2009-04-14 00:32:25 +0000686 assert(SrcRegMap[NewReg] == DstReg &&
687 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000688 VirtRegPairs.push_back(NewReg);
689 DstReg = NewReg;
690 }
691
692 if (!VirtRegPairs.empty()) {
693 unsigned ToReg = VirtRegPairs.back();
694 VirtRegPairs.pop_back();
695 while (!VirtRegPairs.empty()) {
696 unsigned FromReg = VirtRegPairs.back();
697 VirtRegPairs.pop_back();
698 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000699 if (!isNew)
700 assert(DstRegMap[FromReg] == ToReg &&
701 "Can't map to two dst physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000702 ToReg = FromReg;
703 }
704 }
705 }
706
707 Processed.insert(MI);
708}
709
Evan Cheng28c7ce32009-02-21 03:14:25 +0000710/// isSafeToDelete - If the specified instruction does not produce any side
711/// effects and all of its defs are dead, then it's safe to delete.
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000712static bool isSafeToDelete(MachineInstr *MI, unsigned Reg,
713 const TargetInstrInfo *TII,
714 SmallVector<unsigned, 4> &Kills) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000715 const TargetInstrDesc &TID = MI->getDesc();
716 if (TID.mayStore() || TID.isCall())
717 return false;
718 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
719 return false;
720
721 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
722 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000723 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000724 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000725 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000726 return false;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000727 if (MO.isUse() && MO.getReg() != Reg && MO.isKill())
728 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000729 }
730
731 return true;
732}
733
Bill Wendling637980e2008-05-10 00:12:52 +0000734/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000735///
Chris Lattner163c1e72004-01-31 21:14:04 +0000736bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlinga09362e2006-11-28 22:48:48 +0000737 DOUT << "Machine Function\n";
Misha Brukman75fa4e42004-07-22 15:26:23 +0000738 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +0000739 MRI = &MF.getRegInfo();
740 TII = TM.getInstrInfo();
741 TRI = TM.getRegisterInfo();
Duncan Sands1465d612009-01-28 13:14:17 +0000742 LV = getAnalysisIfAvailable<LiveVariables>();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000743
Misha Brukman75fa4e42004-07-22 15:26:23 +0000744 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000745
Bill Wendlinga09362e2006-11-28 22:48:48 +0000746 DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
747 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +0000748
Evan Cheng7543e582008-06-18 07:49:14 +0000749 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
750 BitVector ReMatRegs;
751 ReMatRegs.resize(MRI->getLastVirtReg()+1);
752
Evan Cheng870b8072009-03-01 02:03:43 +0000753 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +0000754 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
755 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +0000756 unsigned Dist = 0;
757 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +0000758 SrcRegMap.clear();
759 DstRegMap.clear();
760 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +0000761 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +0000762 mi != me; ) {
763 MachineBasicBlock::iterator nmi = next(mi);
Chris Lattner749c6f62008-01-07 07:27:27 +0000764 const TargetInstrDesc &TID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +0000765 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +0000766
Evan Cheng7543e582008-06-18 07:49:14 +0000767 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +0000768
769 ProcessCopy(&*mi, &*mbbi, Processed);
770
Evan Chengfb112882009-03-23 08:01:15 +0000771 unsigned NumOps = (mi->getOpcode() == TargetInstrInfo::INLINEASM)
772 ? mi->getNumOperands() : TID.getNumOperands();
773 for (unsigned si = 0; si < NumOps; ++si) {
Evan Chenga24752f2009-03-19 20:30:06 +0000774 unsigned ti = 0;
775 if (!mi->isRegTiedToDefOperand(si, &ti))
Evan Cheng360c2dd2006-11-01 23:06:55 +0000776 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000777
Evan Cheng360c2dd2006-11-01 23:06:55 +0000778 if (FirstTied) {
779 ++NumTwoAddressInstrs;
Bill Wendlingbcd24982006-12-07 20:28:15 +0000780 DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
Evan Cheng360c2dd2006-11-01 23:06:55 +0000781 }
Bill Wendling637980e2008-05-10 00:12:52 +0000782
Evan Cheng360c2dd2006-11-01 23:06:55 +0000783 FirstTied = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000784
Dan Gohmand735b802008-10-03 15:45:36 +0000785 assert(mi->getOperand(si).isReg() && mi->getOperand(si).getReg() &&
Evan Cheng360c2dd2006-11-01 23:06:55 +0000786 mi->getOperand(si).isUse() && "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000787
Bill Wendling637980e2008-05-10 00:12:52 +0000788 // If the two operands are the same we just remove the use
Evan Cheng360c2dd2006-11-01 23:06:55 +0000789 // and mark the def as def&use, otherwise we have to insert a copy.
790 if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
Bill Wendling637980e2008-05-10 00:12:52 +0000791 // Rewrite:
Evan Cheng360c2dd2006-11-01 23:06:55 +0000792 // a = b op c
793 // to:
794 // a = b
795 // a = a op c
796 unsigned regA = mi->getOperand(ti).getReg();
797 unsigned regB = mi->getOperand(si).getReg();
798
Evan Chengfb112882009-03-23 08:01:15 +0000799 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
Evan Cheng360c2dd2006-11-01 23:06:55 +0000800 "cannot update physical register live information");
Chris Lattner6b507672004-01-31 21:21:43 +0000801
Chris Lattner1e313632004-07-21 23:17:57 +0000802#ifndef NDEBUG
Evan Cheng360c2dd2006-11-01 23:06:55 +0000803 // First, verify that we don't have a use of a in the instruction (a =
804 // b + a for example) because our transformation will not work. This
805 // should never occur because we are in SSA form.
806 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
Evan Chenga24752f2009-03-19 20:30:06 +0000807 assert(i == ti ||
Dan Gohmand735b802008-10-03 15:45:36 +0000808 !mi->getOperand(i).isReg() ||
Evan Cheng360c2dd2006-11-01 23:06:55 +0000809 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +0000810#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +0000811
Evan Cheng360c2dd2006-11-01 23:06:55 +0000812 // If this instruction is not the killing user of B, see if we can
813 // rearrange the code to make it so. Making it the killing user will
814 // allow us to coalesce A and B together, eliminating the copy we are
815 // about to insert.
Dan Gohman97121ba2009-04-08 00:15:30 +0000816 if (!isKilled(*mi, regB, MRI, TII)) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000817 // If regA is dead and the instruction can be deleted, just delete
818 // it so it doesn't clobber regB.
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000819 SmallVector<unsigned, 4> Kills;
820 if (mi->getOperand(ti).isDead() &&
821 isSafeToDelete(mi, regB, TII, Kills)) {
822 SmallVector<std::pair<std::pair<unsigned, bool>
823 ,MachineInstr*>, 4> NewKills;
824 bool ReallySafe = true;
825 // If this instruction kills some virtual registers, we need
826 // update the kill information. If it's not possible to do so,
827 // then bail out.
828 while (!Kills.empty()) {
829 unsigned Kill = Kills.back();
830 Kills.pop_back();
831 if (TargetRegisterInfo::isPhysicalRegister(Kill)) {
832 ReallySafe = false;
833 break;
834 }
835 MachineInstr *LastKill = FindLastUseInMBB(Kill, &*mbbi, Dist);
836 if (LastKill) {
837 bool isModRef = LastKill->modifiesRegister(Kill);
838 NewKills.push_back(std::make_pair(std::make_pair(Kill,isModRef),
839 LastKill));
840 } else {
841 ReallySafe = false;
842 break;
843 }
844 }
845
846 if (ReallySafe) {
847 if (LV) {
848 while (!NewKills.empty()) {
849 MachineInstr *NewKill = NewKills.back().second;
850 unsigned Kill = NewKills.back().first.first;
851 bool isDead = NewKills.back().first.second;
852 NewKills.pop_back();
853 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
854 if (isDead)
855 LV->addVirtualRegisterDead(Kill, NewKill);
856 else
857 LV->addVirtualRegisterKilled(Kill, NewKill);
858 }
859 }
860 }
Lang Hames60dc7342009-05-13 04:18:47 +0000861
862 // We're really going to nuke the old inst. If regB was marked
863 // as a kill we need to update its Kills list.
864 if (mi->getOperand(si).isKill())
865 LV->removeVirtualRegisterKilled(regB, mi);
866
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000867 mbbi->erase(mi); // Nuke the old inst.
868 mi = nmi;
869 ++NumDeletes;
870 break; // Done with this instruction.
871 }
Evan Cheng28c7ce32009-02-21 03:14:25 +0000872 }
873
Evan Cheng360c2dd2006-11-01 23:06:55 +0000874 // If this instruction is commutative, check to see if C dies. If
875 // so, swap the B and C operands. This makes the live ranges of A
876 // and C joinable.
877 // FIXME: This code also works for A := B op C instructions.
Chris Lattner749c6f62008-01-07 07:27:27 +0000878 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
Dan Gohmand735b802008-10-03 15:45:36 +0000879 assert(mi->getOperand(3-si).isReg() &&
Evan Cheng360c2dd2006-11-01 23:06:55 +0000880 "Not a proper commutative instruction!");
881 unsigned regC = mi->getOperand(3-si).getReg();
Dan Gohman97121ba2009-04-08 00:15:30 +0000882 if (isKilled(*mi, regC, MRI, TII)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000883 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
Evan Cheng360c2dd2006-11-01 23:06:55 +0000884 ++NumCommuted;
885 regB = regC;
886 goto InstructionRearranged;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000887 }
Chris Lattnerc71d6942005-01-19 07:08:42 +0000888 }
Chris Lattnercfa0f2e2005-01-02 02:34:12 +0000889 }
Evan Cheng360c2dd2006-11-01 23:06:55 +0000890
891 // If this instruction is potentially convertible to a true
892 // three-address instruction,
Chris Lattner749c6f62008-01-07 07:27:27 +0000893 if (TID.isConvertibleTo3Addr()) {
Evan Cheng360c2dd2006-11-01 23:06:55 +0000894 // FIXME: This assumes there are no more operands which are tied
895 // to another register.
896#ifndef NDEBUG
Bill Wendling637980e2008-05-10 00:12:52 +0000897 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
Chris Lattner749c6f62008-01-07 07:27:27 +0000898 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
Evan Cheng360c2dd2006-11-01 23:06:55 +0000899#endif
900
Evan Chenge6f350d2009-03-30 21:34:07 +0000901 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
Evan Cheng360c2dd2006-11-01 23:06:55 +0000902 ++NumConvertedTo3Addr;
Bill Wendling637980e2008-05-10 00:12:52 +0000903 break; // Done with this instruction.
Evan Cheng360c2dd2006-11-01 23:06:55 +0000904 }
Evan Chengb9d5e7c2007-10-20 04:01:47 +0000905 }
Chris Lattnercfa0f2e2005-01-02 02:34:12 +0000906 }
Evan Cheng360c2dd2006-11-01 23:06:55 +0000907
Evan Chengd498c8f2009-01-25 03:53:59 +0000908 // If it's profitable to commute the instruction, do so.
909 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
910 unsigned regC = mi->getOperand(3-si).getReg();
Evan Cheng870b8072009-03-01 02:03:43 +0000911 if (isProfitableToCommute(regB, regC, mi, mbbi, Dist))
912 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000913 ++NumAggrCommuted;
914 ++NumCommuted;
915 regB = regC;
Evan Chenge6f350d2009-03-30 21:34:07 +0000916 goto InstructionRearranged;
Evan Chengd498c8f2009-01-25 03:53:59 +0000917 }
918 }
919
Evan Chenge6f350d2009-03-30 21:34:07 +0000920 // If it's profitable to convert the 2-address instruction to a
921 // 3-address one, do so.
922 if (TID.isConvertibleTo3Addr() && isProfitableToConv3Addr(regA)) {
923 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
924 ++NumConvertedTo3Addr;
925 break; // Done with this instruction.
926 }
927 }
928
Evan Cheng360c2dd2006-11-01 23:06:55 +0000929 InstructionRearranged:
Evan Chengfb112882009-03-23 08:01:15 +0000930 const TargetRegisterClass* rc = MRI->getRegClass(regB);
Evan Cheng7543e582008-06-18 07:49:14 +0000931 MachineInstr *DefMI = MRI->getVRegDef(regB);
932 // If it's safe and profitable, remat the definition instead of
933 // copying it.
Evan Cheng601ca4b2008-06-25 01:16:38 +0000934 if (DefMI &&
Evan Cheng8763c1c2008-08-27 20:58:54 +0000935 DefMI->getDesc().isAsCheapAsAMove() &&
Evan Chengdf3b9932008-08-27 20:33:50 +0000936 DefMI->isSafeToReMat(TII, regB) &&
Evan Cheng870b8072009-03-01 02:03:43 +0000937 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
Evan Cheng7543e582008-06-18 07:49:14 +0000938 DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
939 TII->reMaterialize(*mbbi, mi, regA, DefMI);
940 ReMatRegs.set(regB);
941 ++NumReMats;
Bill Wendling48f7f232008-05-26 05:18:34 +0000942 } else {
Dan Gohman6ed0e202009-04-13 15:16:56 +0000943 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
Mike Stump1e8f0722009-05-08 22:53:06 +0000944 (void)Emitted;
Dan Gohman6ed0e202009-04-13 15:16:56 +0000945 assert(Emitted && "Unable to issue a copy instruction!\n");
Bill Wendling48f7f232008-05-26 05:18:34 +0000946 }
Evan Cheng360c2dd2006-11-01 23:06:55 +0000947
Evan Chengd498c8f2009-01-25 03:53:59 +0000948 MachineBasicBlock::iterator prevMI = prior(mi);
949 // Update DistanceMap.
950 DistanceMap.insert(std::make_pair(prevMI, Dist));
951 DistanceMap[mi] = ++Dist;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000952
Bill Wendling637980e2008-05-10 00:12:52 +0000953 // Update live variables for regB.
Owen Anderson802af112008-07-02 21:28:58 +0000954 if (LV) {
955 LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
Bill Wendling637980e2008-05-10 00:12:52 +0000956
Owen Anderson802af112008-07-02 21:28:58 +0000957 // regB is used in this BB.
958 varInfoB.UsedBlocks[mbbi->getNumber()] = true;
Bill Wendling637980e2008-05-10 00:12:52 +0000959
Evan Cheng9f1c8312008-07-03 09:09:37 +0000960 if (LV->removeVirtualRegisterKilled(regB, mi))
Evan Chengd498c8f2009-01-25 03:53:59 +0000961 LV->addVirtualRegisterKilled(regB, prevMI);
Evan Cheng360c2dd2006-11-01 23:06:55 +0000962
Evan Cheng9f1c8312008-07-03 09:09:37 +0000963 if (LV->removeVirtualRegisterDead(regB, mi))
Evan Chengd498c8f2009-01-25 03:53:59 +0000964 LV->addVirtualRegisterDead(regB, prevMI);
Owen Anderson802af112008-07-02 21:28:58 +0000965 }
Dan Gohman2d9716f2008-11-12 17:15:19 +0000966
Evan Chengd498c8f2009-01-25 03:53:59 +0000967 DOUT << "\t\tprepend:\t"; DEBUG(prevMI->print(*cerr.stream(), &TM));
Owen Anderson802af112008-07-02 21:28:58 +0000968
Bill Wendling637980e2008-05-10 00:12:52 +0000969 // Replace all occurences of regB with regA.
Evan Cheng360c2dd2006-11-01 23:06:55 +0000970 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
Dan Gohmand735b802008-10-03 15:45:36 +0000971 if (mi->getOperand(i).isReg() &&
Evan Cheng360c2dd2006-11-01 23:06:55 +0000972 mi->getOperand(i).getReg() == regB)
973 mi->getOperand(i).setReg(regA);
974 }
Chris Lattnercfa0f2e2005-01-02 02:34:12 +0000975 }
Alkis Evlogimenos14be6402004-02-04 22:17:40 +0000976
Evan Cheng360c2dd2006-11-01 23:06:55 +0000977 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
978 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
979 MadeChange = true;
Alkis Evlogimenos14be6402004-02-04 22:17:40 +0000980
Bill Wendlingbcd24982006-12-07 20:28:15 +0000981 DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
Misha Brukman75fa4e42004-07-22 15:26:23 +0000982 }
Bill Wendling637980e2008-05-10 00:12:52 +0000983
Evan Cheng7a963fa2008-03-27 01:27:25 +0000984 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +0000985 }
986 }
987
Evan Cheng601ca4b2008-06-25 01:16:38 +0000988 // Some remat'ed instructions are dead.
989 int VReg = ReMatRegs.find_first();
990 while (VReg != -1) {
991 if (MRI->use_empty(VReg)) {
992 MachineInstr *DefMI = MRI->getVRegDef(VReg);
993 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +0000994 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000995 VReg = ReMatRegs.find_next(VReg);
Bill Wendling48f7f232008-05-26 05:18:34 +0000996 }
997
Misha Brukman75fa4e42004-07-22 15:26:23 +0000998 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000999}