blob: 33ed4cc907a1614a34e99a89cc07db8506ec3e7b [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"
Evan Cheng2a4410d2011-11-14 19:48:55 +000039#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000040#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000041#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000043#include "llvm/Target/TargetOptions.h"
Evan Cheng875357d2008-03-13 06:37:55 +000044#include "llvm/Support/Debug.h"
Evan Cheng3d720fb2010-05-05 18:45:40 +000045#include "llvm/Support/ErrorHandling.h"
Evan Cheng7543e582008-06-18 07:49:14 +000046#include "llvm/ADT/BitVector.h"
47#include "llvm/ADT/DenseMap.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000048#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000049#include "llvm/ADT/Statistic.h"
50#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000051using namespace llvm;
52
Chris Lattnercd3245a2006-12-19 22:41:21 +000053STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
54STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengd498c8f2009-01-25 03:53:59 +000055STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattnercd3245a2006-12-19 22:41:21 +000056STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng875357d2008-03-13 06:37:55 +000057STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng7543e582008-06-18 07:49:14 +000058STATISTIC(NumReMats, "Number of instructions re-materialized");
Evan Cheng28c7ce32009-02-21 03:14:25 +000059STATISTIC(NumDeletes, "Number of dead instructions deleted");
Evan Cheng2a4410d2011-11-14 19:48:55 +000060STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
61STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
Evan Cheng875357d2008-03-13 06:37:55 +000062
63namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000064 class TwoAddressInstructionPass : public MachineFunctionPass {
Evan Cheng875357d2008-03-13 06:37:55 +000065 const TargetInstrInfo *TII;
66 const TargetRegisterInfo *TRI;
Evan Cheng2a4410d2011-11-14 19:48:55 +000067 const InstrItineraryData *InstrItins;
Evan Cheng875357d2008-03-13 06:37:55 +000068 MachineRegisterInfo *MRI;
69 LiveVariables *LV;
Dan Gohmana70dca12009-10-09 23:27:56 +000070 AliasAnalysis *AA;
Evan Cheng875357d2008-03-13 06:37:55 +000071
Evan Cheng870b8072009-03-01 02:03:43 +000072 // DistanceMap - Keep track the distance of a MI from the start of the
73 // current basic block.
74 DenseMap<MachineInstr*, unsigned> DistanceMap;
75
76 // SrcRegMap - A map from virtual registers to physical registers which
77 // are likely targets to be coalesced to due to copies from physical
78 // registers to virtual registers. e.g. v1024 = move r0.
79 DenseMap<unsigned, unsigned> SrcRegMap;
80
81 // DstRegMap - A map from virtual registers to physical registers which
82 // are likely targets to be coalesced to due to copies to physical
83 // registers from virtual registers. e.g. r1 = move v1024.
84 DenseMap<unsigned, unsigned> DstRegMap;
85
Evan Cheng3d720fb2010-05-05 18:45:40 +000086 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
87 /// during the initial walk of the machine function.
88 SmallVector<MachineInstr*, 16> RegSequences;
89
Bill Wendling637980e2008-05-10 00:12:52 +000090 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
91 unsigned Reg,
92 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000093
Evan Cheng7543e582008-06-18 07:49:14 +000094 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
Evan Cheng601ca4b2008-06-25 01:16:38 +000095 MachineInstr *MI, MachineInstr *DefMI,
Evan Cheng870b8072009-03-01 02:03:43 +000096 MachineBasicBlock *MBB, unsigned Loc);
Evan Cheng81913712009-01-23 23:27:33 +000097
Evan Chengd498c8f2009-01-25 03:53:59 +000098 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
Evan Chengd498c8f2009-01-25 03:53:59 +000099 unsigned &LastDef);
100
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000101 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
102 unsigned Dist);
103
Evan Chengd498c8f2009-01-25 03:53:59 +0000104 bool isProfitableToCommute(unsigned regB, unsigned regC,
105 MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng870b8072009-03-01 02:03:43 +0000106 unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +0000107
Evan Cheng81913712009-01-23 23:27:33 +0000108 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
109 MachineFunction::iterator &mbbi,
Evan Cheng870b8072009-03-01 02:03:43 +0000110 unsigned RegB, unsigned RegC, unsigned Dist);
111
Evan Chengf06e6c22011-03-02 01:08:17 +0000112 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000113
114 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
115 MachineBasicBlock::iterator &nmi,
116 MachineFunction::iterator &mbbi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000117 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Chenge6f350d2009-03-30 21:34:07 +0000118
Bob Wilson326f4382009-09-01 22:51:08 +0000119 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
120 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
121 SmallVector<NewKill, 4> &NewKills,
122 MachineBasicBlock *MBB, unsigned Dist);
123 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
124 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000125 MachineFunction::iterator &mbbi, unsigned Dist);
Bob Wilson326f4382009-09-01 22:51:08 +0000126
Evan Cheng2a4410d2011-11-14 19:48:55 +0000127 bool isDefTooClose(unsigned Reg, unsigned Dist,
128 MachineInstr *MI, MachineBasicBlock *MBB);
129
130 bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
131 MachineBasicBlock::iterator &mi,
132 MachineBasicBlock::iterator &nmi,
133 unsigned Reg);
134 bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
135 MachineBasicBlock::iterator &mi,
136 MachineBasicBlock::iterator &nmi,
137 unsigned Reg);
138
Bob Wilsoncc80df92009-09-03 20:58:42 +0000139 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
140 MachineBasicBlock::iterator &nmi,
141 MachineFunction::iterator &mbbi,
142 unsigned SrcIdx, unsigned DstIdx,
Evan Chengf06e6c22011-03-02 01:08:17 +0000143 unsigned Dist,
144 SmallPtrSet<MachineInstr*, 8> &Processed);
145
146 void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
147 SmallPtrSet<MachineInstr*, 8> &Processed);
Bob Wilsoncc80df92009-09-03 20:58:42 +0000148
Evan Cheng870b8072009-03-01 02:03:43 +0000149 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
150 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000151
Evan Cheng53c779b2010-05-17 20:57:12 +0000152 void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
153
Evan Cheng3d720fb2010-05-05 18:45:40 +0000154 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
155 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
156 /// sub-register references of the register defined by REG_SEQUENCE.
157 bool EliminateRegSequences();
Evan Chengc6dcce32010-05-17 23:24:12 +0000158
Evan Cheng875357d2008-03-13 06:37:55 +0000159 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000160 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000161 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
162 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
163 }
Devang Patel794fd752007-05-01 21:15:47 +0000164
Bill Wendling637980e2008-05-10 00:12:52 +0000165 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000166 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +0000167 AU.addRequired<AliasAnalysis>();
Bill Wendling637980e2008-05-10 00:12:52 +0000168 AU.addPreserved<LiveVariables>();
169 AU.addPreservedID(MachineLoopInfoID);
170 AU.addPreservedID(MachineDominatorsID);
Cameron Zwarichd959da92010-12-19 18:03:27 +0000171 AU.addPreservedID(PHIEliminationID);
Bill Wendling637980e2008-05-10 00:12:52 +0000172 MachineFunctionPass::getAnalysisUsage(AU);
173 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000174
Bill Wendling637980e2008-05-10 00:12:52 +0000175 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000176 bool runOnMachineFunction(MachineFunction&);
177 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000178}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000179
Dan Gohman844731a2008-05-13 00:00:25 +0000180char TwoAddressInstructionPass::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000181INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
182 "Two-Address instruction pass", false, false)
183INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
184INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersonce665bd2010-10-07 22:25:06 +0000185 "Two-Address instruction pass", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000186
Owen Anderson90c579d2010-08-06 18:33:48 +0000187char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000188
Evan Cheng875357d2008-03-13 06:37:55 +0000189/// Sink3AddrInstruction - A two-address instruction has been converted to a
190/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000191/// past the instruction that would kill the above mentioned register to reduce
192/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000193bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
194 MachineInstr *MI, unsigned SavedReg,
195 MachineBasicBlock::iterator OldPos) {
Eli Friedmanbde81d52011-09-23 22:41:57 +0000196 // FIXME: Shouldn't we be trying to do this before we three-addressify the
197 // instruction? After this transformation is done, we no longer need
198 // the instruction to be in three-address form.
199
Evan Cheng875357d2008-03-13 06:37:55 +0000200 // Check if it's safe to move this instruction.
201 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000202 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000203 return false;
204
205 unsigned DefReg = 0;
206 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000207
Evan Cheng875357d2008-03-13 06:37:55 +0000208 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
209 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000210 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000211 continue;
212 unsigned MOReg = MO.getReg();
213 if (!MOReg)
214 continue;
215 if (MO.isUse() && MOReg != SavedReg)
216 UseRegs.insert(MO.getReg());
217 if (!MO.isDef())
218 continue;
219 if (MO.isImplicit())
220 // Don't try to move it if it implicitly defines a register.
221 return false;
222 if (DefReg)
223 // For now, don't move any instructions that define multiple registers.
224 return false;
225 DefReg = MO.getReg();
226 }
227
228 // Find the instruction that kills SavedReg.
229 MachineInstr *KillMI = NULL;
Evan Chengf1250ee2010-03-23 20:36:12 +0000230 for (MachineRegisterInfo::use_nodbg_iterator
231 UI = MRI->use_nodbg_begin(SavedReg),
232 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng875357d2008-03-13 06:37:55 +0000233 MachineOperand &UseMO = UI.getOperand();
234 if (!UseMO.isKill())
235 continue;
236 KillMI = UseMO.getParent();
237 break;
238 }
Bill Wendling637980e2008-05-10 00:12:52 +0000239
Eli Friedmanbde81d52011-09-23 22:41:57 +0000240 // If we find the instruction that kills SavedReg, and it is in an
241 // appropriate location, we can try to sink the current instruction
242 // past it.
243 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
244 KillMI->getDesc().isTerminator())
Evan Cheng875357d2008-03-13 06:37:55 +0000245 return false;
246
Bill Wendling637980e2008-05-10 00:12:52 +0000247 // If any of the definitions are used by another instruction between the
248 // position and the kill use, then it's not safe to sink it.
249 //
250 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000251 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000252 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000253 MachineOperand *KillMO = NULL;
254 MachineBasicBlock::iterator KillPos = KillMI;
255 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000256
Evan Cheng7543e582008-06-18 07:49:14 +0000257 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000258 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000259 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000260 // DBG_VALUE cannot be counted against the limit.
261 if (OtherMI->isDebugValue())
262 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000263 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
264 return false;
265 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000266 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
267 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000268 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000269 continue;
270 unsigned MOReg = MO.getReg();
271 if (!MOReg)
272 continue;
273 if (DefReg == MOReg)
274 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000275
Evan Cheng875357d2008-03-13 06:37:55 +0000276 if (MO.isKill()) {
277 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000278 // Save the operand that kills the register. We want to unset the kill
279 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000280 KillMO = &MO;
281 else if (UseRegs.count(MOReg))
282 // One of the uses is killed before the destination.
283 return false;
284 }
285 }
286 }
287
Evan Cheng875357d2008-03-13 06:37:55 +0000288 // Update kill and LV information.
289 KillMO->setIsKill(false);
290 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
291 KillMO->setIsKill(true);
Owen Anderson802af112008-07-02 21:28:58 +0000292
Evan Cheng9f1c8312008-07-03 09:09:37 +0000293 if (LV)
294 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000295
296 // Move instruction to its destination.
297 MBB->remove(MI);
298 MBB->insert(KillPos, MI);
299
300 ++Num3AddrSunk;
301 return true;
302}
303
Evan Cheng7543e582008-06-18 07:49:14 +0000304/// isTwoAddrUse - Return true if the specified MI is using the specified
305/// register as a two-address operand.
306static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
Evan Chenge837dea2011-06-28 19:10:37 +0000307 const MCInstrDesc &MCID = UseMI->getDesc();
308 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
Evan Cheng7543e582008-06-18 07:49:14 +0000309 MachineOperand &MO = UseMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000310 if (MO.isReg() && MO.getReg() == Reg &&
Evan Chenga24752f2009-03-19 20:30:06 +0000311 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
Evan Cheng7543e582008-06-18 07:49:14 +0000312 // Earlier use is a two-address one.
313 return true;
314 }
315 return false;
316}
317
318/// isProfitableToReMat - Return true if the heuristics determines it is likely
319/// to be profitable to re-materialize the definition of Reg rather than copy
320/// the register.
321bool
322TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000323 const TargetRegisterClass *RC,
324 MachineInstr *MI, MachineInstr *DefMI,
325 MachineBasicBlock *MBB, unsigned Loc) {
Evan Cheng7543e582008-06-18 07:49:14 +0000326 bool OtherUse = false;
Evan Chengf1250ee2010-03-23 20:36:12 +0000327 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg),
328 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng7543e582008-06-18 07:49:14 +0000329 MachineOperand &UseMO = UI.getOperand();
Evan Cheng7543e582008-06-18 07:49:14 +0000330 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng601ca4b2008-06-25 01:16:38 +0000331 MachineBasicBlock *UseMBB = UseMI->getParent();
332 if (UseMBB == MBB) {
333 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
334 if (DI != DistanceMap.end() && DI->second == Loc)
335 continue; // Current use.
336 OtherUse = true;
337 // There is at least one other use in the MBB that will clobber the
338 // register.
339 if (isTwoAddrUse(UseMI, Reg))
340 return true;
341 }
Evan Cheng7543e582008-06-18 07:49:14 +0000342 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000343
344 // If other uses in MBB are not two-address uses, then don't remat.
345 if (OtherUse)
346 return false;
347
348 // No other uses in the same block, remat if it's defined in the same
349 // block so it does not unnecessarily extend the live range.
350 return MBB == DefMI->getParent();
Evan Cheng7543e582008-06-18 07:49:14 +0000351}
352
Evan Chengd498c8f2009-01-25 03:53:59 +0000353/// NoUseAfterLastDef - Return true if there are no intervening uses between the
354/// last instruction in the MBB that defines the specified register and the
355/// two-address instruction which is being processed. It also returns the last
356/// def location by reference
357bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000358 MachineBasicBlock *MBB, unsigned Dist,
359 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000360 LastDef = 0;
361 unsigned LastUse = Dist;
362 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
363 E = MRI->reg_end(); I != E; ++I) {
364 MachineOperand &MO = I.getOperand();
365 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000366 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000367 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000368 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
369 if (DI == DistanceMap.end())
370 continue;
371 if (MO.isUse() && DI->second < LastUse)
372 LastUse = DI->second;
373 if (MO.isDef() && DI->second > LastDef)
374 LastDef = DI->second;
375 }
376
377 return !(LastUse > LastDef && LastUse < Dist);
378}
379
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000380MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
381 MachineBasicBlock *MBB,
382 unsigned Dist) {
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000383 unsigned LastUseDist = 0;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000384 MachineInstr *LastUse = 0;
385 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
386 E = MRI->reg_end(); I != E; ++I) {
387 MachineOperand &MO = I.getOperand();
388 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000389 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000390 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000391 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
392 if (DI == DistanceMap.end())
393 continue;
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000394 if (DI->second >= Dist)
395 continue;
396
397 if (MO.isUse() && DI->second > LastUseDist) {
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000398 LastUse = DI->first;
399 LastUseDist = DI->second;
400 }
401 }
402 return LastUse;
403}
404
Evan Cheng870b8072009-03-01 02:03:43 +0000405/// isCopyToReg - Return true if the specified MI is a copy instruction or
406/// a extract_subreg instruction. It also returns the source and destination
407/// registers and whether they are physical registers by reference.
408static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
409 unsigned &SrcReg, unsigned &DstReg,
410 bool &IsSrcPhys, bool &IsDstPhys) {
411 SrcReg = 0;
412 DstReg = 0;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000413 if (MI.isCopy()) {
414 DstReg = MI.getOperand(0).getReg();
415 SrcReg = MI.getOperand(1).getReg();
416 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
417 DstReg = MI.getOperand(0).getReg();
418 SrcReg = MI.getOperand(2).getReg();
419 } else
420 return false;
Evan Cheng870b8072009-03-01 02:03:43 +0000421
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000422 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
423 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
424 return true;
Evan Cheng870b8072009-03-01 02:03:43 +0000425}
426
Dan Gohman97121ba2009-04-08 00:15:30 +0000427/// isKilled - Test if the given register value, which is used by the given
428/// instruction, is killed by the given instruction. This looks through
429/// coalescable copies to see if the original value is potentially not killed.
430///
431/// For example, in this code:
432///
433/// %reg1034 = copy %reg1024
434/// %reg1035 = copy %reg1025<kill>
435/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
436///
437/// %reg1034 is not considered to be killed, since it is copied from a
438/// register which is not killed. Treating it as not killed lets the
439/// normal heuristics commute the (two-address) add, which lets
440/// coalescing eliminate the extra copy.
441///
442static bool isKilled(MachineInstr &MI, unsigned Reg,
443 const MachineRegisterInfo *MRI,
444 const TargetInstrInfo *TII) {
445 MachineInstr *DefMI = &MI;
446 for (;;) {
447 if (!DefMI->killsRegister(Reg))
448 return false;
449 if (TargetRegisterInfo::isPhysicalRegister(Reg))
450 return true;
451 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
452 // If there are multiple defs, we can't do a simple analysis, so just
453 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000454 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000455 return true;
456 DefMI = &*Begin;
457 bool IsSrcPhys, IsDstPhys;
458 unsigned SrcReg, DstReg;
459 // If the def is something other than a copy, then it isn't going to
460 // be coalesced, so follow the kill flag.
461 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
462 return true;
463 Reg = SrcReg;
464 }
465}
466
Evan Cheng870b8072009-03-01 02:03:43 +0000467/// isTwoAddrUse - Return true if the specified MI uses the specified register
468/// as a two-address use. If so, return the destination register by reference.
469static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chenge837dea2011-06-28 19:10:37 +0000470 const MCInstrDesc &MCID = MI.getDesc();
471 unsigned NumOps = MI.isInlineAsm()
472 ? MI.getNumOperands() : MCID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000473 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000474 const MachineOperand &MO = MI.getOperand(i);
475 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
476 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000477 unsigned ti;
478 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000479 DstReg = MI.getOperand(ti).getReg();
480 return true;
481 }
482 }
483 return false;
484}
485
Evan Cheng2a4410d2011-11-14 19:48:55 +0000486/// findLocalKill - Look for an instruction below MI in the MBB that kills the
487/// specified register. Returns null if there are any other Reg use between the
488/// instructions.
489static
490MachineInstr *findLocalKill(unsigned Reg, MachineBasicBlock *MBB,
491 MachineInstr *MI, MachineRegisterInfo *MRI,
492 DenseMap<MachineInstr*, unsigned> &DistanceMap) {
493 MachineInstr *KillMI = 0;
494 for (MachineRegisterInfo::use_nodbg_iterator
495 UI = MRI->use_nodbg_begin(Reg),
496 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
497 MachineInstr *UseMI = &*UI;
498 if (UseMI == MI || UseMI->getParent() != MBB)
499 continue;
500 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
501 if (DI != DistanceMap.end())
502 continue;
503 if (!UI.getOperand().isKill())
504 return 0;
505 assert(!KillMI && "More than one local kills?");
506 KillMI = UseMI;
507 }
508
509 return KillMI;
510}
511
Evan Cheng870b8072009-03-01 02:03:43 +0000512/// findOnlyInterestingUse - Given a register, if has a single in-basic block
513/// use, return the use instruction if it's a copy or a two-address use.
514static
515MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
516 MachineRegisterInfo *MRI,
517 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000518 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000519 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000520 if (!MRI->hasOneNonDBGUse(Reg))
521 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000522 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000523 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000524 if (UseMI.getParent() != MBB)
525 return 0;
526 unsigned SrcReg;
527 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000528 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
529 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000530 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000531 }
Evan Cheng870b8072009-03-01 02:03:43 +0000532 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000533 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
534 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000535 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000536 }
Evan Cheng870b8072009-03-01 02:03:43 +0000537 return 0;
538}
539
540/// getMappedReg - Return the physical register the specified virtual register
541/// might be mapped to.
542static unsigned
543getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
544 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
545 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
546 if (SI == RegMap.end())
547 return 0;
548 Reg = SI->second;
549 }
550 if (TargetRegisterInfo::isPhysicalRegister(Reg))
551 return Reg;
552 return 0;
553}
554
555/// regsAreCompatible - Return true if the two registers are equal or aliased.
556///
557static bool
558regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
559 if (RegA == RegB)
560 return true;
561 if (!RegA || !RegB)
562 return false;
563 return TRI->regsOverlap(RegA, RegB);
564}
565
566
Evan Chengd498c8f2009-01-25 03:53:59 +0000567/// isProfitableToReMat - Return true if it's potentially profitable to commute
568/// the two-address instruction that's being processed.
569bool
570TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000571 MachineInstr *MI, MachineBasicBlock *MBB,
572 unsigned Dist) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000573 // Determine if it's profitable to commute this two address instruction. In
574 // general, we want no uses between this instruction and the definition of
575 // the two-address register.
576 // e.g.
577 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
578 // %reg1029<def> = MOV8rr %reg1028
579 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
580 // insert => %reg1030<def> = MOV8rr %reg1028
581 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
582 // In this case, it might not be possible to coalesce the second MOV8rr
583 // instruction if the first one is coalesced. So it would be profitable to
584 // commute it:
585 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
586 // %reg1029<def> = MOV8rr %reg1028
587 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
588 // insert => %reg1030<def> = MOV8rr %reg1029
589 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
590
591 if (!MI->killsRegister(regC))
592 return false;
593
594 // Ok, we have something like:
595 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
596 // let's see if it's worth commuting it.
597
Evan Cheng870b8072009-03-01 02:03:43 +0000598 // Look for situations like this:
599 // %reg1024<def> = MOV r1
600 // %reg1025<def> = MOV r0
601 // %reg1026<def> = ADD %reg1024, %reg1025
602 // r0 = MOV %reg1026
603 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
604 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
605 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
606 unsigned ToRegB = getMappedReg(regB, DstRegMap);
607 unsigned ToRegC = getMappedReg(regC, DstRegMap);
Evan Cheng4d96c632011-02-10 02:20:55 +0000608 if ((FromRegB && ToRegB && !regsAreCompatible(FromRegB, ToRegB, TRI)) &&
Evan Chengbbc726d2010-12-14 21:34:53 +0000609 ((!FromRegC && !ToRegC) ||
610 regsAreCompatible(FromRegB, ToRegC, TRI) ||
Evan Cheng870b8072009-03-01 02:03:43 +0000611 regsAreCompatible(FromRegC, ToRegB, TRI)))
612 return true;
613
Evan Chengd498c8f2009-01-25 03:53:59 +0000614 // If there is a use of regC between its last def (could be livein) and this
615 // instruction, then bail.
616 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000617 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000618 return false;
619
620 // If there is a use of regB between its last def (could be livein) and this
621 // instruction, then go ahead and make this transformation.
622 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000623 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000624 return true;
625
626 // Since there are no intervening uses for both registers, then commute
627 // if the def of regC is closer. Its live interval is shorter.
628 return LastDefB && LastDefC && LastDefC > LastDefB;
629}
630
Evan Cheng81913712009-01-23 23:27:33 +0000631/// CommuteInstruction - Commute a two-address instruction and update the basic
632/// block, distance map, and live variables if needed. Return true if it is
633/// successful.
634bool
635TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000636 MachineFunction::iterator &mbbi,
637 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000638 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000639 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000640 MachineInstr *NewMI = TII->commuteInstruction(MI);
641
642 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000643 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000644 return false;
645 }
646
David Greeneeb00b182010-01-05 01:24:21 +0000647 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000648 // If the instruction changed to commute it, update livevar.
649 if (NewMI != MI) {
650 if (LV)
651 // Update live variables
652 LV->replaceKillInstruction(RegC, MI, NewMI);
653
654 mbbi->insert(mi, NewMI); // Insert the new inst
655 mbbi->erase(mi); // Nuke the old inst.
656 mi = NewMI;
657 DistanceMap.insert(std::make_pair(NewMI, Dist));
658 }
Evan Cheng870b8072009-03-01 02:03:43 +0000659
660 // Update source register map.
661 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
662 if (FromRegC) {
663 unsigned RegA = MI->getOperand(0).getReg();
664 SrcRegMap[RegA] = FromRegC;
665 }
666
Evan Cheng81913712009-01-23 23:27:33 +0000667 return true;
668}
669
Evan Chenge6f350d2009-03-30 21:34:07 +0000670/// isProfitableToConv3Addr - Return true if it is profitable to convert the
671/// given 2-address instruction to a 3-address one.
672bool
Evan Chengf06e6c22011-03-02 01:08:17 +0000673TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Chenge6f350d2009-03-30 21:34:07 +0000674 // Look for situations like this:
675 // %reg1024<def> = MOV r1
676 // %reg1025<def> = MOV r0
677 // %reg1026<def> = ADD %reg1024, %reg1025
678 // r2 = MOV %reg1026
679 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Chengf06e6c22011-03-02 01:08:17 +0000680 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
681 if (!FromRegB)
682 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000683 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Chengf06e6c22011-03-02 01:08:17 +0000684 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Chenge6f350d2009-03-30 21:34:07 +0000685}
686
687/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
688/// three address one. Return true if this transformation was successful.
689bool
690TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
691 MachineBasicBlock::iterator &nmi,
692 MachineFunction::iterator &mbbi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000693 unsigned RegA, unsigned RegB,
694 unsigned Dist) {
Evan Chenge6f350d2009-03-30 21:34:07 +0000695 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
696 if (NewMI) {
David Greeneeb00b182010-01-05 01:24:21 +0000697 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
698 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000699 bool Sunk = false;
700
701 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
702 // FIXME: Temporary workaround. If the new instruction doesn't
703 // uses RegB, convertToThreeAddress must have created more
704 // then one instruction.
705 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
706
707 mbbi->erase(mi); // Nuke the old inst.
708
709 if (!Sunk) {
710 DistanceMap.insert(std::make_pair(NewMI, Dist));
711 mi = NewMI;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000712 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000713 }
Evan Cheng4d96c632011-02-10 02:20:55 +0000714
715 // Update source and destination register maps.
716 SrcRegMap.erase(RegA);
717 DstRegMap.erase(RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000718 return true;
719 }
720
721 return false;
722}
723
Evan Chengf06e6c22011-03-02 01:08:17 +0000724/// ScanUses - Scan forward recursively for only uses, update maps if the use
725/// is a copy or a two-address instruction.
726void
727TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
728 SmallPtrSet<MachineInstr*, 8> &Processed) {
729 SmallVector<unsigned, 4> VirtRegPairs;
730 bool IsDstPhys;
731 bool IsCopy = false;
732 unsigned NewReg = 0;
733 unsigned Reg = DstReg;
734 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
735 NewReg, IsDstPhys)) {
736 if (IsCopy && !Processed.insert(UseMI))
737 break;
738
739 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
740 if (DI != DistanceMap.end())
741 // Earlier in the same MBB.Reached via a back edge.
742 break;
743
744 if (IsDstPhys) {
745 VirtRegPairs.push_back(NewReg);
746 break;
747 }
748 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
749 if (!isNew)
750 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
751 VirtRegPairs.push_back(NewReg);
752 Reg = NewReg;
753 }
754
755 if (!VirtRegPairs.empty()) {
756 unsigned ToReg = VirtRegPairs.back();
757 VirtRegPairs.pop_back();
758 while (!VirtRegPairs.empty()) {
759 unsigned FromReg = VirtRegPairs.back();
760 VirtRegPairs.pop_back();
761 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
762 if (!isNew)
763 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
764 ToReg = FromReg;
765 }
766 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
767 if (!isNew)
768 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
769 }
770}
771
Evan Cheng870b8072009-03-01 02:03:43 +0000772/// ProcessCopy - If the specified instruction is not yet processed, process it
773/// if it's a copy. For a copy instruction, we find the physical registers the
774/// source and destination registers might be mapped to. These are kept in
775/// point-to maps used to determine future optimizations. e.g.
776/// v1024 = mov r0
777/// v1025 = mov r1
778/// v1026 = add v1024, v1025
779/// r1 = mov r1026
780/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
781/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
782/// potentially joined with r1 on the output side. It's worthwhile to commute
783/// 'add' to eliminate a copy.
784void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
785 MachineBasicBlock *MBB,
786 SmallPtrSet<MachineInstr*, 8> &Processed) {
787 if (Processed.count(MI))
788 return;
789
790 bool IsSrcPhys, IsDstPhys;
791 unsigned SrcReg, DstReg;
792 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
793 return;
794
795 if (IsDstPhys && !IsSrcPhys)
796 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
797 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000798 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
799 if (!isNew)
800 assert(SrcRegMap[DstReg] == SrcReg &&
801 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000802
Evan Chengf06e6c22011-03-02 01:08:17 +0000803 ScanUses(DstReg, MBB, Processed);
Evan Cheng870b8072009-03-01 02:03:43 +0000804 }
805
806 Processed.insert(MI);
Evan Chengf06e6c22011-03-02 01:08:17 +0000807 return;
Evan Cheng870b8072009-03-01 02:03:43 +0000808}
809
Evan Cheng28c7ce32009-02-21 03:14:25 +0000810/// isSafeToDelete - If the specified instruction does not produce any side
811/// effects and all of its defs are dead, then it's safe to delete.
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000812static bool isSafeToDelete(MachineInstr *MI,
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000813 const TargetInstrInfo *TII,
814 SmallVector<unsigned, 4> &Kills) {
Evan Chenge837dea2011-06-28 19:10:37 +0000815 const MCInstrDesc &MCID = MI->getDesc();
816 if (MCID.mayStore() || MCID.isCall())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000817 return false;
Evan Chenge837dea2011-06-28 19:10:37 +0000818 if (MCID.isTerminator() || MI->hasUnmodeledSideEffects())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000819 return false;
820
821 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
822 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000823 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000824 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000825 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000826 return false;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000827 if (MO.isUse() && MO.isKill())
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000828 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000829 }
Evan Cheng28c7ce32009-02-21 03:14:25 +0000830 return true;
831}
832
Bob Wilson326f4382009-09-01 22:51:08 +0000833/// canUpdateDeletedKills - Check if all the registers listed in Kills are
834/// killed by instructions in MBB preceding the current instruction at
835/// position Dist. If so, return true and record information about the
836/// preceding kills in NewKills.
837bool TwoAddressInstructionPass::
838canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
839 SmallVector<NewKill, 4> &NewKills,
840 MachineBasicBlock *MBB, unsigned Dist) {
841 while (!Kills.empty()) {
842 unsigned Kill = Kills.back();
843 Kills.pop_back();
844 if (TargetRegisterInfo::isPhysicalRegister(Kill))
845 return false;
846
847 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
848 if (!LastKill)
849 return false;
850
Evan Cheng1015ba72010-05-21 20:53:24 +0000851 bool isModRef = LastKill->definesRegister(Kill);
Bob Wilson326f4382009-09-01 22:51:08 +0000852 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
853 LastKill));
854 }
855 return true;
856}
857
858/// DeleteUnusedInstr - If an instruction with a tied register operand can
859/// be safely deleted, just delete it.
860bool
861TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
862 MachineBasicBlock::iterator &nmi,
863 MachineFunction::iterator &mbbi,
Bob Wilson326f4382009-09-01 22:51:08 +0000864 unsigned Dist) {
865 // Check if the instruction has no side effects and if all its defs are dead.
866 SmallVector<unsigned, 4> Kills;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000867 if (!isSafeToDelete(mi, TII, Kills))
Bob Wilson326f4382009-09-01 22:51:08 +0000868 return false;
869
870 // If this instruction kills some virtual registers, we need to
871 // update the kill information. If it's not possible to do so,
872 // then bail out.
873 SmallVector<NewKill, 4> NewKills;
874 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
875 return false;
876
877 if (LV) {
878 while (!NewKills.empty()) {
879 MachineInstr *NewKill = NewKills.back().second;
880 unsigned Kill = NewKills.back().first.first;
881 bool isDead = NewKills.back().first.second;
882 NewKills.pop_back();
883 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
884 if (isDead)
885 LV->addVirtualRegisterDead(Kill, NewKill);
886 else
887 LV->addVirtualRegisterKilled(Kill, NewKill);
888 }
889 }
Bob Wilson326f4382009-09-01 22:51:08 +0000890 }
891
892 mbbi->erase(mi); // Nuke the old inst.
893 mi = nmi;
894 return true;
895}
896
Evan Cheng2a4410d2011-11-14 19:48:55 +0000897/// RescheduleMIBelowKill - If there is one more local instruction that reads
898/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
899/// instruction in order to eliminate the need for the copy.
900bool
901TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
902 MachineBasicBlock::iterator &mi,
903 MachineBasicBlock::iterator &nmi,
904 unsigned Reg) {
905 MachineInstr *MI = &*mi;
906 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
907 if (DI == DistanceMap.end())
908 // Must be created from unfolded load. Don't waste time trying this.
909 return false;
910
911 MachineInstr *KillMI = findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
912 if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
913 // Don't mess with copies, they may be coalesced later.
914 return false;
915
916 const MCInstrDesc &MCID = KillMI->getDesc();
917 if (MCID.hasUnmodeledSideEffects() || MCID.isCall() || MCID.isBranch() ||
918 MCID.isTerminator())
919 // Don't move pass calls, etc.
920 return false;
921
922 unsigned DstReg;
923 if (isTwoAddrUse(*KillMI, Reg, DstReg))
924 return false;
925
926 bool SeenStore;
927 if (!MI->isSafeToMove(TII, AA, SeenStore))
928 return false;
929
930 if (TII->getInstrLatency(InstrItins, MI) > 1)
931 // FIXME: Needs more sophisticated heuristics.
932 return false;
933
934 SmallSet<unsigned, 2> Uses;
935 SmallSet<unsigned, 2> Defs;
936 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
937 const MachineOperand &MO = MI->getOperand(i);
938 if (!MO.isReg())
939 continue;
940 unsigned MOReg = MO.getReg();
941 if (!MOReg)
942 continue;
943 if (MO.isDef())
944 Defs.insert(MOReg);
945 else
946 Uses.insert(MOReg);
947 }
948
949 // Move the copies connected to MI down as well.
950 MachineBasicBlock::iterator From = MI;
951 MachineBasicBlock::iterator To = llvm::next(From);
952 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
953 Defs.insert(To->getOperand(0).getReg());
954 ++To;
955 }
956
957 // Check if the reschedule will not break depedencies.
958 unsigned NumVisited = 0;
959 MachineBasicBlock::iterator KillPos = KillMI;
960 ++KillPos;
961 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
962 MachineInstr *OtherMI = I;
963 // DBG_VALUE cannot be counted against the limit.
964 if (OtherMI->isDebugValue())
965 continue;
966 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
967 return false;
968 ++NumVisited;
969 const MCInstrDesc &OMCID = OtherMI->getDesc();
970 if (OMCID.hasUnmodeledSideEffects() || OMCID.isCall() || OMCID.isBranch() ||
971 OMCID.isTerminator())
972 // Don't move pass calls, etc.
973 return false;
974 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
975 const MachineOperand &MO = OtherMI->getOperand(i);
976 if (!MO.isReg())
977 continue;
978 unsigned MOReg = MO.getReg();
979 if (!MOReg)
980 continue;
981 if (MO.isDef()) {
982 if (Uses.count(MOReg))
983 // Physical register use would be clobbered.
984 return false;
985 if (!MO.isDead() && Defs.count(MOReg))
986 // May clobber a physical register def.
987 // FIXME: This may be too conservative. It's ok if the instruction
988 // is sunken completely below the use.
989 return false;
990 } else {
991 if (Defs.count(MOReg))
992 return false;
993 if (MOReg != Reg && MO.isKill() && Uses.count(MOReg))
994 // Don't want to extend other live ranges and update kills.
995 return false;
996 }
997 }
998 }
999
1000 // Move debug info as well.
1001 if (From != MBB->begin()) {
1002 while (llvm::prior(From)->isDebugValue())
1003 --From;
1004 }
1005
1006 // Copies following MI may have been moved as well.
1007 nmi = To;
1008 MBB->splice(KillPos, MBB, From, To);
1009 DistanceMap.erase(DI);
1010
1011 if (LV) {
1012 // Update live variables
1013 LV->removeVirtualRegisterKilled(Reg, KillMI);
1014 LV->addVirtualRegisterKilled(Reg, MI);
1015 } else {
1016 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1017 MachineOperand &MO = KillMI->getOperand(i);
1018 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
1019 continue;
1020 MO.setIsKill(false);
1021 }
1022 MI->addRegisterKilled(Reg, 0);
1023 }
1024
1025 return true;
1026}
1027
1028/// isDefTooClose - Return true if the re-scheduling will put the given
1029/// instruction too close to the defs of its register dependencies.
1030bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
1031 MachineInstr *MI,
1032 MachineBasicBlock *MBB) {
1033 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
1034 DE = MRI->def_end(); DI != DE; ++DI) {
1035 MachineInstr *DefMI = &*DI;
1036 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
1037 continue;
1038 if (DefMI == MI)
1039 return true; // MI is defining something KillMI uses
1040 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
1041 if (DDI == DistanceMap.end())
1042 return true; // Below MI
1043 unsigned DefDist = DDI->second;
1044 assert(Dist > DefDist && "Visited def already?");
1045 if (TII->getInstrLatency(InstrItins, DefMI) > (int)(Dist - DefDist))
1046 return true;
1047 }
1048 return false;
1049}
1050
1051/// RescheduleKillAboveMI - If there is one more local instruction that reads
1052/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
1053/// current two-address instruction in order to eliminate the need for the
1054/// copy.
1055bool
1056TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
1057 MachineBasicBlock::iterator &mi,
1058 MachineBasicBlock::iterator &nmi,
1059 unsigned Reg) {
1060 MachineInstr *MI = &*mi;
1061 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1062 if (DI == DistanceMap.end())
1063 // Must be created from unfolded load. Don't waste time trying this.
1064 return false;
1065
1066 MachineInstr *KillMI = findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
1067 if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1068 // Don't mess with copies, they may be coalesced later.
1069 return false;
1070
1071 unsigned DstReg;
1072 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1073 return false;
1074
1075 bool SeenStore;
1076 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
1077 return false;
1078
1079 SmallSet<unsigned, 2> Uses;
1080 SmallSet<unsigned, 2> Kills;
1081 SmallSet<unsigned, 2> Defs;
1082 SmallSet<unsigned, 2> LiveDefs;
1083 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1084 const MachineOperand &MO = KillMI->getOperand(i);
1085 if (!MO.isReg())
1086 continue;
1087 unsigned MOReg = MO.getReg();
1088 if (MO.isUse()) {
1089 if (!MOReg)
1090 continue;
1091 if (isDefTooClose(MOReg, DI->second, MI, MBB))
1092 return false;
1093 Uses.insert(MOReg);
1094 if (MO.isKill() && MOReg != Reg)
1095 Kills.insert(MOReg);
1096 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1097 Defs.insert(MOReg);
1098 if (!MO.isDead())
1099 LiveDefs.insert(MOReg);
1100 }
1101 }
1102
1103 // Check if the reschedule will not break depedencies.
1104 unsigned NumVisited = 0;
1105 MachineBasicBlock::iterator KillPos = KillMI;
1106 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1107 MachineInstr *OtherMI = I;
1108 // DBG_VALUE cannot be counted against the limit.
1109 if (OtherMI->isDebugValue())
1110 continue;
1111 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1112 return false;
1113 ++NumVisited;
1114 const MCInstrDesc &MCID = OtherMI->getDesc();
1115 if (MCID.hasUnmodeledSideEffects() || MCID.isCall() || MCID.isBranch() ||
1116 MCID.isTerminator())
1117 // Don't move pass calls, etc.
1118 return false;
1119 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1120 const MachineOperand &MO = OtherMI->getOperand(i);
1121 if (!MO.isReg())
1122 continue;
1123 unsigned MOReg = MO.getReg();
1124 if (!MOReg)
1125 continue;
1126 if (MO.isUse()) {
1127 if (Defs.count(MOReg))
1128 // Moving KillMI can clobber the physical register if the def has
1129 // not been seen.
1130 return false;
1131 if (Kills.count(MOReg))
1132 // Don't want to extend other live ranges and update kills.
1133 return false;
1134 } else {
1135 if (Uses.count(MOReg))
1136 return false;
1137 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1138 LiveDefs.count(MOReg))
1139 return false;
1140 // Physical register def is seen.
1141 Defs.erase(MOReg);
1142 }
1143 }
1144 }
1145
1146 // Move the old kill above MI, don't forget to move debug info as well.
1147 MachineBasicBlock::iterator InsertPos = mi;
1148 if (InsertPos != MBB->begin())
1149 while (llvm::prior(InsertPos)->isDebugValue())
1150 --InsertPos;
1151 MachineBasicBlock::iterator From = KillMI;
1152 MachineBasicBlock::iterator To = llvm::next(From);
1153 while (llvm::prior(From)->isDebugValue())
1154 --From;
1155 MBB->splice(InsertPos, MBB, From, To);
1156
1157 nmi = llvm::prior(mi); // Backtrack so we process the moved instruction.
1158 DistanceMap.erase(DI);
1159
1160 if (LV) {
1161 // Update live variables
1162 LV->removeVirtualRegisterKilled(Reg, KillMI);
1163 LV->addVirtualRegisterKilled(Reg, MI);
1164 } else {
1165 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1166 MachineOperand &MO = KillMI->getOperand(i);
1167 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
1168 continue;
1169 MO.setIsKill(false);
1170 }
1171 MI->addRegisterKilled(Reg, 0);
1172 }
1173 return true;
1174}
1175
Bob Wilsoncc80df92009-09-03 20:58:42 +00001176/// TryInstructionTransform - For the case where an instruction has a single
1177/// pair of tied register operands, attempt some transformations that may
1178/// either eliminate the tied operands or improve the opportunities for
1179/// coalescing away the register copy. Returns true if the tied operands
1180/// are eliminated altogether.
1181bool TwoAddressInstructionPass::
1182TryInstructionTransform(MachineBasicBlock::iterator &mi,
1183 MachineBasicBlock::iterator &nmi,
1184 MachineFunction::iterator &mbbi,
Evan Chengf06e6c22011-03-02 01:08:17 +00001185 unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1186 SmallPtrSet<MachineInstr*, 8> &Processed) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001187 MachineInstr &MI = *mi;
1188 const MCInstrDesc &MCID = MI.getDesc();
1189 unsigned regA = MI.getOperand(DstIdx).getReg();
1190 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001191
1192 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1193 "cannot make instruction into two-address form");
1194
1195 // If regA is dead and the instruction can be deleted, just delete
1196 // it so it doesn't clobber regB.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001197 bool regBKilled = isKilled(MI, regB, MRI, TII);
1198 if (!regBKilled && MI.getOperand(DstIdx).isDead() &&
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +00001199 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001200 ++NumDeletes;
1201 return true; // Done with this instruction.
1202 }
1203
1204 // Check if it is profitable to commute the operands.
1205 unsigned SrcOp1, SrcOp2;
1206 unsigned regC = 0;
1207 unsigned regCIdx = ~0U;
1208 bool TryCommute = false;
1209 bool AggressiveCommute = false;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001210 if (MCID.isCommutable() && MI.getNumOperands() >= 3 &&
1211 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001212 if (SrcIdx == SrcOp1)
1213 regCIdx = SrcOp2;
1214 else if (SrcIdx == SrcOp2)
1215 regCIdx = SrcOp1;
1216
1217 if (regCIdx != ~0U) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001218 regC = MI.getOperand(regCIdx).getReg();
1219 if (!regBKilled && isKilled(MI, regC, MRI, TII))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001220 // If C dies but B does not, swap the B and C operands.
1221 // This makes the live ranges of A and C joinable.
1222 TryCommute = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001223 else if (isProfitableToCommute(regB, regC, &MI, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001224 TryCommute = true;
1225 AggressiveCommute = true;
1226 }
1227 }
1228 }
1229
1230 // If it's profitable to commute, try to do so.
1231 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1232 ++NumCommuted;
1233 if (AggressiveCommute)
1234 ++NumAggrCommuted;
1235 return false;
1236 }
1237
Evan Cheng2a4410d2011-11-14 19:48:55 +00001238 // If there is one more use of regB later in the same MBB, consider
1239 // re-schedule this MI below it.
1240 if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1241 ++NumReSchedDowns;
1242 return true;
1243 }
1244
Evan Chengf06e6c22011-03-02 01:08:17 +00001245 if (TargetRegisterInfo::isVirtualRegister(regA))
1246 ScanUses(regA, &*mbbi, Processed);
1247
Evan Chenge837dea2011-06-28 19:10:37 +00001248 if (MCID.isConvertibleTo3Addr()) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001249 // This instruction is potentially convertible to a true
1250 // three-address instruction. Check if it is profitable.
Evan Chengf06e6c22011-03-02 01:08:17 +00001251 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001252 // Try to convert it.
Evan Cheng4d96c632011-02-10 02:20:55 +00001253 if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001254 ++NumConvertedTo3Addr;
1255 return true; // Done with this instruction.
1256 }
1257 }
1258 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001259
Evan Cheng2a4410d2011-11-14 19:48:55 +00001260 // If there is one more use of regB later in the same MBB, consider
1261 // re-schedule it before this MI if it's legal.
1262 if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1263 ++NumReSchedUps;
1264 return true;
1265 }
1266
Dan Gohman584fedf2010-06-21 22:17:20 +00001267 // If this is an instruction with a load folded into it, try unfolding
1268 // the load, e.g. avoid this:
1269 // movq %rdx, %rcx
1270 // addq (%rax), %rcx
1271 // in favor of this:
1272 // movq (%rax), %rcx
1273 // addq %rdx, %rcx
1274 // because it's preferable to schedule a load than a register copy.
Evan Chenge837dea2011-06-28 19:10:37 +00001275 if (MCID.mayLoad() && !regBKilled) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001276 // Determine if a load can be unfolded.
1277 unsigned LoadRegIndex;
1278 unsigned NewOpc =
Evan Cheng2a4410d2011-11-14 19:48:55 +00001279 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman584fedf2010-06-21 22:17:20 +00001280 /*UnfoldLoad=*/true,
1281 /*UnfoldStore=*/false,
1282 &LoadRegIndex);
1283 if (NewOpc != 0) {
Evan Chenge837dea2011-06-28 19:10:37 +00001284 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1285 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001286 MachineFunction &MF = *mbbi->getParent();
1287
1288 // Unfold the load.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001289 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001290 const TargetRegisterClass *RC =
Evan Chenge837dea2011-06-28 19:10:37 +00001291 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001292 unsigned Reg = MRI->createVirtualRegister(RC);
1293 SmallVector<MachineInstr *, 2> NewMIs;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001294 if (!TII->unfoldMemoryOperand(MF, &MI, Reg,
Evan Cheng98ec91e2010-07-02 20:36:18 +00001295 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1296 NewMIs)) {
1297 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1298 return false;
1299 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001300 assert(NewMIs.size() == 2 &&
1301 "Unfolded a load into multiple instructions!");
1302 // The load was previously folded, so this is the only use.
1303 NewMIs[1]->addRegisterKilled(Reg, TRI);
1304
1305 // Tentatively insert the instructions into the block so that they
1306 // look "normal" to the transformation logic.
1307 mbbi->insert(mi, NewMIs[0]);
1308 mbbi->insert(mi, NewMIs[1]);
1309
1310 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1311 << "2addr: NEW INST: " << *NewMIs[1]);
1312
1313 // Transform the instruction, now that it no longer has a load.
1314 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1315 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1316 MachineBasicBlock::iterator NewMI = NewMIs[1];
1317 bool TransformSuccess =
1318 TryInstructionTransform(NewMI, mi, mbbi,
Evan Chengf06e6c22011-03-02 01:08:17 +00001319 NewSrcIdx, NewDstIdx, Dist, Processed);
Dan Gohman584fedf2010-06-21 22:17:20 +00001320 if (TransformSuccess ||
1321 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1322 // Success, or at least we made an improvement. Keep the unfolded
1323 // instructions and discard the original.
1324 if (LV) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001325 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1326 MachineOperand &MO = MI.getOperand(i);
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001327 if (MO.isReg() &&
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001328 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1329 if (MO.isUse()) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001330 if (MO.isKill()) {
1331 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng2a4410d2011-11-14 19:48:55 +00001332 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001333 else {
1334 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1335 "Kill missing after load unfold!");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001336 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001337 }
1338 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001339 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001340 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1341 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1342 else {
1343 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1344 "Dead flag missing after load unfold!");
1345 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1346 }
1347 }
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001348 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001349 }
1350 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1351 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001352 MI.eraseFromParent();
Dan Gohman584fedf2010-06-21 22:17:20 +00001353 mi = NewMIs[1];
1354 if (TransformSuccess)
1355 return true;
1356 } else {
1357 // Transforming didn't eliminate the tie and didn't lead to an
1358 // improvement. Clean up the unfolded instructions and keep the
1359 // original.
1360 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1361 NewMIs[0]->eraseFromParent();
1362 NewMIs[1]->eraseFromParent();
1363 }
1364 }
1365 }
1366 }
1367
Bob Wilsoncc80df92009-09-03 20:58:42 +00001368 return false;
1369}
1370
Bill Wendling637980e2008-05-10 00:12:52 +00001371/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001372///
Chris Lattner163c1e72004-01-31 21:14:04 +00001373bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
David Greeneeb00b182010-01-05 01:24:21 +00001374 DEBUG(dbgs() << "Machine Function\n");
Misha Brukman75fa4e42004-07-22 15:26:23 +00001375 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +00001376 MRI = &MF.getRegInfo();
1377 TII = TM.getInstrInfo();
1378 TRI = TM.getRegisterInfo();
Evan Cheng2a4410d2011-11-14 19:48:55 +00001379 InstrItins = TM.getInstrItineraryData();
Duncan Sands1465d612009-01-28 13:14:17 +00001380 LV = getAnalysisIfAvailable<LiveVariables>();
Dan Gohmana70dca12009-10-09 23:27:56 +00001381 AA = &getAnalysis<AliasAnalysis>();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001382
Misha Brukman75fa4e42004-07-22 15:26:23 +00001383 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001384
David Greeneeb00b182010-01-05 01:24:21 +00001385 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1386 DEBUG(dbgs() << "********** Function: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001387 << MF.getFunction()->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001388
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +00001389 // This pass takes the function out of SSA form.
1390 MRI->leaveSSA();
1391
Evan Cheng7543e582008-06-18 07:49:14 +00001392 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
Jakob Stoklund Olesen00f93fc2011-01-09 03:45:44 +00001393 BitVector ReMatRegs(MRI->getNumVirtRegs());
Evan Cheng7543e582008-06-18 07:49:14 +00001394
Bob Wilsoncc80df92009-09-03 20:58:42 +00001395 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1396 TiedOperandMap;
1397 TiedOperandMap TiedOperands(4);
1398
Evan Cheng870b8072009-03-01 02:03:43 +00001399 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001400 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1401 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +00001402 unsigned Dist = 0;
1403 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001404 SrcRegMap.clear();
1405 DstRegMap.clear();
1406 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +00001407 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001408 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001409 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001410 if (mi->isDebugValue()) {
1411 mi = nmi;
1412 continue;
1413 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001414
Evan Cheng3d720fb2010-05-05 18:45:40 +00001415 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1416 if (mi->isRegSequence())
1417 RegSequences.push_back(&*mi);
1418
Evan Chenge837dea2011-06-28 19:10:37 +00001419 const MCInstrDesc &MCID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +00001420 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +00001421
Evan Cheng7543e582008-06-18 07:49:14 +00001422 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001423
1424 ProcessCopy(&*mi, &*mbbi, Processed);
1425
Bob Wilsoncc80df92009-09-03 20:58:42 +00001426 // First scan through all the tied register uses in this instruction
1427 // and record a list of pairs of tied operands for each register.
Chris Lattner518bb532010-02-09 19:54:29 +00001428 unsigned NumOps = mi->isInlineAsm()
Evan Chenge837dea2011-06-28 19:10:37 +00001429 ? mi->getNumOperands() : MCID.getNumOperands();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001430 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1431 unsigned DstIdx = 0;
1432 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
Evan Cheng360c2dd2006-11-01 23:06:55 +00001433 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001434
Evan Cheng360c2dd2006-11-01 23:06:55 +00001435 if (FirstTied) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001436 FirstTied = false;
Evan Cheng360c2dd2006-11-01 23:06:55 +00001437 ++NumTwoAddressInstrs;
David Greeneeb00b182010-01-05 01:24:21 +00001438 DEBUG(dbgs() << '\t' << *mi);
Evan Cheng360c2dd2006-11-01 23:06:55 +00001439 }
Bill Wendling637980e2008-05-10 00:12:52 +00001440
Bob Wilsoncc80df92009-09-03 20:58:42 +00001441 assert(mi->getOperand(SrcIdx).isReg() &&
1442 mi->getOperand(SrcIdx).getReg() &&
1443 mi->getOperand(SrcIdx).isUse() &&
1444 "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001445
Bob Wilsoncc80df92009-09-03 20:58:42 +00001446 unsigned regB = mi->getOperand(SrcIdx).getReg();
Benjamin Kramer4e39f8f2011-06-18 13:53:47 +00001447 TiedOperands[regB].push_back(std::make_pair(SrcIdx, DstIdx));
Bob Wilsoncc80df92009-09-03 20:58:42 +00001448 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001449
Bob Wilsoncc80df92009-09-03 20:58:42 +00001450 // Now iterate over the information collected above.
1451 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1452 OE = TiedOperands.end(); OI != OE; ++OI) {
1453 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
Evan Cheng360c2dd2006-11-01 23:06:55 +00001454
Bob Wilsoncc80df92009-09-03 20:58:42 +00001455 // If the instruction has a single pair of tied operands, try some
1456 // transformations that may either eliminate the tied operands or
1457 // improve the opportunities for coalescing away the register copy.
1458 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
1459 unsigned SrcIdx = TiedPairs[0].first;
1460 unsigned DstIdx = TiedPairs[0].second;
Bob Wilson43449792009-08-31 21:54:55 +00001461
Bob Wilsoncc80df92009-09-03 20:58:42 +00001462 // If the registers are already equal, nothing needs to be done.
1463 if (mi->getOperand(SrcIdx).getReg() ==
1464 mi->getOperand(DstIdx).getReg())
1465 break; // Done with this instruction.
1466
Evan Chengf06e6c22011-03-02 01:08:17 +00001467 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1468 Processed))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001469 break; // The tied operands have been eliminated.
1470 }
1471
Cameron Zwarichaaa5f142011-06-07 23:54:00 +00001472 bool IsEarlyClobber = false;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001473 bool RemovedKillFlag = false;
1474 bool AllUsesCopied = true;
1475 unsigned LastCopiedReg = 0;
1476 unsigned regB = OI->first;
1477 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1478 unsigned SrcIdx = TiedPairs[tpi].first;
1479 unsigned DstIdx = TiedPairs[tpi].second;
Cameron Zwarichaaa5f142011-06-07 23:54:00 +00001480
1481 const MachineOperand &DstMO = mi->getOperand(DstIdx);
1482 unsigned regA = DstMO.getReg();
1483 IsEarlyClobber |= DstMO.isEarlyClobber();
1484
Bob Wilsoncc80df92009-09-03 20:58:42 +00001485 // Grab regB from the instruction because it may have changed if the
1486 // instruction was commuted.
1487 regB = mi->getOperand(SrcIdx).getReg();
1488
1489 if (regA == regB) {
1490 // The register is tied to multiple destinations (or else we would
1491 // not have continued this far), but this use of the register
1492 // already matches the tied destination. Leave it.
1493 AllUsesCopied = false;
1494 continue;
1495 }
1496 LastCopiedReg = regA;
1497
1498 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1499 "cannot make instruction into two-address form");
Chris Lattner6b507672004-01-31 21:21:43 +00001500
Chris Lattner1e313632004-07-21 23:17:57 +00001501#ifndef NDEBUG
Bob Wilsoncc80df92009-09-03 20:58:42 +00001502 // First, verify that we don't have a use of "a" in the instruction
1503 // (a = b + a for example) because our transformation will not
1504 // work. This should never occur because we are in SSA form.
1505 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1506 assert(i == DstIdx ||
1507 !mi->getOperand(i).isReg() ||
1508 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +00001509#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +00001510
Bob Wilsoncc80df92009-09-03 20:58:42 +00001511 // Emit a copy or rematerialize the definition.
1512 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1513 MachineInstr *DefMI = MRI->getVRegDef(regB);
1514 // If it's safe and profitable, remat the definition instead of
1515 // copying it.
1516 if (DefMI &&
1517 DefMI->getDesc().isAsCheapAsAMove() &&
Evan Chengac1abde2010-03-02 19:03:01 +00001518 DefMI->isSafeToReMat(TII, AA, regB) &&
Bob Wilsoncc80df92009-09-03 20:58:42 +00001519 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
David Greeneeb00b182010-01-05 01:24:21 +00001520 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
Bob Wilsoncc80df92009-09-03 20:58:42 +00001521 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
Jakob Stoklund Olesen9edf7de2010-06-02 22:47:25 +00001522 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, *TRI);
Jakob Stoklund Olesen00f93fc2011-01-09 03:45:44 +00001523 ReMatRegs.set(TargetRegisterInfo::virtReg2Index(regB));
Bob Wilsoncc80df92009-09-03 20:58:42 +00001524 ++NumReMats;
Bob Wilson71124f62009-09-01 04:18:40 +00001525 } else {
Jakob Stoklund Olesen92c1f722010-07-10 19:08:25 +00001526 BuildMI(*mbbi, mi, mi->getDebugLoc(), TII->get(TargetOpcode::COPY),
1527 regA).addReg(regB);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001528 }
1529
1530 MachineBasicBlock::iterator prevMI = prior(mi);
1531 // Update DistanceMap.
1532 DistanceMap.insert(std::make_pair(prevMI, Dist));
1533 DistanceMap[mi] = ++Dist;
1534
David Greeneeb00b182010-01-05 01:24:21 +00001535 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001536
1537 MachineOperand &MO = mi->getOperand(SrcIdx);
1538 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1539 "inconsistent operand info for 2-reg pass");
1540 if (MO.isKill()) {
1541 MO.setIsKill(false);
1542 RemovedKillFlag = true;
1543 }
1544 MO.setReg(regA);
1545 }
1546
1547 if (AllUsesCopied) {
Cameron Zwarichaaa5f142011-06-07 23:54:00 +00001548 if (!IsEarlyClobber) {
1549 // Replace other (un-tied) uses of regB with LastCopiedReg.
1550 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1551 MachineOperand &MO = mi->getOperand(i);
1552 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1553 if (MO.isKill()) {
1554 MO.setIsKill(false);
1555 RemovedKillFlag = true;
1556 }
1557 MO.setReg(LastCopiedReg);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001558 }
Bob Wilsoncc80df92009-09-03 20:58:42 +00001559 }
1560 }
1561
1562 // Update live variables for regB.
1563 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1564 LV->addVirtualRegisterKilled(regB, prior(mi));
1565
1566 } else if (RemovedKillFlag) {
1567 // Some tied uses of regB matched their destination registers, so
1568 // regB is still used in this instruction, but a kill flag was
1569 // removed from a different tied use of regB, so now we need to add
1570 // a kill flag to one of the remaining uses of regB.
1571 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1572 MachineOperand &MO = mi->getOperand(i);
1573 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1574 MO.setIsKill(true);
1575 break;
Bob Wilson71124f62009-09-01 04:18:40 +00001576 }
1577 }
Bob Wilson43449792009-08-31 21:54:55 +00001578 }
Evan Cheng68fc2da2010-06-09 19:26:01 +00001579
1580 // Schedule the source copy / remat inserted to form two-address
1581 // instruction. FIXME: Does it matter the distance map may not be
1582 // accurate after it's scheduled?
1583 TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1584
Bob Wilson43449792009-08-31 21:54:55 +00001585 MadeChange = true;
1586
David Greeneeb00b182010-01-05 01:24:21 +00001587 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Misha Brukman75fa4e42004-07-22 15:26:23 +00001588 }
Bill Wendling637980e2008-05-10 00:12:52 +00001589
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +00001590 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1591 if (mi->isInsertSubreg()) {
1592 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1593 // To %reg:subidx = COPY %subreg
1594 unsigned SubIdx = mi->getOperand(3).getImm();
1595 mi->RemoveOperand(3);
1596 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1597 mi->getOperand(0).setSubReg(SubIdx);
1598 mi->RemoveOperand(1);
1599 mi->setDesc(TII->get(TargetOpcode::COPY));
1600 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1601 }
1602
Bob Wilsoncc80df92009-09-03 20:58:42 +00001603 // Clear TiedOperands here instead of at the top of the loop
1604 // since most instructions do not have tied operands.
1605 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001606 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001607 }
1608 }
1609
Evan Cheng601ca4b2008-06-25 01:16:38 +00001610 // Some remat'ed instructions are dead.
Jakob Stoklund Olesen00f93fc2011-01-09 03:45:44 +00001611 for (int i = ReMatRegs.find_first(); i != -1; i = ReMatRegs.find_next(i)) {
1612 unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
Evan Chengf1250ee2010-03-23 20:36:12 +00001613 if (MRI->use_nodbg_empty(VReg)) {
Evan Cheng601ca4b2008-06-25 01:16:38 +00001614 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1615 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +00001616 }
Bill Wendling48f7f232008-05-26 05:18:34 +00001617 }
1618
Evan Cheng3d720fb2010-05-05 18:45:40 +00001619 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1620 // SSA form. It's now safe to de-SSA.
1621 MadeChange |= EliminateRegSequences();
1622
Misha Brukman75fa4e42004-07-22 15:26:23 +00001623 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001624}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001625
1626static void UpdateRegSequenceSrcs(unsigned SrcReg,
Evan Cheng53c779b2010-05-17 20:57:12 +00001627 unsigned DstReg, unsigned SubIdx,
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001628 MachineRegisterInfo *MRI,
1629 const TargetRegisterInfo &TRI) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001630 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
Evan Cheng3ae56bc2010-05-12 01:27:49 +00001631 RE = MRI->reg_end(); RI != RE; ) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001632 MachineOperand &MO = RI.getOperand();
1633 ++RI;
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001634 MO.substVirtReg(DstReg, SubIdx, TRI);
Evan Cheng53c779b2010-05-17 20:57:12 +00001635 }
1636}
1637
1638/// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1639/// EXTRACT_SUBREG from the same register and to the same virtual register
1640/// with different sub-register indices, attempt to combine the
1641/// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1642/// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1643/// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1644/// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1645/// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1646/// reg1026 to reg1029.
1647void
1648TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1649 unsigned DstReg) {
1650 SmallSet<unsigned, 4> Seen;
1651 for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1652 unsigned SrcReg = Srcs[i];
1653 if (!Seen.insert(SrcReg))
1654 continue;
1655
Bob Wilson26bf8f92010-06-03 23:53:58 +00001656 // Check that the instructions are all in the same basic block.
1657 MachineInstr *SrcDefMI = MRI->getVRegDef(SrcReg);
1658 MachineInstr *DstDefMI = MRI->getVRegDef(DstReg);
1659 if (SrcDefMI->getParent() != DstDefMI->getParent())
1660 continue;
1661
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001662 // If there are no other uses than copies which feed into
Evan Cheng53c779b2010-05-17 20:57:12 +00001663 // the reg_sequence, then we might be able to coalesce them.
1664 bool CanCoalesce = true;
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001665 SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
Evan Cheng53c779b2010-05-17 20:57:12 +00001666 for (MachineRegisterInfo::use_nodbg_iterator
1667 UI = MRI->use_nodbg_begin(SrcReg),
1668 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1669 MachineInstr *UseMI = &*UI;
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001670 if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
Evan Cheng53c779b2010-05-17 20:57:12 +00001671 CanCoalesce = false;
1672 break;
1673 }
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001674 SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001675 DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
Evan Cheng53c779b2010-05-17 20:57:12 +00001676 }
1677
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001678 if (!CanCoalesce || SrcSubIndices.size() < 2)
Evan Cheng53c779b2010-05-17 20:57:12 +00001679 continue;
1680
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001681 // Check that the source subregisters can be combined.
1682 std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
Bob Wilson852a7e32010-06-15 05:56:31 +00001683 unsigned NewSrcSubIdx = 0;
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001684 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
Bob Wilson852a7e32010-06-15 05:56:31 +00001685 NewSrcSubIdx))
Bob Wilson26bf8f92010-06-03 23:53:58 +00001686 continue;
1687
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001688 // Check that the destination subregisters can also be combined.
1689 std::sort(DstSubIndices.begin(), DstSubIndices.end());
1690 unsigned NewDstSubIdx = 0;
1691 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1692 NewDstSubIdx))
1693 continue;
1694
1695 // If neither source nor destination can be combined to the full register,
1696 // just give up. This could be improved if it ever matters.
1697 if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1698 continue;
1699
Bob Wilson852a7e32010-06-15 05:56:31 +00001700 // Now that we know that all the uses are extract_subregs and that those
1701 // subregs can somehow be combined, scan all the extract_subregs again to
1702 // make sure the subregs are in the right order and can be composed.
Bob Wilson852a7e32010-06-15 05:56:31 +00001703 MachineInstr *SomeMI = 0;
1704 CanCoalesce = true;
1705 for (MachineRegisterInfo::use_nodbg_iterator
1706 UI = MRI->use_nodbg_begin(SrcReg),
1707 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1708 MachineInstr *UseMI = &*UI;
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001709 assert(UseMI->isCopy());
Bob Wilson852a7e32010-06-15 05:56:31 +00001710 unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001711 unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
Bob Wilson852a7e32010-06-15 05:56:31 +00001712 assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001713 if ((NewDstSubIdx == 0 &&
1714 TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1715 (NewSrcSubIdx == 0 &&
1716 TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
Bob Wilson852a7e32010-06-15 05:56:31 +00001717 CanCoalesce = false;
1718 break;
Evan Cheng53c779b2010-05-17 20:57:12 +00001719 }
Bob Wilson852a7e32010-06-15 05:56:31 +00001720 // Keep track of one of the uses.
1721 SomeMI = UseMI;
1722 }
1723 if (!CanCoalesce)
1724 continue;
1725
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001726 // Insert a copy to replace the original.
Jakob Stoklund Olesen5c00e072010-07-08 16:40:15 +00001727 MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1728 SomeMI->getDebugLoc(),
1729 TII->get(TargetOpcode::COPY))
1730 .addReg(DstReg, RegState::Define, NewDstSubIdx)
1731 .addReg(SrcReg, 0, NewSrcSubIdx);
Bob Wilson852a7e32010-06-15 05:56:31 +00001732
1733 // Remove all the old extract instructions.
1734 for (MachineRegisterInfo::use_nodbg_iterator
1735 UI = MRI->use_nodbg_begin(SrcReg),
1736 UE = MRI->use_nodbg_end(); UI != UE; ) {
1737 MachineInstr *UseMI = &*UI;
1738 ++UI;
1739 if (UseMI == CopyMI)
1740 continue;
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001741 assert(UseMI->isCopy());
Bob Wilson852a7e32010-06-15 05:56:31 +00001742 // Move any kills to the new copy or extract instruction.
1743 if (UseMI->getOperand(1).isKill()) {
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001744 CopyMI->getOperand(1).setIsKill();
Bob Wilson852a7e32010-06-15 05:56:31 +00001745 if (LV)
1746 // Update live variables
1747 LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1748 }
1749 UseMI->eraseFromParent();
1750 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001751 }
1752}
1753
Evan Chengc6dcce32010-05-17 23:24:12 +00001754static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1755 MachineRegisterInfo *MRI) {
1756 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1757 UE = MRI->use_end(); UI != UE; ++UI) {
1758 MachineInstr *UseMI = &*UI;
1759 if (UseMI != RegSeq && UseMI->isRegSequence())
1760 return true;
1761 }
1762 return false;
1763}
1764
Evan Cheng3d720fb2010-05-05 18:45:40 +00001765/// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1766/// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1767/// sub-register references of the register defined by REG_SEQUENCE. e.g.
1768///
1769/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1770/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1771/// =>
1772/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1773bool TwoAddressInstructionPass::EliminateRegSequences() {
1774 if (RegSequences.empty())
1775 return false;
1776
1777 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1778 MachineInstr *MI = RegSequences[i];
1779 unsigned DstReg = MI->getOperand(0).getReg();
1780 if (MI->getOperand(0).getSubReg() ||
1781 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1782 !(MI->getNumOperands() & 1)) {
1783 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1784 llvm_unreachable(0);
1785 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001786
Evan Cheng44bfdd32010-05-17 22:09:49 +00001787 bool IsImpDef = true;
Evan Chengb990a2f2010-05-14 23:21:14 +00001788 SmallVector<unsigned, 4> RealSrcs;
Evan Cheng0bcccac2010-05-11 00:04:31 +00001789 SmallSet<unsigned, 4> Seen;
Evan Cheng3d720fb2010-05-05 18:45:40 +00001790 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1791 unsigned SrcReg = MI->getOperand(i).getReg();
Bob Wilson495de3b2010-12-17 01:21:12 +00001792 unsigned SubIdx = MI->getOperand(i+1).getImm();
Evan Cheng3d720fb2010-05-05 18:45:40 +00001793 if (MI->getOperand(i).getSubReg() ||
1794 TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1795 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1796 llvm_unreachable(0);
1797 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001798
Evan Cheng054dbb82010-05-13 00:00:35 +00001799 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
Evan Chengb990a2f2010-05-14 23:21:14 +00001800 if (DefMI->isImplicitDef()) {
1801 DefMI->eraseFromParent();
1802 continue;
1803 }
Evan Cheng44bfdd32010-05-17 22:09:49 +00001804 IsImpDef = false;
Evan Chengb990a2f2010-05-14 23:21:14 +00001805
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001806 // Remember COPY sources. These might be candidate for coalescing.
Jakob Stoklund Olesenc0075cc2010-07-10 22:42:53 +00001807 if (DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
Evan Chengb990a2f2010-05-14 23:21:14 +00001808 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1809
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001810 bool isKill = MI->getOperand(i).isKill();
1811 if (!Seen.insert(SrcReg) || MI->getParent() != DefMI->getParent() ||
Bob Wilson495de3b2010-12-17 01:21:12 +00001812 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1813 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1814 MRI->getRegClass(SrcReg), SubIdx)) {
Evan Cheng054dbb82010-05-13 00:00:35 +00001815 // REG_SEQUENCE cannot have duplicated operands, add a copy.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001816 // Also add an copy if the source is live-in the block. We don't want
Evan Cheng054dbb82010-05-13 00:00:35 +00001817 // to end up with a partial-redef of a livein, e.g.
1818 // BB0:
1819 // reg1051:10<def> =
1820 // ...
1821 // BB1:
1822 // ... = reg1051:10
1823 // BB2:
1824 // reg1051:9<def> =
1825 // LiveIntervalAnalysis won't like it.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001826 //
1827 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1828 // correctly up to date becomes very difficult. Insert a copy.
Jakob Stoklund Olesene4b9c4f2010-08-09 20:19:16 +00001829
1830 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1831 // might insert a COPY that uses SrcReg after is was killed.
1832 if (isKill)
1833 for (unsigned j = i + 2; j < e; j += 2)
1834 if (MI->getOperand(j).getReg() == SrcReg) {
1835 MI->getOperand(j).setIsKill();
1836 isKill = false;
1837 break;
1838 }
1839
Evan Cheng054dbb82010-05-13 00:00:35 +00001840 MachineBasicBlock::iterator InsertLoc = MI;
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001841 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1842 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
Bob Wilson495de3b2010-12-17 01:21:12 +00001843 .addReg(DstReg, RegState::Define, SubIdx)
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001844 .addReg(SrcReg, getKillRegState(isKill));
1845 MI->getOperand(i).setReg(0);
1846 if (LV && isKill)
1847 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1848 DEBUG(dbgs() << "Inserted: " << *CopyMI);
Evan Cheng0bcccac2010-05-11 00:04:31 +00001849 }
1850 }
1851
1852 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1853 unsigned SrcReg = MI->getOperand(i).getReg();
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001854 if (!SrcReg) continue;
Evan Cheng53c779b2010-05-17 20:57:12 +00001855 unsigned SubIdx = MI->getOperand(i+1).getImm();
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001856 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001857 }
1858
Evan Cheng44bfdd32010-05-17 22:09:49 +00001859 if (IsImpDef) {
1860 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1861 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1862 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1863 MI->RemoveOperand(j);
1864 } else {
1865 DEBUG(dbgs() << "Eliminated: " << *MI);
1866 MI->eraseFromParent();
1867 }
Evan Chengb990a2f2010-05-14 23:21:14 +00001868
Jakob Stoklund Olesenfe181f42010-06-18 23:10:20 +00001869 // Try coalescing some EXTRACT_SUBREG instructions. This can create
1870 // INSERT_SUBREG instructions that must have <undef> flags added by
1871 // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1872 if (LV)
1873 CoalesceExtSubRegs(RealSrcs, DstReg);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001874 }
1875
Evan Chengfc6e6a92010-05-10 21:24:55 +00001876 RegSequences.clear();
Evan Cheng3d720fb2010-05-05 18:45:40 +00001877 return true;
1878}