blob: 6144ecd002e3d88b11e016786c6e0971ea5f8225 [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"
Bob Wilson852a7e32010-06-15 05:56:31 +000036#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000037#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmana70dca12009-10-09 23:27:56 +000038#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000039#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000040#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000042#include "llvm/Target/TargetOptions.h"
Evan Cheng875357d2008-03-13 06:37:55 +000043#include "llvm/Support/Debug.h"
Evan Cheng3d720fb2010-05-05 18:45:40 +000044#include "llvm/Support/ErrorHandling.h"
Evan Cheng7543e582008-06-18 07:49:14 +000045#include "llvm/ADT/BitVector.h"
46#include "llvm/ADT/DenseMap.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000047#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000048#include "llvm/ADT/Statistic.h"
49#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000050using namespace llvm;
51
Chris Lattnercd3245a2006-12-19 22:41:21 +000052STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
53STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengd498c8f2009-01-25 03:53:59 +000054STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattnercd3245a2006-12-19 22:41:21 +000055STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng875357d2008-03-13 06:37:55 +000056STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng7543e582008-06-18 07:49:14 +000057STATISTIC(NumReMats, "Number of instructions re-materialized");
Evan Cheng28c7ce32009-02-21 03:14:25 +000058STATISTIC(NumDeletes, "Number of dead instructions deleted");
Evan Cheng875357d2008-03-13 06:37:55 +000059
60namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000061 class TwoAddressInstructionPass : public MachineFunctionPass {
Evan Cheng875357d2008-03-13 06:37:55 +000062 const TargetInstrInfo *TII;
63 const TargetRegisterInfo *TRI;
64 MachineRegisterInfo *MRI;
65 LiveVariables *LV;
Dan Gohmana70dca12009-10-09 23:27:56 +000066 AliasAnalysis *AA;
Evan Cheng875357d2008-03-13 06:37:55 +000067
Evan Cheng870b8072009-03-01 02:03:43 +000068 // DistanceMap - Keep track the distance of a MI from the start of the
69 // current basic block.
70 DenseMap<MachineInstr*, unsigned> DistanceMap;
71
72 // SrcRegMap - A map from virtual registers to physical registers which
73 // are likely targets to be coalesced to due to copies from physical
74 // registers to virtual registers. e.g. v1024 = move r0.
75 DenseMap<unsigned, unsigned> SrcRegMap;
76
77 // DstRegMap - A map from virtual registers to physical registers which
78 // are likely targets to be coalesced to due to copies to physical
79 // registers from virtual registers. e.g. r1 = move v1024.
80 DenseMap<unsigned, unsigned> DstRegMap;
81
Evan Cheng3d720fb2010-05-05 18:45:40 +000082 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
83 /// during the initial walk of the machine function.
84 SmallVector<MachineInstr*, 16> RegSequences;
85
Bill Wendling637980e2008-05-10 00:12:52 +000086 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
87 unsigned Reg,
88 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000089
Evan Cheng7543e582008-06-18 07:49:14 +000090 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
Evan Cheng601ca4b2008-06-25 01:16:38 +000091 MachineInstr *MI, MachineInstr *DefMI,
Evan Cheng870b8072009-03-01 02:03:43 +000092 MachineBasicBlock *MBB, unsigned Loc);
Evan Cheng81913712009-01-23 23:27:33 +000093
Evan Chengd498c8f2009-01-25 03:53:59 +000094 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
Evan Chengd498c8f2009-01-25 03:53:59 +000095 unsigned &LastDef);
96
Evan Chenge9ccb3a2009-04-28 02:12:36 +000097 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
98 unsigned Dist);
99
Evan Chengd498c8f2009-01-25 03:53:59 +0000100 bool isProfitableToCommute(unsigned regB, unsigned regC,
101 MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng870b8072009-03-01 02:03:43 +0000102 unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +0000103
Evan Cheng81913712009-01-23 23:27:33 +0000104 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
105 MachineFunction::iterator &mbbi,
Evan Cheng870b8072009-03-01 02:03:43 +0000106 unsigned RegB, unsigned RegC, unsigned Dist);
107
Evan Chenge6f350d2009-03-30 21:34:07 +0000108 bool isProfitableToConv3Addr(unsigned RegA);
109
110 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
111 MachineBasicBlock::iterator &nmi,
112 MachineFunction::iterator &mbbi,
113 unsigned RegB, unsigned Dist);
114
Bob Wilson326f4382009-09-01 22:51:08 +0000115 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
116 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
117 SmallVector<NewKill, 4> &NewKills,
118 MachineBasicBlock *MBB, unsigned Dist);
119 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
120 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000121 MachineFunction::iterator &mbbi, unsigned Dist);
Bob Wilson326f4382009-09-01 22:51:08 +0000122
Bob Wilsoncc80df92009-09-03 20:58:42 +0000123 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
124 MachineBasicBlock::iterator &nmi,
125 MachineFunction::iterator &mbbi,
126 unsigned SrcIdx, unsigned DstIdx,
127 unsigned Dist);
128
Evan Cheng870b8072009-03-01 02:03:43 +0000129 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
130 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000131
Evan Cheng53c779b2010-05-17 20:57:12 +0000132 void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
133
Evan Cheng3d720fb2010-05-05 18:45:40 +0000134 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
135 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
136 /// sub-register references of the register defined by REG_SEQUENCE.
137 bool EliminateRegSequences();
Evan Chengc6dcce32010-05-17 23:24:12 +0000138
Evan Cheng875357d2008-03-13 06:37:55 +0000139 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000140 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000141 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000142
Bill Wendling637980e2008-05-10 00:12:52 +0000143 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000144 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +0000145 AU.addRequired<AliasAnalysis>();
Bill Wendling637980e2008-05-10 00:12:52 +0000146 AU.addPreserved<LiveVariables>();
147 AU.addPreservedID(MachineLoopInfoID);
148 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +0000149 if (StrongPHIElim)
150 AU.addPreservedID(StrongPHIEliminationID);
151 else
152 AU.addPreservedID(PHIEliminationID);
Bill Wendling637980e2008-05-10 00:12:52 +0000153 MachineFunctionPass::getAnalysisUsage(AU);
154 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000155
Bill Wendling637980e2008-05-10 00:12:52 +0000156 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000157 bool runOnMachineFunction(MachineFunction&);
158 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000159}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000160
Dan Gohman844731a2008-05-13 00:00:25 +0000161char TwoAddressInstructionPass::ID = 0;
162static RegisterPass<TwoAddressInstructionPass>
163X("twoaddressinstruction", "Two-Address instruction pass");
164
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000165const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000166
Evan Cheng875357d2008-03-13 06:37:55 +0000167/// Sink3AddrInstruction - A two-address instruction has been converted to a
168/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000169/// past the instruction that would kill the above mentioned register to reduce
170/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000171bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
172 MachineInstr *MI, unsigned SavedReg,
173 MachineBasicBlock::iterator OldPos) {
174 // Check if it's safe to move this instruction.
175 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000176 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000177 return false;
178
179 unsigned DefReg = 0;
180 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000181
Evan Cheng875357d2008-03-13 06:37:55 +0000182 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
183 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000184 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000185 continue;
186 unsigned MOReg = MO.getReg();
187 if (!MOReg)
188 continue;
189 if (MO.isUse() && MOReg != SavedReg)
190 UseRegs.insert(MO.getReg());
191 if (!MO.isDef())
192 continue;
193 if (MO.isImplicit())
194 // Don't try to move it if it implicitly defines a register.
195 return false;
196 if (DefReg)
197 // For now, don't move any instructions that define multiple registers.
198 return false;
199 DefReg = MO.getReg();
200 }
201
202 // Find the instruction that kills SavedReg.
203 MachineInstr *KillMI = NULL;
Evan Chengf1250ee2010-03-23 20:36:12 +0000204 for (MachineRegisterInfo::use_nodbg_iterator
205 UI = MRI->use_nodbg_begin(SavedReg),
206 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng875357d2008-03-13 06:37:55 +0000207 MachineOperand &UseMO = UI.getOperand();
208 if (!UseMO.isKill())
209 continue;
210 KillMI = UseMO.getParent();
211 break;
212 }
Bill Wendling637980e2008-05-10 00:12:52 +0000213
Dan Gohman97121ba2009-04-08 00:15:30 +0000214 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
Evan Cheng875357d2008-03-13 06:37:55 +0000215 return false;
216
Bill Wendling637980e2008-05-10 00:12:52 +0000217 // If any of the definitions are used by another instruction between the
218 // position and the kill use, then it's not safe to sink it.
219 //
220 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000221 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000222 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000223 MachineOperand *KillMO = NULL;
224 MachineBasicBlock::iterator KillPos = KillMI;
225 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000226
Evan Cheng7543e582008-06-18 07:49:14 +0000227 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000228 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000229 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000230 // DBG_VALUE cannot be counted against the limit.
231 if (OtherMI->isDebugValue())
232 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000233 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
234 return false;
235 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000236 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
237 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000238 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000239 continue;
240 unsigned MOReg = MO.getReg();
241 if (!MOReg)
242 continue;
243 if (DefReg == MOReg)
244 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000245
Evan Cheng875357d2008-03-13 06:37:55 +0000246 if (MO.isKill()) {
247 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000248 // Save the operand that kills the register. We want to unset the kill
249 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000250 KillMO = &MO;
251 else if (UseRegs.count(MOReg))
252 // One of the uses is killed before the destination.
253 return false;
254 }
255 }
256 }
257
Evan Cheng875357d2008-03-13 06:37:55 +0000258 // Update kill and LV information.
259 KillMO->setIsKill(false);
260 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
261 KillMO->setIsKill(true);
Owen Anderson802af112008-07-02 21:28:58 +0000262
Evan Cheng9f1c8312008-07-03 09:09:37 +0000263 if (LV)
264 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000265
266 // Move instruction to its destination.
267 MBB->remove(MI);
268 MBB->insert(KillPos, MI);
269
270 ++Num3AddrSunk;
271 return true;
272}
273
Evan Cheng7543e582008-06-18 07:49:14 +0000274/// isTwoAddrUse - Return true if the specified MI is using the specified
275/// register as a two-address operand.
276static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
277 const TargetInstrDesc &TID = UseMI->getDesc();
278 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
279 MachineOperand &MO = UseMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000280 if (MO.isReg() && MO.getReg() == Reg &&
Evan Chenga24752f2009-03-19 20:30:06 +0000281 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
Evan Cheng7543e582008-06-18 07:49:14 +0000282 // Earlier use is a two-address one.
283 return true;
284 }
285 return false;
286}
287
288/// isProfitableToReMat - Return true if the heuristics determines it is likely
289/// to be profitable to re-materialize the definition of Reg rather than copy
290/// the register.
291bool
292TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000293 const TargetRegisterClass *RC,
294 MachineInstr *MI, MachineInstr *DefMI,
295 MachineBasicBlock *MBB, unsigned Loc) {
Evan Cheng7543e582008-06-18 07:49:14 +0000296 bool OtherUse = false;
Evan Chengf1250ee2010-03-23 20:36:12 +0000297 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg),
298 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng7543e582008-06-18 07:49:14 +0000299 MachineOperand &UseMO = UI.getOperand();
Evan Cheng7543e582008-06-18 07:49:14 +0000300 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng601ca4b2008-06-25 01:16:38 +0000301 MachineBasicBlock *UseMBB = UseMI->getParent();
302 if (UseMBB == MBB) {
303 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
304 if (DI != DistanceMap.end() && DI->second == Loc)
305 continue; // Current use.
306 OtherUse = true;
307 // There is at least one other use in the MBB that will clobber the
308 // register.
309 if (isTwoAddrUse(UseMI, Reg))
310 return true;
311 }
Evan Cheng7543e582008-06-18 07:49:14 +0000312 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000313
314 // If other uses in MBB are not two-address uses, then don't remat.
315 if (OtherUse)
316 return false;
317
318 // No other uses in the same block, remat if it's defined in the same
319 // block so it does not unnecessarily extend the live range.
320 return MBB == DefMI->getParent();
Evan Cheng7543e582008-06-18 07:49:14 +0000321}
322
Evan Chengd498c8f2009-01-25 03:53:59 +0000323/// NoUseAfterLastDef - Return true if there are no intervening uses between the
324/// last instruction in the MBB that defines the specified register and the
325/// two-address instruction which is being processed. It also returns the last
326/// def location by reference
327bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000328 MachineBasicBlock *MBB, unsigned Dist,
329 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000330 LastDef = 0;
331 unsigned LastUse = Dist;
332 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
333 E = MRI->reg_end(); I != E; ++I) {
334 MachineOperand &MO = I.getOperand();
335 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000336 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000337 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000338 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
339 if (DI == DistanceMap.end())
340 continue;
341 if (MO.isUse() && DI->second < LastUse)
342 LastUse = DI->second;
343 if (MO.isDef() && DI->second > LastDef)
344 LastDef = DI->second;
345 }
346
347 return !(LastUse > LastDef && LastUse < Dist);
348}
349
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000350MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
351 MachineBasicBlock *MBB,
352 unsigned Dist) {
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000353 unsigned LastUseDist = 0;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000354 MachineInstr *LastUse = 0;
355 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
356 E = MRI->reg_end(); I != E; ++I) {
357 MachineOperand &MO = I.getOperand();
358 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000359 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000360 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000361 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
362 if (DI == DistanceMap.end())
363 continue;
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000364 if (DI->second >= Dist)
365 continue;
366
367 if (MO.isUse() && DI->second > LastUseDist) {
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000368 LastUse = DI->first;
369 LastUseDist = DI->second;
370 }
371 }
372 return LastUse;
373}
374
Evan Cheng870b8072009-03-01 02:03:43 +0000375/// isCopyToReg - Return true if the specified MI is a copy instruction or
376/// a extract_subreg instruction. It also returns the source and destination
377/// registers and whether they are physical registers by reference.
378static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
379 unsigned &SrcReg, unsigned &DstReg,
380 bool &IsSrcPhys, bool &IsDstPhys) {
381 SrcReg = 0;
382 DstReg = 0;
383 unsigned SrcSubIdx, DstSubIdx;
384 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Chris Lattner518bb532010-02-09 19:54:29 +0000385 if (MI.isExtractSubreg()) {
Evan Cheng870b8072009-03-01 02:03:43 +0000386 DstReg = MI.getOperand(0).getReg();
387 SrcReg = MI.getOperand(1).getReg();
Chris Lattner518bb532010-02-09 19:54:29 +0000388 } else if (MI.isInsertSubreg()) {
Evan Cheng870b8072009-03-01 02:03:43 +0000389 DstReg = MI.getOperand(0).getReg();
390 SrcReg = MI.getOperand(2).getReg();
Chris Lattner518bb532010-02-09 19:54:29 +0000391 } else if (MI.isSubregToReg()) {
Dan Gohman97121ba2009-04-08 00:15:30 +0000392 DstReg = MI.getOperand(0).getReg();
393 SrcReg = MI.getOperand(2).getReg();
Evan Cheng870b8072009-03-01 02:03:43 +0000394 }
395 }
396
397 if (DstReg) {
398 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
399 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
400 return true;
401 }
402 return false;
403}
404
Dan Gohman97121ba2009-04-08 00:15:30 +0000405/// isKilled - Test if the given register value, which is used by the given
406/// instruction, is killed by the given instruction. This looks through
407/// coalescable copies to see if the original value is potentially not killed.
408///
409/// For example, in this code:
410///
411/// %reg1034 = copy %reg1024
412/// %reg1035 = copy %reg1025<kill>
413/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
414///
415/// %reg1034 is not considered to be killed, since it is copied from a
416/// register which is not killed. Treating it as not killed lets the
417/// normal heuristics commute the (two-address) add, which lets
418/// coalescing eliminate the extra copy.
419///
420static bool isKilled(MachineInstr &MI, unsigned Reg,
421 const MachineRegisterInfo *MRI,
422 const TargetInstrInfo *TII) {
423 MachineInstr *DefMI = &MI;
424 for (;;) {
425 if (!DefMI->killsRegister(Reg))
426 return false;
427 if (TargetRegisterInfo::isPhysicalRegister(Reg))
428 return true;
429 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
430 // If there are multiple defs, we can't do a simple analysis, so just
431 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000432 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000433 return true;
434 DefMI = &*Begin;
435 bool IsSrcPhys, IsDstPhys;
436 unsigned SrcReg, DstReg;
437 // If the def is something other than a copy, then it isn't going to
438 // be coalesced, so follow the kill flag.
439 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
440 return true;
441 Reg = SrcReg;
442 }
443}
444
Evan Cheng870b8072009-03-01 02:03:43 +0000445/// isTwoAddrUse - Return true if the specified MI uses the specified register
446/// as a two-address use. If so, return the destination register by reference.
447static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
448 const TargetInstrDesc &TID = MI.getDesc();
Chris Lattner518bb532010-02-09 19:54:29 +0000449 unsigned NumOps = MI.isInlineAsm() ? MI.getNumOperands():TID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000450 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000451 const MachineOperand &MO = MI.getOperand(i);
452 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
453 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000454 unsigned ti;
455 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000456 DstReg = MI.getOperand(ti).getReg();
457 return true;
458 }
459 }
460 return false;
461}
462
463/// findOnlyInterestingUse - Given a register, if has a single in-basic block
464/// use, return the use instruction if it's a copy or a two-address use.
465static
466MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
467 MachineRegisterInfo *MRI,
468 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000469 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000470 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000471 if (!MRI->hasOneNonDBGUse(Reg))
472 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000473 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000474 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000475 if (UseMI.getParent() != MBB)
476 return 0;
477 unsigned SrcReg;
478 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000479 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
480 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000481 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000482 }
Evan Cheng870b8072009-03-01 02:03:43 +0000483 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000484 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
485 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000486 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000487 }
Evan Cheng870b8072009-03-01 02:03:43 +0000488 return 0;
489}
490
491/// getMappedReg - Return the physical register the specified virtual register
492/// might be mapped to.
493static unsigned
494getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
495 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
496 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
497 if (SI == RegMap.end())
498 return 0;
499 Reg = SI->second;
500 }
501 if (TargetRegisterInfo::isPhysicalRegister(Reg))
502 return Reg;
503 return 0;
504}
505
506/// regsAreCompatible - Return true if the two registers are equal or aliased.
507///
508static bool
509regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
510 if (RegA == RegB)
511 return true;
512 if (!RegA || !RegB)
513 return false;
514 return TRI->regsOverlap(RegA, RegB);
515}
516
517
Evan Chengd498c8f2009-01-25 03:53:59 +0000518/// isProfitableToReMat - Return true if it's potentially profitable to commute
519/// the two-address instruction that's being processed.
520bool
521TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000522 MachineInstr *MI, MachineBasicBlock *MBB,
523 unsigned Dist) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000524 // Determine if it's profitable to commute this two address instruction. In
525 // general, we want no uses between this instruction and the definition of
526 // the two-address register.
527 // e.g.
528 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
529 // %reg1029<def> = MOV8rr %reg1028
530 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
531 // insert => %reg1030<def> = MOV8rr %reg1028
532 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
533 // In this case, it might not be possible to coalesce the second MOV8rr
534 // instruction if the first one is coalesced. So it would be profitable to
535 // commute it:
536 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
537 // %reg1029<def> = MOV8rr %reg1028
538 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
539 // insert => %reg1030<def> = MOV8rr %reg1029
540 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
541
542 if (!MI->killsRegister(regC))
543 return false;
544
545 // Ok, we have something like:
546 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
547 // let's see if it's worth commuting it.
548
Evan Cheng870b8072009-03-01 02:03:43 +0000549 // Look for situations like this:
550 // %reg1024<def> = MOV r1
551 // %reg1025<def> = MOV r0
552 // %reg1026<def> = ADD %reg1024, %reg1025
553 // r0 = MOV %reg1026
554 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
555 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
556 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
557 unsigned ToRegB = getMappedReg(regB, DstRegMap);
558 unsigned ToRegC = getMappedReg(regC, DstRegMap);
559 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
560 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
561 regsAreCompatible(FromRegC, ToRegB, TRI)))
562 return true;
563
Evan Chengd498c8f2009-01-25 03:53:59 +0000564 // If there is a use of regC between its last def (could be livein) and this
565 // instruction, then bail.
566 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000567 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000568 return false;
569
570 // If there is a use of regB between its last def (could be livein) and this
571 // instruction, then go ahead and make this transformation.
572 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000573 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000574 return true;
575
576 // Since there are no intervening uses for both registers, then commute
577 // if the def of regC is closer. Its live interval is shorter.
578 return LastDefB && LastDefC && LastDefC > LastDefB;
579}
580
Evan Cheng81913712009-01-23 23:27:33 +0000581/// CommuteInstruction - Commute a two-address instruction and update the basic
582/// block, distance map, and live variables if needed. Return true if it is
583/// successful.
584bool
585TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000586 MachineFunction::iterator &mbbi,
587 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000588 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000589 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000590 MachineInstr *NewMI = TII->commuteInstruction(MI);
591
592 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000593 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000594 return false;
595 }
596
David Greeneeb00b182010-01-05 01:24:21 +0000597 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000598 // If the instruction changed to commute it, update livevar.
599 if (NewMI != MI) {
600 if (LV)
601 // Update live variables
602 LV->replaceKillInstruction(RegC, MI, NewMI);
603
604 mbbi->insert(mi, NewMI); // Insert the new inst
605 mbbi->erase(mi); // Nuke the old inst.
606 mi = NewMI;
607 DistanceMap.insert(std::make_pair(NewMI, Dist));
608 }
Evan Cheng870b8072009-03-01 02:03:43 +0000609
610 // Update source register map.
611 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
612 if (FromRegC) {
613 unsigned RegA = MI->getOperand(0).getReg();
614 SrcRegMap[RegA] = FromRegC;
615 }
616
Evan Cheng81913712009-01-23 23:27:33 +0000617 return true;
618}
619
Evan Chenge6f350d2009-03-30 21:34:07 +0000620/// isProfitableToConv3Addr - Return true if it is profitable to convert the
621/// given 2-address instruction to a 3-address one.
622bool
623TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
624 // Look for situations like this:
625 // %reg1024<def> = MOV r1
626 // %reg1025<def> = MOV r0
627 // %reg1026<def> = ADD %reg1024, %reg1025
628 // r2 = MOV %reg1026
629 // Turn ADD into a 3-address instruction to avoid a copy.
630 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
631 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
632 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
633}
634
635/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
636/// three address one. Return true if this transformation was successful.
637bool
638TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
639 MachineBasicBlock::iterator &nmi,
640 MachineFunction::iterator &mbbi,
641 unsigned RegB, unsigned Dist) {
642 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
643 if (NewMI) {
David Greeneeb00b182010-01-05 01:24:21 +0000644 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
645 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000646 bool Sunk = false;
647
648 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
649 // FIXME: Temporary workaround. If the new instruction doesn't
650 // uses RegB, convertToThreeAddress must have created more
651 // then one instruction.
652 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
653
654 mbbi->erase(mi); // Nuke the old inst.
655
656 if (!Sunk) {
657 DistanceMap.insert(std::make_pair(NewMI, Dist));
658 mi = NewMI;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000659 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000660 }
661 return true;
662 }
663
664 return false;
665}
666
Evan Cheng870b8072009-03-01 02:03:43 +0000667/// ProcessCopy - If the specified instruction is not yet processed, process it
668/// if it's a copy. For a copy instruction, we find the physical registers the
669/// source and destination registers might be mapped to. These are kept in
670/// point-to maps used to determine future optimizations. e.g.
671/// v1024 = mov r0
672/// v1025 = mov r1
673/// v1026 = add v1024, v1025
674/// r1 = mov r1026
675/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
676/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
677/// potentially joined with r1 on the output side. It's worthwhile to commute
678/// 'add' to eliminate a copy.
679void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
680 MachineBasicBlock *MBB,
681 SmallPtrSet<MachineInstr*, 8> &Processed) {
682 if (Processed.count(MI))
683 return;
684
685 bool IsSrcPhys, IsDstPhys;
686 unsigned SrcReg, DstReg;
687 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
688 return;
689
690 if (IsDstPhys && !IsSrcPhys)
691 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
692 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000693 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
694 if (!isNew)
695 assert(SrcRegMap[DstReg] == SrcReg &&
696 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000697
698 SmallVector<unsigned, 4> VirtRegPairs;
Evan Cheng87d696a2009-04-14 00:32:25 +0000699 bool IsCopy = false;
Evan Cheng870b8072009-03-01 02:03:43 +0000700 unsigned NewReg = 0;
701 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000702 IsCopy, NewReg, IsDstPhys)) {
703 if (IsCopy) {
704 if (!Processed.insert(UseMI))
Evan Cheng870b8072009-03-01 02:03:43 +0000705 break;
706 }
707
708 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
709 if (DI != DistanceMap.end())
710 // Earlier in the same MBB.Reached via a back edge.
711 break;
712
713 if (IsDstPhys) {
714 VirtRegPairs.push_back(NewReg);
715 break;
716 }
717 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000718 if (!isNew)
Evan Cheng87d696a2009-04-14 00:32:25 +0000719 assert(SrcRegMap[NewReg] == DstReg &&
720 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000721 VirtRegPairs.push_back(NewReg);
722 DstReg = NewReg;
723 }
724
725 if (!VirtRegPairs.empty()) {
726 unsigned ToReg = VirtRegPairs.back();
727 VirtRegPairs.pop_back();
728 while (!VirtRegPairs.empty()) {
729 unsigned FromReg = VirtRegPairs.back();
730 VirtRegPairs.pop_back();
731 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000732 if (!isNew)
733 assert(DstRegMap[FromReg] == ToReg &&
734 "Can't map to two dst physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000735 ToReg = FromReg;
736 }
737 }
738 }
739
740 Processed.insert(MI);
741}
742
Evan Cheng28c7ce32009-02-21 03:14:25 +0000743/// isSafeToDelete - If the specified instruction does not produce any side
744/// effects and all of its defs are dead, then it's safe to delete.
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000745static bool isSafeToDelete(MachineInstr *MI,
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000746 const TargetInstrInfo *TII,
747 SmallVector<unsigned, 4> &Kills) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000748 const TargetInstrDesc &TID = MI->getDesc();
749 if (TID.mayStore() || TID.isCall())
750 return false;
751 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
752 return false;
753
754 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
755 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000756 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000757 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000758 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000759 return false;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000760 if (MO.isUse() && MO.isKill())
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000761 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000762 }
Evan Cheng28c7ce32009-02-21 03:14:25 +0000763 return true;
764}
765
Bob Wilson326f4382009-09-01 22:51:08 +0000766/// canUpdateDeletedKills - Check if all the registers listed in Kills are
767/// killed by instructions in MBB preceding the current instruction at
768/// position Dist. If so, return true and record information about the
769/// preceding kills in NewKills.
770bool TwoAddressInstructionPass::
771canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
772 SmallVector<NewKill, 4> &NewKills,
773 MachineBasicBlock *MBB, unsigned Dist) {
774 while (!Kills.empty()) {
775 unsigned Kill = Kills.back();
776 Kills.pop_back();
777 if (TargetRegisterInfo::isPhysicalRegister(Kill))
778 return false;
779
780 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
781 if (!LastKill)
782 return false;
783
Evan Cheng1015ba72010-05-21 20:53:24 +0000784 bool isModRef = LastKill->definesRegister(Kill);
Bob Wilson326f4382009-09-01 22:51:08 +0000785 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
786 LastKill));
787 }
788 return true;
789}
790
791/// DeleteUnusedInstr - If an instruction with a tied register operand can
792/// be safely deleted, just delete it.
793bool
794TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
795 MachineBasicBlock::iterator &nmi,
796 MachineFunction::iterator &mbbi,
Bob Wilson326f4382009-09-01 22:51:08 +0000797 unsigned Dist) {
798 // Check if the instruction has no side effects and if all its defs are dead.
799 SmallVector<unsigned, 4> Kills;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000800 if (!isSafeToDelete(mi, TII, Kills))
Bob Wilson326f4382009-09-01 22:51:08 +0000801 return false;
802
803 // If this instruction kills some virtual registers, we need to
804 // update the kill information. If it's not possible to do so,
805 // then bail out.
806 SmallVector<NewKill, 4> NewKills;
807 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
808 return false;
809
810 if (LV) {
811 while (!NewKills.empty()) {
812 MachineInstr *NewKill = NewKills.back().second;
813 unsigned Kill = NewKills.back().first.first;
814 bool isDead = NewKills.back().first.second;
815 NewKills.pop_back();
816 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
817 if (isDead)
818 LV->addVirtualRegisterDead(Kill, NewKill);
819 else
820 LV->addVirtualRegisterKilled(Kill, NewKill);
821 }
822 }
Bob Wilson326f4382009-09-01 22:51:08 +0000823 }
824
825 mbbi->erase(mi); // Nuke the old inst.
826 mi = nmi;
827 return true;
828}
829
Bob Wilsoncc80df92009-09-03 20:58:42 +0000830/// TryInstructionTransform - For the case where an instruction has a single
831/// pair of tied register operands, attempt some transformations that may
832/// either eliminate the tied operands or improve the opportunities for
833/// coalescing away the register copy. Returns true if the tied operands
834/// are eliminated altogether.
835bool TwoAddressInstructionPass::
836TryInstructionTransform(MachineBasicBlock::iterator &mi,
837 MachineBasicBlock::iterator &nmi,
838 MachineFunction::iterator &mbbi,
839 unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
840 const TargetInstrDesc &TID = mi->getDesc();
841 unsigned regA = mi->getOperand(DstIdx).getReg();
842 unsigned regB = mi->getOperand(SrcIdx).getReg();
843
844 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
845 "cannot make instruction into two-address form");
846
847 // If regA is dead and the instruction can be deleted, just delete
848 // it so it doesn't clobber regB.
849 bool regBKilled = isKilled(*mi, regB, MRI, TII);
850 if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000851 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +0000852 ++NumDeletes;
853 return true; // Done with this instruction.
854 }
855
856 // Check if it is profitable to commute the operands.
857 unsigned SrcOp1, SrcOp2;
858 unsigned regC = 0;
859 unsigned regCIdx = ~0U;
860 bool TryCommute = false;
861 bool AggressiveCommute = false;
862 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
863 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
864 if (SrcIdx == SrcOp1)
865 regCIdx = SrcOp2;
866 else if (SrcIdx == SrcOp2)
867 regCIdx = SrcOp1;
868
869 if (regCIdx != ~0U) {
870 regC = mi->getOperand(regCIdx).getReg();
871 if (!regBKilled && isKilled(*mi, regC, MRI, TII))
872 // If C dies but B does not, swap the B and C operands.
873 // This makes the live ranges of A and C joinable.
874 TryCommute = true;
875 else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
876 TryCommute = true;
877 AggressiveCommute = true;
878 }
879 }
880 }
881
882 // If it's profitable to commute, try to do so.
883 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
884 ++NumCommuted;
885 if (AggressiveCommute)
886 ++NumAggrCommuted;
887 return false;
888 }
889
890 if (TID.isConvertibleTo3Addr()) {
891 // This instruction is potentially convertible to a true
892 // three-address instruction. Check if it is profitable.
893 if (!regBKilled || isProfitableToConv3Addr(regA)) {
894 // Try to convert it.
895 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
896 ++NumConvertedTo3Addr;
897 return true; // Done with this instruction.
898 }
899 }
900 }
Dan Gohman584fedf2010-06-21 22:17:20 +0000901
902 // If this is an instruction with a load folded into it, try unfolding
903 // the load, e.g. avoid this:
904 // movq %rdx, %rcx
905 // addq (%rax), %rcx
906 // in favor of this:
907 // movq (%rax), %rcx
908 // addq %rdx, %rcx
909 // because it's preferable to schedule a load than a register copy.
910 if (TID.mayLoad() && !regBKilled) {
911 // Determine if a load can be unfolded.
912 unsigned LoadRegIndex;
913 unsigned NewOpc =
914 TII->getOpcodeAfterMemoryUnfold(mi->getOpcode(),
915 /*UnfoldLoad=*/true,
916 /*UnfoldStore=*/false,
917 &LoadRegIndex);
918 if (NewOpc != 0) {
919 const TargetInstrDesc &UnfoldTID = TII->get(NewOpc);
920 if (UnfoldTID.getNumDefs() == 1) {
921 MachineFunction &MF = *mbbi->getParent();
922
923 // Unfold the load.
924 DEBUG(dbgs() << "2addr: UNFOLDING: " << *mi);
925 const TargetRegisterClass *RC =
926 UnfoldTID.OpInfo[LoadRegIndex].getRegClass(TRI);
927 unsigned Reg = MRI->createVirtualRegister(RC);
928 SmallVector<MachineInstr *, 2> NewMIs;
929 bool Success =
930 TII->unfoldMemoryOperand(MF, mi, Reg,
931 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
932 NewMIs);
933 (void)Success;
934 assert(Success &&
935 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
936 "succeeded!");
937 assert(NewMIs.size() == 2 &&
938 "Unfolded a load into multiple instructions!");
939 // The load was previously folded, so this is the only use.
940 NewMIs[1]->addRegisterKilled(Reg, TRI);
941
942 // Tentatively insert the instructions into the block so that they
943 // look "normal" to the transformation logic.
944 mbbi->insert(mi, NewMIs[0]);
945 mbbi->insert(mi, NewMIs[1]);
946
947 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
948 << "2addr: NEW INST: " << *NewMIs[1]);
949
950 // Transform the instruction, now that it no longer has a load.
951 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
952 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
953 MachineBasicBlock::iterator NewMI = NewMIs[1];
954 bool TransformSuccess =
955 TryInstructionTransform(NewMI, mi, mbbi,
956 NewSrcIdx, NewDstIdx, Dist);
957 if (TransformSuccess ||
958 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
959 // Success, or at least we made an improvement. Keep the unfolded
960 // instructions and discard the original.
961 if (LV) {
962 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
963 MachineOperand &MO = mi->getOperand(i);
964 if (MO.isReg() && MO.isUse() && MO.isKill())
965 LV->replaceKillInstruction(Reg, mi, NewMIs[0]);
966 }
967 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
968 }
969 mi->eraseFromParent();
970 mi = NewMIs[1];
971 if (TransformSuccess)
972 return true;
973 } else {
974 // Transforming didn't eliminate the tie and didn't lead to an
975 // improvement. Clean up the unfolded instructions and keep the
976 // original.
977 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
978 NewMIs[0]->eraseFromParent();
979 NewMIs[1]->eraseFromParent();
980 }
981 }
982 }
983 }
984
Bob Wilsoncc80df92009-09-03 20:58:42 +0000985 return false;
986}
987
Bill Wendling637980e2008-05-10 00:12:52 +0000988/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000989///
Chris Lattner163c1e72004-01-31 21:14:04 +0000990bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
David Greeneeb00b182010-01-05 01:24:21 +0000991 DEBUG(dbgs() << "Machine Function\n");
Misha Brukman75fa4e42004-07-22 15:26:23 +0000992 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +0000993 MRI = &MF.getRegInfo();
994 TII = TM.getInstrInfo();
995 TRI = TM.getRegisterInfo();
Duncan Sands1465d612009-01-28 13:14:17 +0000996 LV = getAnalysisIfAvailable<LiveVariables>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000997 AA = &getAnalysis<AliasAnalysis>();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000998
Misha Brukman75fa4e42004-07-22 15:26:23 +0000999 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001000
David Greeneeb00b182010-01-05 01:24:21 +00001001 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1002 DEBUG(dbgs() << "********** Function: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001003 << MF.getFunction()->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001004
Evan Cheng7543e582008-06-18 07:49:14 +00001005 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
1006 BitVector ReMatRegs;
1007 ReMatRegs.resize(MRI->getLastVirtReg()+1);
1008
Bob Wilsoncc80df92009-09-03 20:58:42 +00001009 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1010 TiedOperandMap;
1011 TiedOperandMap TiedOperands(4);
1012
Evan Cheng870b8072009-03-01 02:03:43 +00001013 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001014 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1015 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +00001016 unsigned Dist = 0;
1017 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001018 SrcRegMap.clear();
1019 DstRegMap.clear();
1020 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +00001021 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001022 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001023 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001024 if (mi->isDebugValue()) {
1025 mi = nmi;
1026 continue;
1027 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001028
Evan Cheng3d720fb2010-05-05 18:45:40 +00001029 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1030 if (mi->isRegSequence())
1031 RegSequences.push_back(&*mi);
1032
Chris Lattner749c6f62008-01-07 07:27:27 +00001033 const TargetInstrDesc &TID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +00001034 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +00001035
Evan Cheng7543e582008-06-18 07:49:14 +00001036 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001037
1038 ProcessCopy(&*mi, &*mbbi, Processed);
1039
Bob Wilsoncc80df92009-09-03 20:58:42 +00001040 // First scan through all the tied register uses in this instruction
1041 // and record a list of pairs of tied operands for each register.
Chris Lattner518bb532010-02-09 19:54:29 +00001042 unsigned NumOps = mi->isInlineAsm()
Evan Chengfb112882009-03-23 08:01:15 +00001043 ? mi->getNumOperands() : TID.getNumOperands();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001044 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1045 unsigned DstIdx = 0;
1046 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
Evan Cheng360c2dd2006-11-01 23:06:55 +00001047 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001048
Evan Cheng360c2dd2006-11-01 23:06:55 +00001049 if (FirstTied) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001050 FirstTied = false;
Evan Cheng360c2dd2006-11-01 23:06:55 +00001051 ++NumTwoAddressInstrs;
David Greeneeb00b182010-01-05 01:24:21 +00001052 DEBUG(dbgs() << '\t' << *mi);
Evan Cheng360c2dd2006-11-01 23:06:55 +00001053 }
Bill Wendling637980e2008-05-10 00:12:52 +00001054
Bob Wilsoncc80df92009-09-03 20:58:42 +00001055 assert(mi->getOperand(SrcIdx).isReg() &&
1056 mi->getOperand(SrcIdx).getReg() &&
1057 mi->getOperand(SrcIdx).isUse() &&
1058 "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001059
Bob Wilsoncc80df92009-09-03 20:58:42 +00001060 unsigned regB = mi->getOperand(SrcIdx).getReg();
1061 TiedOperandMap::iterator OI = TiedOperands.find(regB);
1062 if (OI == TiedOperands.end()) {
1063 SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
1064 OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
1065 }
1066 OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
1067 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001068
Bob Wilsoncc80df92009-09-03 20:58:42 +00001069 // Now iterate over the information collected above.
1070 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1071 OE = TiedOperands.end(); OI != OE; ++OI) {
1072 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
Evan Cheng360c2dd2006-11-01 23:06:55 +00001073
Bob Wilsoncc80df92009-09-03 20:58:42 +00001074 // If the instruction has a single pair of tied operands, try some
1075 // transformations that may either eliminate the tied operands or
1076 // improve the opportunities for coalescing away the register copy.
1077 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
1078 unsigned SrcIdx = TiedPairs[0].first;
1079 unsigned DstIdx = TiedPairs[0].second;
Bob Wilson43449792009-08-31 21:54:55 +00001080
Bob Wilsoncc80df92009-09-03 20:58:42 +00001081 // If the registers are already equal, nothing needs to be done.
1082 if (mi->getOperand(SrcIdx).getReg() ==
1083 mi->getOperand(DstIdx).getReg())
1084 break; // Done with this instruction.
1085
1086 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
1087 break; // The tied operands have been eliminated.
1088 }
1089
1090 bool RemovedKillFlag = false;
1091 bool AllUsesCopied = true;
1092 unsigned LastCopiedReg = 0;
1093 unsigned regB = OI->first;
1094 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1095 unsigned SrcIdx = TiedPairs[tpi].first;
1096 unsigned DstIdx = TiedPairs[tpi].second;
1097 unsigned regA = mi->getOperand(DstIdx).getReg();
1098 // Grab regB from the instruction because it may have changed if the
1099 // instruction was commuted.
1100 regB = mi->getOperand(SrcIdx).getReg();
1101
1102 if (regA == regB) {
1103 // The register is tied to multiple destinations (or else we would
1104 // not have continued this far), but this use of the register
1105 // already matches the tied destination. Leave it.
1106 AllUsesCopied = false;
1107 continue;
1108 }
1109 LastCopiedReg = regA;
1110
1111 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1112 "cannot make instruction into two-address form");
Chris Lattner6b507672004-01-31 21:21:43 +00001113
Chris Lattner1e313632004-07-21 23:17:57 +00001114#ifndef NDEBUG
Bob Wilsoncc80df92009-09-03 20:58:42 +00001115 // First, verify that we don't have a use of "a" in the instruction
1116 // (a = b + a for example) because our transformation will not
1117 // work. This should never occur because we are in SSA form.
1118 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1119 assert(i == DstIdx ||
1120 !mi->getOperand(i).isReg() ||
1121 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +00001122#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +00001123
Bob Wilsoncc80df92009-09-03 20:58:42 +00001124 // Emit a copy or rematerialize the definition.
1125 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1126 MachineInstr *DefMI = MRI->getVRegDef(regB);
1127 // If it's safe and profitable, remat the definition instead of
1128 // copying it.
1129 if (DefMI &&
1130 DefMI->getDesc().isAsCheapAsAMove() &&
Evan Chengac1abde2010-03-02 19:03:01 +00001131 DefMI->isSafeToReMat(TII, AA, regB) &&
Bob Wilsoncc80df92009-09-03 20:58:42 +00001132 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
David Greeneeb00b182010-01-05 01:24:21 +00001133 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
Bob Wilsoncc80df92009-09-03 20:58:42 +00001134 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
Jakob Stoklund Olesen9edf7de2010-06-02 22:47:25 +00001135 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, *TRI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001136 ReMatRegs.set(regB);
1137 ++NumReMats;
Bob Wilson71124f62009-09-01 04:18:40 +00001138 } else {
Dan Gohman34dcc6f2010-05-06 20:33:48 +00001139 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc,
1140 mi->getDebugLoc());
Bob Wilsoncc80df92009-09-03 20:58:42 +00001141 (void)Emitted;
1142 assert(Emitted && "Unable to issue a copy instruction!\n");
1143 }
1144
1145 MachineBasicBlock::iterator prevMI = prior(mi);
1146 // Update DistanceMap.
1147 DistanceMap.insert(std::make_pair(prevMI, Dist));
1148 DistanceMap[mi] = ++Dist;
1149
David Greeneeb00b182010-01-05 01:24:21 +00001150 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001151
1152 MachineOperand &MO = mi->getOperand(SrcIdx);
1153 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1154 "inconsistent operand info for 2-reg pass");
1155 if (MO.isKill()) {
1156 MO.setIsKill(false);
1157 RemovedKillFlag = true;
1158 }
1159 MO.setReg(regA);
1160 }
1161
1162 if (AllUsesCopied) {
1163 // Replace other (un-tied) uses of regB with LastCopiedReg.
1164 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1165 MachineOperand &MO = mi->getOperand(i);
1166 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1167 if (MO.isKill()) {
1168 MO.setIsKill(false);
1169 RemovedKillFlag = true;
1170 }
1171 MO.setReg(LastCopiedReg);
1172 }
1173 }
1174
1175 // Update live variables for regB.
1176 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1177 LV->addVirtualRegisterKilled(regB, prior(mi));
1178
1179 } else if (RemovedKillFlag) {
1180 // Some tied uses of regB matched their destination registers, so
1181 // regB is still used in this instruction, but a kill flag was
1182 // removed from a different tied use of regB, so now we need to add
1183 // a kill flag to one of the remaining uses of regB.
1184 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1185 MachineOperand &MO = mi->getOperand(i);
1186 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1187 MO.setIsKill(true);
1188 break;
Bob Wilson71124f62009-09-01 04:18:40 +00001189 }
1190 }
Bob Wilson43449792009-08-31 21:54:55 +00001191 }
Evan Cheng68fc2da2010-06-09 19:26:01 +00001192
1193 // Schedule the source copy / remat inserted to form two-address
1194 // instruction. FIXME: Does it matter the distance map may not be
1195 // accurate after it's scheduled?
1196 TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1197
Bob Wilson43449792009-08-31 21:54:55 +00001198 MadeChange = true;
1199
David Greeneeb00b182010-01-05 01:24:21 +00001200 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Misha Brukman75fa4e42004-07-22 15:26:23 +00001201 }
Bill Wendling637980e2008-05-10 00:12:52 +00001202
Bob Wilsoncc80df92009-09-03 20:58:42 +00001203 // Clear TiedOperands here instead of at the top of the loop
1204 // since most instructions do not have tied operands.
1205 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001206 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001207 }
1208 }
1209
Evan Cheng601ca4b2008-06-25 01:16:38 +00001210 // Some remat'ed instructions are dead.
1211 int VReg = ReMatRegs.find_first();
1212 while (VReg != -1) {
Evan Chengf1250ee2010-03-23 20:36:12 +00001213 if (MRI->use_nodbg_empty(VReg)) {
Evan Cheng601ca4b2008-06-25 01:16:38 +00001214 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1215 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +00001216 }
Evan Cheng601ca4b2008-06-25 01:16:38 +00001217 VReg = ReMatRegs.find_next(VReg);
Bill Wendling48f7f232008-05-26 05:18:34 +00001218 }
1219
Evan Cheng3d720fb2010-05-05 18:45:40 +00001220 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1221 // SSA form. It's now safe to de-SSA.
1222 MadeChange |= EliminateRegSequences();
1223
Misha Brukman75fa4e42004-07-22 15:26:23 +00001224 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001225}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001226
1227static void UpdateRegSequenceSrcs(unsigned SrcReg,
Evan Cheng53c779b2010-05-17 20:57:12 +00001228 unsigned DstReg, unsigned SubIdx,
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001229 MachineRegisterInfo *MRI,
1230 const TargetRegisterInfo &TRI) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001231 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
Evan Cheng3ae56bc2010-05-12 01:27:49 +00001232 RE = MRI->reg_end(); RI != RE; ) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001233 MachineOperand &MO = RI.getOperand();
1234 ++RI;
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001235 MO.substVirtReg(DstReg, SubIdx, TRI);
Evan Cheng53c779b2010-05-17 20:57:12 +00001236 }
1237}
1238
1239/// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1240/// EXTRACT_SUBREG from the same register and to the same virtual register
1241/// with different sub-register indices, attempt to combine the
1242/// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1243/// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1244/// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1245/// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1246/// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1247/// reg1026 to reg1029.
1248void
1249TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1250 unsigned DstReg) {
1251 SmallSet<unsigned, 4> Seen;
1252 for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1253 unsigned SrcReg = Srcs[i];
1254 if (!Seen.insert(SrcReg))
1255 continue;
1256
Bob Wilson26bf8f92010-06-03 23:53:58 +00001257 // Check that the instructions are all in the same basic block.
1258 MachineInstr *SrcDefMI = MRI->getVRegDef(SrcReg);
1259 MachineInstr *DstDefMI = MRI->getVRegDef(DstReg);
1260 if (SrcDefMI->getParent() != DstDefMI->getParent())
1261 continue;
1262
Evan Cheng53c779b2010-05-17 20:57:12 +00001263 // If there are no other uses than extract_subreg which feed into
1264 // the reg_sequence, then we might be able to coalesce them.
1265 bool CanCoalesce = true;
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001266 SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
Evan Cheng53c779b2010-05-17 20:57:12 +00001267 for (MachineRegisterInfo::use_nodbg_iterator
1268 UI = MRI->use_nodbg_begin(SrcReg),
1269 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1270 MachineInstr *UseMI = &*UI;
1271 if (!UseMI->isExtractSubreg() ||
Bob Wilson26bf8f92010-06-03 23:53:58 +00001272 UseMI->getOperand(0).getReg() != DstReg ||
Bob Wilson26bf8f92010-06-03 23:53:58 +00001273 UseMI->getOperand(1).getSubReg() != 0) {
Evan Cheng53c779b2010-05-17 20:57:12 +00001274 CanCoalesce = false;
1275 break;
1276 }
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001277 SrcSubIndices.push_back(UseMI->getOperand(2).getImm());
1278 DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
Evan Cheng53c779b2010-05-17 20:57:12 +00001279 }
1280
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001281 if (!CanCoalesce || SrcSubIndices.size() < 2)
Evan Cheng53c779b2010-05-17 20:57:12 +00001282 continue;
1283
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001284 // Check that the source subregisters can be combined.
1285 std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
Bob Wilson852a7e32010-06-15 05:56:31 +00001286 unsigned NewSrcSubIdx = 0;
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001287 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
Bob Wilson852a7e32010-06-15 05:56:31 +00001288 NewSrcSubIdx))
Bob Wilson26bf8f92010-06-03 23:53:58 +00001289 continue;
1290
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001291 // Check that the destination subregisters can also be combined.
1292 std::sort(DstSubIndices.begin(), DstSubIndices.end());
1293 unsigned NewDstSubIdx = 0;
1294 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1295 NewDstSubIdx))
1296 continue;
1297
1298 // If neither source nor destination can be combined to the full register,
1299 // just give up. This could be improved if it ever matters.
1300 if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1301 continue;
1302
Bob Wilson852a7e32010-06-15 05:56:31 +00001303 // Now that we know that all the uses are extract_subregs and that those
1304 // subregs can somehow be combined, scan all the extract_subregs again to
1305 // make sure the subregs are in the right order and can be composed.
Bob Wilson852a7e32010-06-15 05:56:31 +00001306 MachineInstr *SomeMI = 0;
1307 CanCoalesce = true;
1308 for (MachineRegisterInfo::use_nodbg_iterator
1309 UI = MRI->use_nodbg_begin(SrcReg),
1310 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1311 MachineInstr *UseMI = &*UI;
1312 assert(UseMI->isExtractSubreg());
1313 unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
1314 unsigned SrcSubIdx = UseMI->getOperand(2).getImm();
1315 assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001316 if ((NewDstSubIdx == 0 &&
1317 TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1318 (NewSrcSubIdx == 0 &&
1319 TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
Bob Wilson852a7e32010-06-15 05:56:31 +00001320 CanCoalesce = false;
1321 break;
Evan Cheng53c779b2010-05-17 20:57:12 +00001322 }
Bob Wilson852a7e32010-06-15 05:56:31 +00001323 // Keep track of one of the uses.
1324 SomeMI = UseMI;
1325 }
1326 if (!CanCoalesce)
1327 continue;
1328
Bob Wilson852a7e32010-06-15 05:56:31 +00001329 // Insert a copy or an extract to replace the original extracts.
1330 MachineBasicBlock::iterator InsertLoc = SomeMI;
1331 if (NewSrcSubIdx) {
1332 // Insert an extract subreg.
1333 BuildMI(*SomeMI->getParent(), InsertLoc, SomeMI->getDebugLoc(),
1334 TII->get(TargetOpcode::EXTRACT_SUBREG), DstReg)
1335 .addReg(SrcReg).addImm(NewSrcSubIdx);
1336 } else if (NewDstSubIdx) {
1337 // Do a subreg insertion.
1338 BuildMI(*SomeMI->getParent(), InsertLoc, SomeMI->getDebugLoc(),
1339 TII->get(TargetOpcode::INSERT_SUBREG), DstReg)
1340 .addReg(DstReg).addReg(SrcReg).addImm(NewDstSubIdx);
1341 } else {
1342 // Insert a copy.
1343 bool Emitted =
1344 TII->copyRegToReg(*SomeMI->getParent(), InsertLoc, DstReg, SrcReg,
1345 MRI->getRegClass(DstReg), MRI->getRegClass(SrcReg),
1346 SomeMI->getDebugLoc());
1347 (void)Emitted;
1348 }
1349 MachineBasicBlock::iterator CopyMI = prior(InsertLoc);
1350
1351 // Remove all the old extract instructions.
1352 for (MachineRegisterInfo::use_nodbg_iterator
1353 UI = MRI->use_nodbg_begin(SrcReg),
1354 UE = MRI->use_nodbg_end(); UI != UE; ) {
1355 MachineInstr *UseMI = &*UI;
1356 ++UI;
1357 if (UseMI == CopyMI)
1358 continue;
1359 assert(UseMI->isExtractSubreg());
1360 // Move any kills to the new copy or extract instruction.
1361 if (UseMI->getOperand(1).isKill()) {
1362 MachineOperand *KillMO = CopyMI->findRegisterUseOperand(SrcReg);
1363 KillMO->setIsKill();
1364 if (LV)
1365 // Update live variables
1366 LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1367 }
1368 UseMI->eraseFromParent();
1369 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001370 }
1371}
1372
Evan Chengc6dcce32010-05-17 23:24:12 +00001373static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1374 MachineRegisterInfo *MRI) {
1375 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1376 UE = MRI->use_end(); UI != UE; ++UI) {
1377 MachineInstr *UseMI = &*UI;
1378 if (UseMI != RegSeq && UseMI->isRegSequence())
1379 return true;
1380 }
1381 return false;
1382}
1383
Evan Cheng3d720fb2010-05-05 18:45:40 +00001384/// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1385/// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1386/// sub-register references of the register defined by REG_SEQUENCE. e.g.
1387///
1388/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1389/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1390/// =>
1391/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1392bool TwoAddressInstructionPass::EliminateRegSequences() {
1393 if (RegSequences.empty())
1394 return false;
1395
1396 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1397 MachineInstr *MI = RegSequences[i];
1398 unsigned DstReg = MI->getOperand(0).getReg();
1399 if (MI->getOperand(0).getSubReg() ||
1400 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1401 !(MI->getNumOperands() & 1)) {
1402 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1403 llvm_unreachable(0);
1404 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001405
Evan Cheng44bfdd32010-05-17 22:09:49 +00001406 bool IsImpDef = true;
Evan Chengb990a2f2010-05-14 23:21:14 +00001407 SmallVector<unsigned, 4> RealSrcs;
Evan Cheng0bcccac2010-05-11 00:04:31 +00001408 SmallSet<unsigned, 4> Seen;
Evan Cheng3d720fb2010-05-05 18:45:40 +00001409 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1410 unsigned SrcReg = MI->getOperand(i).getReg();
1411 if (MI->getOperand(i).getSubReg() ||
1412 TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1413 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1414 llvm_unreachable(0);
1415 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001416
Evan Cheng054dbb82010-05-13 00:00:35 +00001417 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
Evan Chengb990a2f2010-05-14 23:21:14 +00001418 if (DefMI->isImplicitDef()) {
1419 DefMI->eraseFromParent();
1420 continue;
1421 }
Evan Cheng44bfdd32010-05-17 22:09:49 +00001422 IsImpDef = false;
Evan Chengb990a2f2010-05-14 23:21:14 +00001423
1424 // Remember EXTRACT_SUBREG sources. These might be candidate for
1425 // coalescing.
1426 if (DefMI->isExtractSubreg())
1427 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1428
Evan Chengc6dcce32010-05-17 23:24:12 +00001429 if (!Seen.insert(SrcReg) ||
1430 MI->getParent() != DefMI->getParent() ||
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001431 !MI->getOperand(i).isKill() ||
Evan Chengc6dcce32010-05-17 23:24:12 +00001432 HasOtherRegSequenceUses(SrcReg, MI, MRI)) {
Evan Cheng054dbb82010-05-13 00:00:35 +00001433 // REG_SEQUENCE cannot have duplicated operands, add a copy.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001434 // Also add an copy if the source is live-in the block. We don't want
Evan Cheng054dbb82010-05-13 00:00:35 +00001435 // to end up with a partial-redef of a livein, e.g.
1436 // BB0:
1437 // reg1051:10<def> =
1438 // ...
1439 // BB1:
1440 // ... = reg1051:10
1441 // BB2:
1442 // reg1051:9<def> =
1443 // LiveIntervalAnalysis won't like it.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001444 //
1445 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1446 // correctly up to date becomes very difficult. Insert a copy.
1447 //
Evan Cheng0bcccac2010-05-11 00:04:31 +00001448 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
1449 unsigned NewReg = MRI->createVirtualRegister(RC);
Evan Cheng054dbb82010-05-13 00:00:35 +00001450 MachineBasicBlock::iterator InsertLoc = MI;
Evan Cheng0bcccac2010-05-11 00:04:31 +00001451 bool Emitted =
Evan Cheng054dbb82010-05-13 00:00:35 +00001452 TII->copyRegToReg(*MI->getParent(), InsertLoc, NewReg, SrcReg, RC, RC,
Evan Cheng0bcccac2010-05-11 00:04:31 +00001453 MI->getDebugLoc());
1454 (void)Emitted;
1455 assert(Emitted && "Unable to issue a copy instruction!\n");
1456 MI->getOperand(i).setReg(NewReg);
Evan Cheng054dbb82010-05-13 00:00:35 +00001457 if (MI->getOperand(i).isKill()) {
1458 MachineBasicBlock::iterator CopyMI = prior(InsertLoc);
1459 MachineOperand *KillMO = CopyMI->findRegisterUseOperand(SrcReg);
1460 KillMO->setIsKill();
1461 if (LV)
1462 // Update live variables
1463 LV->replaceKillInstruction(SrcReg, MI, &*CopyMI);
1464 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001465 }
1466 }
1467
1468 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1469 unsigned SrcReg = MI->getOperand(i).getReg();
Evan Cheng53c779b2010-05-17 20:57:12 +00001470 unsigned SubIdx = MI->getOperand(i+1).getImm();
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001471 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001472 }
1473
Evan Cheng44bfdd32010-05-17 22:09:49 +00001474 if (IsImpDef) {
1475 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1476 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1477 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1478 MI->RemoveOperand(j);
1479 } else {
1480 DEBUG(dbgs() << "Eliminated: " << *MI);
1481 MI->eraseFromParent();
1482 }
Evan Chengb990a2f2010-05-14 23:21:14 +00001483
Jakob Stoklund Olesenfe181f42010-06-18 23:10:20 +00001484 // Try coalescing some EXTRACT_SUBREG instructions. This can create
1485 // INSERT_SUBREG instructions that must have <undef> flags added by
1486 // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1487 if (LV)
1488 CoalesceExtSubRegs(RealSrcs, DstReg);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001489 }
1490
Evan Chengfc6e6a92010-05-10 21:24:55 +00001491 RegSequences.clear();
Evan Cheng3d720fb2010-05-05 18:45:40 +00001492 return true;
1493}