blob: ee31dde6384aefbf892714eed9e1e395190f5e9b [file] [log] [blame]
David Goodwin2e7be612009-10-26 16:59:04 +00001//===----- CriticalAntiDepBreaker.cpp - Anti-dep breaker -------- ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the CriticalAntiDepBreaker class, which
11// implements register anti-dependence breaking along a blocks
12// critical path during post-RA scheduler.
13//
14//===----------------------------------------------------------------------===//
15
David Goodwin4de099d2009-11-03 20:57:50 +000016#define DEBUG_TYPE "post-RA-sched"
David Goodwin2e7be612009-10-26 16:59:04 +000017#include "CriticalAntiDepBreaker.h"
18#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
David Goodwin2e7be612009-10-26 16:59:04 +000020#include "llvm/Support/Debug.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Target/TargetRegisterInfo.h"
David Goodwin2e7be612009-10-26 16:59:04 +000026
27using namespace llvm;
28
29CriticalAntiDepBreaker::
Jakob Stoklund Olesenfa796dd2011-06-16 21:56:21 +000030CriticalAntiDepBreaker(MachineFunction& MFi, const RegisterClassInfo &RCI) :
David Goodwin2e7be612009-10-26 16:59:04 +000031 AntiDepBreaker(), MF(MFi),
32 MRI(MF.getRegInfo()),
Evan Cheng46df4eb2010-06-16 07:35:02 +000033 TII(MF.getTarget().getInstrInfo()),
David Goodwin2e7be612009-10-26 16:59:04 +000034 TRI(MF.getTarget().getRegisterInfo()),
Jakob Stoklund Olesenfa796dd2011-06-16 21:56:21 +000035 RegClassInfo(RCI),
Bill Wendling9c2a0342010-07-15 19:58:14 +000036 Classes(TRI->getNumRegs(), static_cast<const TargetRegisterClass *>(0)),
37 KillIndices(TRI->getNumRegs(), 0),
Benjamin Kramercff4ad72012-03-17 20:22:57 +000038 DefIndices(TRI->getNumRegs(), 0),
39 KeepRegs(TRI->getNumRegs(), false) {}
David Goodwin2e7be612009-10-26 16:59:04 +000040
41CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
42}
43
44void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
David Goodwin990d2852009-12-09 17:18:22 +000045 const unsigned BBSize = BB->size();
Bill Wendling9c2a0342010-07-15 19:58:14 +000046 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
47 // Clear out the register class data.
48 Classes[i] = static_cast<const TargetRegisterClass *>(0);
49
50 // Initialize the indices to indicate that no registers are live.
David Goodwin990d2852009-12-09 17:18:22 +000051 KillIndices[i] = ~0u;
52 DefIndices[i] = BBSize;
53 }
David Goodwin2e7be612009-10-26 16:59:04 +000054
55 // Clear "do not change" set.
Benjamin Kramercff4ad72012-03-17 20:22:57 +000056 KeepRegs.reset();
David Goodwin2e7be612009-10-26 16:59:04 +000057
Benjamin Kramer87f3dbc2012-03-16 15:46:47 +000058 bool IsReturnBlock = (BBSize != 0 && BB->back().isReturn());
David Goodwin2e7be612009-10-26 16:59:04 +000059
60 // Determine the live-out physregs for this block.
61 if (IsReturnBlock) {
62 // In a return block, examine the function live-out regs.
63 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
64 E = MRI.liveout_end(); I != E; ++I) {
Jakob Stoklund Olesenf152fe82012-06-01 20:36:54 +000065 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
66 unsigned Reg = *AI;
67 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
68 KillIndices[Reg] = BBSize;
69 DefIndices[Reg] = ~0u;
David Goodwin2e7be612009-10-26 16:59:04 +000070 }
71 }
David Goodwin2e7be612009-10-26 16:59:04 +000072 }
73
Evan Cheng46df4eb2010-06-16 07:35:02 +000074 // In a non-return block, examine the live-in regs of all successors.
75 // Note a return block can have successors if the return instruction is
76 // predicated.
77 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
78 SE = BB->succ_end(); SI != SE; ++SI)
79 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
80 E = (*SI)->livein_end(); I != E; ++I) {
Jakob Stoklund Olesenf152fe82012-06-01 20:36:54 +000081 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
82 unsigned Reg = *AI;
83 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
84 KillIndices[Reg] = BBSize;
85 DefIndices[Reg] = ~0u;
Evan Cheng46df4eb2010-06-16 07:35:02 +000086 }
87 }
88
David Goodwin2e7be612009-10-26 16:59:04 +000089 // Mark live-out callee-saved registers. In a return block this is
90 // all callee-saved registers. In non-return this is any
91 // callee-saved register that is not saved in the prolog.
92 const MachineFrameInfo *MFI = MF.getFrameInfo();
93 BitVector Pristine = MFI->getPristineRegs(BB);
Craig Topper015f2282012-03-04 03:33:22 +000094 for (const uint16_t *I = TRI->getCalleeSavedRegs(&MF); *I; ++I) {
Jakob Stoklund Olesenf152fe82012-06-01 20:36:54 +000095 if (!IsReturnBlock && !Pristine.test(*I)) continue;
96 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
97 unsigned Reg = *AI;
98 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
99 KillIndices[Reg] = BBSize;
100 DefIndices[Reg] = ~0u;
David Goodwin2e7be612009-10-26 16:59:04 +0000101 }
102 }
103}
104
105void CriticalAntiDepBreaker::FinishBlock() {
106 RegRefs.clear();
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000107 KeepRegs.reset();
David Goodwin2e7be612009-10-26 16:59:04 +0000108}
109
110void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
111 unsigned InsertPosIndex) {
Dale Johannesenb0812f12010-03-05 00:02:59 +0000112 if (MI->isDebugValue())
113 return;
David Goodwin2e7be612009-10-26 16:59:04 +0000114 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
115
Bob Wilsonf70007e2010-10-02 01:49:29 +0000116 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
117 if (KillIndices[Reg] != ~0u) {
118 // If Reg is currently live, then mark that it can't be renamed as
119 // we don't know the extent of its live-range anymore (now that it
120 // has been scheduled).
121 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
122 KillIndices[Reg] = Count;
123 } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
124 // Any register which was defined within the previous scheduling region
125 // may have been rescheduled and its lifetime may overlap with registers
126 // in ways not reflected in our current liveness state. For each such
127 // register, adjust the liveness state to be conservatively correct.
David Goodwin2e7be612009-10-26 16:59:04 +0000128 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
Bill Wendling9c2a0342010-07-15 19:58:14 +0000129
David Goodwin2e7be612009-10-26 16:59:04 +0000130 // Move the def index to the end of the previous region, to reflect
131 // that the def could theoretically have been scheduled at the end.
132 DefIndices[Reg] = InsertPosIndex;
133 }
Bob Wilsonf70007e2010-10-02 01:49:29 +0000134 }
David Goodwin2e7be612009-10-26 16:59:04 +0000135
136 PrescanInstruction(MI);
137 ScanInstruction(MI, Count);
138}
139
140/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
141/// critical path.
Dan Gohman66db3a02010-04-19 23:11:58 +0000142static const SDep *CriticalPathStep(const SUnit *SU) {
143 const SDep *Next = 0;
David Goodwin2e7be612009-10-26 16:59:04 +0000144 unsigned NextDepth = 0;
145 // Find the predecessor edge with the greatest depth.
Dan Gohman66db3a02010-04-19 23:11:58 +0000146 for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
David Goodwin2e7be612009-10-26 16:59:04 +0000147 P != PE; ++P) {
Dan Gohman66db3a02010-04-19 23:11:58 +0000148 const SUnit *PredSU = P->getSUnit();
David Goodwin2e7be612009-10-26 16:59:04 +0000149 unsigned PredLatency = P->getLatency();
150 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
151 // In the case of a latency tie, prefer an anti-dependency edge over
152 // other types of edges.
153 if (NextDepth < PredTotalLatency ||
154 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
155 NextDepth = PredTotalLatency;
156 Next = &*P;
157 }
158 }
159 return Next;
160}
161
162void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
Evan Cheng46df4eb2010-06-16 07:35:02 +0000163 // It's not safe to change register allocation for source operands of
164 // that have special allocation requirements. Also assume all registers
165 // used in a call must not be changed (ABI).
166 // FIXME: The issue with predicated instruction is more complex. We are being
Bob Wilson59718a42010-09-10 22:42:21 +0000167 // conservative here because the kill markers cannot be trusted after
Evan Cheng46df4eb2010-06-16 07:35:02 +0000168 // if-conversion:
169 // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
170 // ...
171 // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
172 // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
173 // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
174 //
175 // The first R6 kill is not really a kill since it's killed by a predicated
176 // instruction which may not be executed. The second R6 def may or may not
177 // re-define R6 so it's not safe to change it since the last R6 use cannot be
178 // changed.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000179 bool Special = MI->isCall() ||
180 MI->hasExtraSrcRegAllocReq() ||
Evan Cheng46df4eb2010-06-16 07:35:02 +0000181 TII->isPredicated(MI);
182
David Goodwin2e7be612009-10-26 16:59:04 +0000183 // Scan the register operands for this instruction and update
184 // Classes and RegRefs.
185 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
186 MachineOperand &MO = MI->getOperand(i);
187 if (!MO.isReg()) continue;
188 unsigned Reg = MO.getReg();
189 if (Reg == 0) continue;
190 const TargetRegisterClass *NewRC = 0;
Jim Grosbach01384ef2010-05-14 21:20:46 +0000191
David Goodwin2e7be612009-10-26 16:59:04 +0000192 if (i < MI->getDesc().getNumOperands())
Jakob Stoklund Olesen397fc482012-05-07 22:10:26 +0000193 NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
David Goodwin2e7be612009-10-26 16:59:04 +0000194
195 // For now, only allow the register to be changed if its register
196 // class is consistent across all uses.
197 if (!Classes[Reg] && NewRC)
198 Classes[Reg] = NewRC;
199 else if (!NewRC || Classes[Reg] != NewRC)
200 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
201
202 // Now check for aliases.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000203 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
David Goodwin2e7be612009-10-26 16:59:04 +0000204 // If an alias of the reg is used during the live range, give up.
205 // Note that this allows us to skip checking if AntiDepReg
206 // overlaps with any of the aliases, among other things.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000207 unsigned AliasReg = *AI;
David Goodwin2e7be612009-10-26 16:59:04 +0000208 if (Classes[AliasReg]) {
209 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
210 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
211 }
212 }
213
214 // If we're still willing to consider this register, note the reference.
215 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
216 RegRefs.insert(std::make_pair(Reg, &MO));
217
Evan Cheng46df4eb2010-06-16 07:35:02 +0000218 if (MO.isUse() && Special) {
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000219 if (!KeepRegs.test(Reg)) {
220 KeepRegs.set(Reg);
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000221 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
222 KeepRegs.set(*SubRegs);
David Goodwin2e7be612009-10-26 16:59:04 +0000223 }
224 }
225 }
226}
227
228void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
229 unsigned Count) {
230 // Update liveness.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000231 // Proceeding upwards, registers that are defed but not used in this
David Goodwin2e7be612009-10-26 16:59:04 +0000232 // instruction are now dead.
David Goodwin2e7be612009-10-26 16:59:04 +0000233
Evan Cheng46df4eb2010-06-16 07:35:02 +0000234 if (!TII->isPredicated(MI)) {
235 // Predicated defs are modeled as read + write, i.e. similar to two
236 // address updates.
237 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
238 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesenbbad2f12012-02-23 01:15:26 +0000239
240 if (MO.isRegMask())
241 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
242 if (MO.clobbersPhysReg(i)) {
243 DefIndices[i] = Count;
244 KillIndices[i] = ~0u;
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000245 KeepRegs.reset(i);
Jakob Stoklund Olesenbbad2f12012-02-23 01:15:26 +0000246 Classes[i] = 0;
247 RegRefs.erase(i);
248 }
249
Evan Cheng46df4eb2010-06-16 07:35:02 +0000250 if (!MO.isReg()) continue;
251 unsigned Reg = MO.getReg();
252 if (Reg == 0) continue;
253 if (!MO.isDef()) continue;
254 // Ignore two-addr defs.
255 if (MI->isRegTiedToUseOperand(i)) continue;
256
257 DefIndices[Reg] = Count;
258 KillIndices[Reg] = ~0u;
259 assert(((KillIndices[Reg] == ~0u) !=
260 (DefIndices[Reg] == ~0u)) &&
261 "Kill and Def maps aren't consistent for Reg!");
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000262 KeepRegs.reset(Reg);
Evan Cheng46df4eb2010-06-16 07:35:02 +0000263 Classes[Reg] = 0;
264 RegRefs.erase(Reg);
265 // Repeat, for all subregs.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000266 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
267 unsigned SubregReg = *SubRegs;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000268 DefIndices[SubregReg] = Count;
269 KillIndices[SubregReg] = ~0u;
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000270 KeepRegs.reset(SubregReg);
Evan Cheng46df4eb2010-06-16 07:35:02 +0000271 Classes[SubregReg] = 0;
272 RegRefs.erase(SubregReg);
273 }
274 // Conservatively mark super-registers as unusable.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000275 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
276 Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
David Goodwin2e7be612009-10-26 16:59:04 +0000277 }
278 }
279 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
280 MachineOperand &MO = MI->getOperand(i);
281 if (!MO.isReg()) continue;
282 unsigned Reg = MO.getReg();
283 if (Reg == 0) continue;
284 if (!MO.isUse()) continue;
285
286 const TargetRegisterClass *NewRC = 0;
287 if (i < MI->getDesc().getNumOperands())
Jakob Stoklund Olesen397fc482012-05-07 22:10:26 +0000288 NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
David Goodwin2e7be612009-10-26 16:59:04 +0000289
290 // For now, only allow the register to be changed if its register
291 // class is consistent across all uses.
292 if (!Classes[Reg] && NewRC)
293 Classes[Reg] = NewRC;
294 else if (!NewRC || Classes[Reg] != NewRC)
295 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
296
297 RegRefs.insert(std::make_pair(Reg, &MO));
298
299 // It wasn't previously live but now it is, this is a kill.
300 if (KillIndices[Reg] == ~0u) {
301 KillIndices[Reg] = Count;
302 DefIndices[Reg] = ~0u;
303 assert(((KillIndices[Reg] == ~0u) !=
304 (DefIndices[Reg] == ~0u)) &&
305 "Kill and Def maps aren't consistent for Reg!");
306 }
307 // Repeat, for all aliases.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000308 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
309 unsigned AliasReg = *AI;
David Goodwin2e7be612009-10-26 16:59:04 +0000310 if (KillIndices[AliasReg] == ~0u) {
311 KillIndices[AliasReg] = Count;
312 DefIndices[AliasReg] = ~0u;
313 }
314 }
315 }
316}
317
Andrew Trickbc4bd922011-02-08 17:39:46 +0000318// Check all machine operands that reference the antidependent register and must
319// be replaced by NewReg. Return true if any of their parent instructions may
320// clobber the new register.
321//
322// Note: AntiDepReg may be referenced by a two-address instruction such that
323// it's use operand is tied to a def operand. We guard against the case in which
324// the two-address instruction also defines NewReg, as may happen with
325// pre/postincrement loads. In this case, both the use and def operands are in
326// RegRefs because the def is inserted by PrescanInstruction and not erased
327// during ScanInstruction. So checking for an instructions with definitions of
328// both NewReg and AntiDepReg covers it.
Andrew Trick46388522010-11-02 18:16:45 +0000329bool
Andrew Trickbc4bd922011-02-08 17:39:46 +0000330CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
331 RegRefIter RegRefEnd,
332 unsigned NewReg)
Andrew Trick46388522010-11-02 18:16:45 +0000333{
334 for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {
Andrew Trickbc4bd922011-02-08 17:39:46 +0000335 MachineOperand *RefOper = I->second;
336
337 // Don't allow the instruction defining AntiDepReg to earlyclobber its
338 // operands, in case they may be assigned to NewReg. In this case antidep
339 // breaking must fail, but it's too rare to bother optimizing.
340 if (RefOper->isDef() && RefOper->isEarlyClobber())
Andrew Trick46388522010-11-02 18:16:45 +0000341 return true;
Andrew Trickbc4bd922011-02-08 17:39:46 +0000342
343 // Handle cases in which this instructions defines NewReg.
344 MachineInstr *MI = RefOper->getParent();
345 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
346 const MachineOperand &CheckOper = MI->getOperand(i);
347
Jakob Stoklund Olesenbbad2f12012-02-23 01:15:26 +0000348 if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
349 return true;
350
Andrew Trickbc4bd922011-02-08 17:39:46 +0000351 if (!CheckOper.isReg() || !CheckOper.isDef() ||
352 CheckOper.getReg() != NewReg)
353 continue;
354
355 // Don't allow the instruction to define NewReg and AntiDepReg.
356 // When AntiDepReg is renamed it will be an illegal op.
357 if (RefOper->isDef())
358 return true;
359
360 // Don't allow an instruction using AntiDepReg to be earlyclobbered by
361 // NewReg
362 if (CheckOper.isEarlyClobber())
363 return true;
364
365 // Don't allow inline asm to define NewReg at all. Who know what it's
366 // doing with it.
367 if (MI->isInlineAsm())
368 return true;
369 }
Andrew Trick46388522010-11-02 18:16:45 +0000370 }
371 return false;
372}
373
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000374unsigned CriticalAntiDepBreaker::
375findSuitableFreeRegister(RegRefIter RegRefBegin,
376 RegRefIter RegRefEnd,
377 unsigned AntiDepReg,
378 unsigned LastNewReg,
379 const TargetRegisterClass *RC,
380 SmallVector<unsigned, 2> &Forbid)
Jim Grosbach2973b572010-01-06 16:48:02 +0000381{
Jakob Stoklund Olesen39b5c0c2012-11-29 03:34:17 +0000382 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
Jakob Stoklund Olesenfa796dd2011-06-16 21:56:21 +0000383 for (unsigned i = 0; i != Order.size(); ++i) {
384 unsigned NewReg = Order[i];
David Goodwin2e7be612009-10-26 16:59:04 +0000385 // Don't replace a register with itself.
386 if (NewReg == AntiDepReg) continue;
387 // Don't replace a register with one that was recently used to repair
388 // an anti-dependence with this AntiDepReg, because that would
389 // re-introduce that anti-dependence.
390 if (NewReg == LastNewReg) continue;
Andrew Trick46388522010-11-02 18:16:45 +0000391 // If any instructions that define AntiDepReg also define the NewReg, it's
392 // not suitable. For example, Instruction with multiple definitions can
393 // result in this condition.
Andrew Trickbc4bd922011-02-08 17:39:46 +0000394 if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;
David Goodwin2e7be612009-10-26 16:59:04 +0000395 // If NewReg is dead and NewReg's most recent def is not before
396 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Jim Grosbach2973b572010-01-06 16:48:02 +0000397 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
398 && "Kill and Def maps aren't consistent for AntiDepReg!");
399 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
400 && "Kill and Def maps aren't consistent for NewReg!");
David Goodwin2e7be612009-10-26 16:59:04 +0000401 if (KillIndices[NewReg] != ~0u ||
402 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
403 KillIndices[AntiDepReg] > DefIndices[NewReg])
404 continue;
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000405 // If NewReg overlaps any of the forbidden registers, we can't use it.
406 bool Forbidden = false;
407 for (SmallVector<unsigned, 2>::iterator it = Forbid.begin(),
408 ite = Forbid.end(); it != ite; ++it)
409 if (TRI->regsOverlap(NewReg, *it)) {
410 Forbidden = true;
411 break;
412 }
413 if (Forbidden) continue;
David Goodwin2e7be612009-10-26 16:59:04 +0000414 return NewReg;
415 }
416
417 // No registers are free and available!
418 return 0;
419}
420
421unsigned CriticalAntiDepBreaker::
Dan Gohman66db3a02010-04-19 23:11:58 +0000422BreakAntiDependencies(const std::vector<SUnit>& SUnits,
423 MachineBasicBlock::iterator Begin,
424 MachineBasicBlock::iterator End,
Devang Patele29e8e12011-06-02 21:26:52 +0000425 unsigned InsertPosIndex,
426 DbgValueVector &DbgValues) {
David Goodwin2e7be612009-10-26 16:59:04 +0000427 // The code below assumes that there is at least one instruction,
428 // so just duck out immediately if the block is empty.
429 if (SUnits.empty()) return 0;
430
Jim Grosbach533934e2010-06-01 23:48:44 +0000431 // Keep a map of the MachineInstr*'s back to the SUnit representing them.
432 // This is used for updating debug information.
Andrew Trickb4566a92012-02-22 06:08:11 +0000433 //
434 // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
Jim Grosbach533934e2010-06-01 23:48:44 +0000435 DenseMap<MachineInstr*,const SUnit*> MISUnitMap;
436
David Goodwin2e7be612009-10-26 16:59:04 +0000437 // Find the node at the bottom of the critical path.
Dan Gohman66db3a02010-04-19 23:11:58 +0000438 const SUnit *Max = 0;
David Goodwin2e7be612009-10-26 16:59:04 +0000439 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Dan Gohman66db3a02010-04-19 23:11:58 +0000440 const SUnit *SU = &SUnits[i];
Jim Grosbach533934e2010-06-01 23:48:44 +0000441 MISUnitMap[SU->getInstr()] = SU;
David Goodwin2e7be612009-10-26 16:59:04 +0000442 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
443 Max = SU;
444 }
445
446#ifndef NDEBUG
447 {
David Greene89d6a242010-01-04 17:47:05 +0000448 DEBUG(dbgs() << "Critical path has total latency "
David Goodwin2e7be612009-10-26 16:59:04 +0000449 << (Max->getDepth() + Max->Latency) << "\n");
David Greene89d6a242010-01-04 17:47:05 +0000450 DEBUG(dbgs() << "Available regs:");
David Goodwin2e7be612009-10-26 16:59:04 +0000451 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
452 if (KillIndices[Reg] == ~0u)
David Greene89d6a242010-01-04 17:47:05 +0000453 DEBUG(dbgs() << " " << TRI->getName(Reg));
David Goodwin2e7be612009-10-26 16:59:04 +0000454 }
David Greene89d6a242010-01-04 17:47:05 +0000455 DEBUG(dbgs() << '\n');
David Goodwin2e7be612009-10-26 16:59:04 +0000456 }
457#endif
458
459 // Track progress along the critical path through the SUnit graph as we walk
460 // the instructions.
Dan Gohman66db3a02010-04-19 23:11:58 +0000461 const SUnit *CriticalPathSU = Max;
David Goodwin2e7be612009-10-26 16:59:04 +0000462 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
463
464 // Consider this pattern:
465 // A = ...
466 // ... = A
467 // A = ...
468 // ... = A
469 // A = ...
470 // ... = A
471 // A = ...
472 // ... = A
473 // There are three anti-dependencies here, and without special care,
474 // we'd break all of them using the same register:
475 // A = ...
476 // ... = A
477 // B = ...
478 // ... = B
479 // B = ...
480 // ... = B
481 // B = ...
482 // ... = B
483 // because at each anti-dependence, B is the first register that
484 // isn't A which is free. This re-introduces anti-dependencies
485 // at all but one of the original anti-dependencies that we were
486 // trying to break. To avoid this, keep track of the most recent
487 // register that each register was replaced with, avoid
488 // using it to repair an anti-dependence on the same register.
489 // This lets us produce this:
490 // A = ...
491 // ... = A
492 // B = ...
493 // ... = B
494 // C = ...
495 // ... = C
496 // B = ...
497 // ... = B
498 // This still has an anti-dependence on B, but at least it isn't on the
499 // original critical path.
500 //
501 // TODO: If we tracked more than one register here, we could potentially
502 // fix that remaining critical edge too. This is a little more involved,
503 // because unlike the most recent register, less recent registers should
504 // still be considered, though only if no other registers are available.
Bill Wendling9c2a0342010-07-15 19:58:14 +0000505 std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
David Goodwin2e7be612009-10-26 16:59:04 +0000506
507 // Attempt to break anti-dependence edges on the critical path. Walk the
508 // instructions from the bottom up, tracking information about liveness
509 // as we go to help determine which registers are available.
510 unsigned Broken = 0;
511 unsigned Count = InsertPosIndex - 1;
512 for (MachineBasicBlock::iterator I = End, E = Begin;
513 I != E; --Count) {
514 MachineInstr *MI = --I;
Dale Johannesenb0812f12010-03-05 00:02:59 +0000515 if (MI->isDebugValue())
516 continue;
David Goodwin2e7be612009-10-26 16:59:04 +0000517
518 // Check if this instruction has a dependence on the critical path that
519 // is an anti-dependence that we may be able to break. If it is, set
520 // AntiDepReg to the non-zero register associated with the anti-dependence.
521 //
522 // We limit our attention to the critical path as a heuristic to avoid
523 // breaking anti-dependence edges that aren't going to significantly
524 // impact the overall schedule. There are a limited number of registers
525 // and we want to save them for the important edges.
Jim Grosbach01384ef2010-05-14 21:20:46 +0000526 //
David Goodwin2e7be612009-10-26 16:59:04 +0000527 // TODO: Instructions with multiple defs could have multiple
528 // anti-dependencies. The current code here only knows how to break one
529 // edge per instruction. Note that we'd have to be able to break all of
530 // the anti-dependencies in an instruction in order to be effective.
531 unsigned AntiDepReg = 0;
532 if (MI == CriticalPathMI) {
Dan Gohman66db3a02010-04-19 23:11:58 +0000533 if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
534 const SUnit *NextSU = Edge->getSUnit();
David Goodwin2e7be612009-10-26 16:59:04 +0000535
536 // Only consider anti-dependence edges.
537 if (Edge->getKind() == SDep::Anti) {
538 AntiDepReg = Edge->getReg();
539 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
Jakob Stoklund Olesen14d1dd92012-10-15 22:41:03 +0000540 if (!MRI.isAllocatable(AntiDepReg))
David Goodwin2e7be612009-10-26 16:59:04 +0000541 // Don't break anti-dependencies on non-allocatable registers.
542 AntiDepReg = 0;
Benjamin Kramercff4ad72012-03-17 20:22:57 +0000543 else if (KeepRegs.test(AntiDepReg))
David Goodwin2e7be612009-10-26 16:59:04 +0000544 // Don't break anti-dependencies if an use down below requires
545 // this exact register.
546 AntiDepReg = 0;
547 else {
548 // If the SUnit has other dependencies on the SUnit that it
549 // anti-depends on, don't bother breaking the anti-dependency
550 // since those edges would prevent such units from being
551 // scheduled past each other regardless.
552 //
553 // Also, if there are dependencies on other SUnits with the
554 // same register as the anti-dependency, don't attempt to
555 // break it.
Dan Gohman66db3a02010-04-19 23:11:58 +0000556 for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
David Goodwin2e7be612009-10-26 16:59:04 +0000557 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
558 if (P->getSUnit() == NextSU ?
559 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
560 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
561 AntiDepReg = 0;
562 break;
563 }
564 }
565 }
566 CriticalPathSU = NextSU;
567 CriticalPathMI = CriticalPathSU->getInstr();
568 } else {
569 // We've reached the end of the critical path.
570 CriticalPathSU = 0;
571 CriticalPathMI = 0;
572 }
573 }
574
575 PrescanInstruction(MI);
576
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000577 SmallVector<unsigned, 2> ForbidRegs;
578
Evan Cheng46df4eb2010-06-16 07:35:02 +0000579 // If MI's defs have a special allocation requirement, don't allow
580 // any def registers to be changed. Also assume all registers
581 // defined in a call must not be changed (ABI).
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000582 if (MI->isCall() || MI->hasExtraDefRegAllocReq() ||
Evan Cheng46df4eb2010-06-16 07:35:02 +0000583 TII->isPredicated(MI))
David Goodwin2e7be612009-10-26 16:59:04 +0000584 // If this instruction's defs have special allocation requirement, don't
585 // break this anti-dependency.
586 AntiDepReg = 0;
587 else if (AntiDepReg) {
588 // If this instruction has a use of AntiDepReg, breaking it
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000589 // is invalid. If the instruction defines other registers,
590 // save a list of them so that we don't pick a new register
591 // that overlaps any of them.
David Goodwin2e7be612009-10-26 16:59:04 +0000592 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
593 MachineOperand &MO = MI->getOperand(i);
594 if (!MO.isReg()) continue;
595 unsigned Reg = MO.getReg();
596 if (Reg == 0) continue;
Evan Cheng46df4eb2010-06-16 07:35:02 +0000597 if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
David Goodwin2e7be612009-10-26 16:59:04 +0000598 AntiDepReg = 0;
599 break;
600 }
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000601 if (MO.isDef() && Reg != AntiDepReg)
602 ForbidRegs.push_back(Reg);
David Goodwin2e7be612009-10-26 16:59:04 +0000603 }
604 }
605
606 // Determine AntiDepReg's register class, if it is live and is
607 // consistently used within a single class.
608 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
609 assert((AntiDepReg == 0 || RC != NULL) &&
610 "Register should be live if it's causing an anti-dependence!");
611 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
612 AntiDepReg = 0;
613
614 // Look for a suitable register to use to break the anti-depenence.
615 //
616 // TODO: Instead of picking the first free register, consider which might
617 // be the best.
618 if (AntiDepReg != 0) {
Andrew Trick46388522010-11-02 18:16:45 +0000619 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
620 std::multimap<unsigned, MachineOperand *>::iterator>
621 Range = RegRefs.equal_range(AntiDepReg);
622 if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
623 AntiDepReg,
David Goodwin2e7be612009-10-26 16:59:04 +0000624 LastNewReg[AntiDepReg],
Bill Schmidt5ff776b2013-01-28 18:36:58 +0000625 RC, ForbidRegs)) {
David Greene89d6a242010-01-04 17:47:05 +0000626 DEBUG(dbgs() << "Breaking anti-dependence edge on "
David Goodwin2e7be612009-10-26 16:59:04 +0000627 << TRI->getName(AntiDepReg)
628 << " with " << RegRefs.count(AntiDepReg) << " references"
629 << " using " << TRI->getName(NewReg) << "!\n");
630
631 // Update the references to the old register to refer to the new
632 // register.
David Goodwin2e7be612009-10-26 16:59:04 +0000633 for (std::multimap<unsigned, MachineOperand *>::iterator
Jim Grosbach533934e2010-06-01 23:48:44 +0000634 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
David Goodwin2e7be612009-10-26 16:59:04 +0000635 Q->second->setReg(NewReg);
Jim Grosbach533934e2010-06-01 23:48:44 +0000636 // If the SU for the instruction being updated has debug information
637 // related to the anti-dependency register, make sure to update that
638 // as well.
639 const SUnit *SU = MISUnitMap[Q->second->getParent()];
Jim Grosbach086723d2010-06-02 15:29:36 +0000640 if (!SU) continue;
Devang Patele29e8e12011-06-02 21:26:52 +0000641 for (DbgValueVector::iterator DVI = DbgValues.begin(),
642 DVE = DbgValues.end(); DVI != DVE; ++DVI)
643 if (DVI->second == Q->second->getParent())
644 UpdateDbgValue(DVI->first, AntiDepReg, NewReg);
Jim Grosbach533934e2010-06-01 23:48:44 +0000645 }
David Goodwin2e7be612009-10-26 16:59:04 +0000646
647 // We just went back in time and modified history; the
Bob Wilsonf70007e2010-10-02 01:49:29 +0000648 // liveness information for the anti-dependence reg is now
David Goodwin2e7be612009-10-26 16:59:04 +0000649 // inconsistent. Set the state as if it were dead.
650 Classes[NewReg] = Classes[AntiDepReg];
651 DefIndices[NewReg] = DefIndices[AntiDepReg];
652 KillIndices[NewReg] = KillIndices[AntiDepReg];
653 assert(((KillIndices[NewReg] == ~0u) !=
654 (DefIndices[NewReg] == ~0u)) &&
655 "Kill and Def maps aren't consistent for NewReg!");
656
657 Classes[AntiDepReg] = 0;
658 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
659 KillIndices[AntiDepReg] = ~0u;
660 assert(((KillIndices[AntiDepReg] == ~0u) !=
661 (DefIndices[AntiDepReg] == ~0u)) &&
662 "Kill and Def maps aren't consistent for AntiDepReg!");
663
664 RegRefs.erase(AntiDepReg);
665 LastNewReg[AntiDepReg] = NewReg;
666 ++Broken;
667 }
668 }
669
670 ScanInstruction(MI, Count);
671 }
672
673 return Broken;
674}