1 //===- AggressiveAntiDepBreaker.cpp - Anti-dep breaker --------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the AggressiveAntiDepBreaker class, which
10 // implements register anti-dependence breaking during post-RA
11 // scheduling. It attempts to break all anti-dependencies within a
14 //===----------------------------------------------------------------------===//
16 #include "AggressiveAntiDepBreaker.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/MachineValueType.h"
27 #include "llvm/CodeGen/RegisterClassInfo.h"
28 #include "llvm/CodeGen/ScheduleDAG.h"
29 #include "llvm/CodeGen/TargetInstrInfo.h"
30 #include "llvm/CodeGen/TargetRegisterInfo.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
41 #define DEBUG_TYPE "post-RA-sched"
43 // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
45 DebugDiv("agg-antidep-debugdiv",
46 cl::desc("Debug control for aggressive anti-dep breaker"),
47 cl::init(0), cl::Hidden
);
50 DebugMod("agg-antidep-debugmod",
51 cl::desc("Debug control for aggressive anti-dep breaker"),
52 cl::init(0), cl::Hidden
);
54 AggressiveAntiDepState::AggressiveAntiDepState(const unsigned TargetRegs
,
55 MachineBasicBlock
*BB
)
56 : NumTargetRegs(TargetRegs
), GroupNodes(TargetRegs
, 0),
57 GroupNodeIndices(TargetRegs
, 0), KillIndices(TargetRegs
, 0),
58 DefIndices(TargetRegs
, 0) {
59 const unsigned BBSize
= BB
->size();
60 for (unsigned i
= 0; i
< NumTargetRegs
; ++i
) {
61 // Initialize all registers to be in their own group. Initially we
62 // assign the register to the same-indexed GroupNode.
63 GroupNodeIndices
[i
] = i
;
64 // Initialize the indices to indicate that no registers are live.
66 DefIndices
[i
] = BBSize
;
70 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg
) {
71 unsigned Node
= GroupNodeIndices
[Reg
];
72 while (GroupNodes
[Node
] != Node
)
73 Node
= GroupNodes
[Node
];
78 void AggressiveAntiDepState::GetGroupRegs(
80 std::vector
<unsigned> &Regs
,
81 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
> *RegRefs
)
83 for (unsigned Reg
= 0; Reg
!= NumTargetRegs
; ++Reg
) {
84 if ((GetGroup(Reg
) == Group
) && (RegRefs
->count(Reg
) > 0))
89 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1
, unsigned Reg2
) {
90 assert(GroupNodes
[0] == 0 && "GroupNode 0 not parent!");
91 assert(GroupNodeIndices
[0] == 0 && "Reg 0 not in Group 0!");
93 // find group for each register
94 unsigned Group1
= GetGroup(Reg1
);
95 unsigned Group2
= GetGroup(Reg2
);
97 // if either group is 0, then that must become the parent
98 unsigned Parent
= (Group1
== 0) ? Group1
: Group2
;
99 unsigned Other
= (Parent
== Group1
) ? Group2
: Group1
;
100 GroupNodes
.at(Other
) = Parent
;
104 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg
) {
105 // Create a new GroupNode for Reg. Reg's existing GroupNode must
106 // stay as is because there could be other GroupNodes referring to
108 unsigned idx
= GroupNodes
.size();
109 GroupNodes
.push_back(idx
);
110 GroupNodeIndices
[Reg
] = idx
;
114 bool AggressiveAntiDepState::IsLive(unsigned Reg
) {
115 // KillIndex must be defined and DefIndex not defined for a register
117 return((KillIndices
[Reg
] != ~0u) && (DefIndices
[Reg
] == ~0u));
120 AggressiveAntiDepBreaker::AggressiveAntiDepBreaker(
121 MachineFunction
&MFi
, const RegisterClassInfo
&RCI
,
122 TargetSubtargetInfo::RegClassVector
&CriticalPathRCs
)
123 : MF(MFi
), MRI(MF
.getRegInfo()), TII(MF
.getSubtarget().getInstrInfo()),
124 TRI(MF
.getSubtarget().getRegisterInfo()), RegClassInfo(RCI
) {
125 /* Collect a bitset of all registers that are only broken if they
126 are on the critical path. */
127 for (unsigned i
= 0, e
= CriticalPathRCs
.size(); i
< e
; ++i
) {
128 BitVector CPSet
= TRI
->getAllocatableSet(MF
, CriticalPathRCs
[i
]);
129 if (CriticalPathSet
.none())
130 CriticalPathSet
= CPSet
;
132 CriticalPathSet
|= CPSet
;
135 LLVM_DEBUG(dbgs() << "AntiDep Critical-Path Registers:");
136 LLVM_DEBUG(for (unsigned r
137 : CriticalPathSet
.set_bits()) dbgs()
138 << " " << printReg(r
, TRI
));
139 LLVM_DEBUG(dbgs() << '\n');
142 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
146 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock
*BB
) {
148 State
= new AggressiveAntiDepState(TRI
->getNumRegs(), BB
);
150 bool IsReturnBlock
= BB
->isReturnBlock();
151 std::vector
<unsigned> &KillIndices
= State
->GetKillIndices();
152 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
154 // Examine the live-in regs of all successors.
155 for (MachineBasicBlock
*Succ
: BB
->successors())
156 for (const auto &LI
: Succ
->liveins()) {
157 for (MCRegAliasIterator
AI(LI
.PhysReg
, TRI
, true); AI
.isValid(); ++AI
) {
159 State
->UnionGroups(Reg
, 0);
160 KillIndices
[Reg
] = BB
->size();
161 DefIndices
[Reg
] = ~0u;
165 // Mark live-out callee-saved registers. In a return block this is
166 // all callee-saved registers. In non-return this is any
167 // callee-saved register that is not saved in the prolog.
168 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
169 BitVector Pristine
= MFI
.getPristineRegs(MF
);
170 for (const MCPhysReg
*I
= MF
.getRegInfo().getCalleeSavedRegs(); *I
;
173 if (!IsReturnBlock
&& !Pristine
.test(Reg
))
175 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
) {
176 unsigned AliasReg
= *AI
;
177 State
->UnionGroups(AliasReg
, 0);
178 KillIndices
[AliasReg
] = BB
->size();
179 DefIndices
[AliasReg
] = ~0u;
184 void AggressiveAntiDepBreaker::FinishBlock() {
189 void AggressiveAntiDepBreaker::Observe(MachineInstr
&MI
, unsigned Count
,
190 unsigned InsertPosIndex
) {
191 assert(Count
< InsertPosIndex
&& "Instruction index out of expected range!");
193 std::set
<unsigned> PassthruRegs
;
194 GetPassthruRegs(MI
, PassthruRegs
);
195 PrescanInstruction(MI
, Count
, PassthruRegs
);
196 ScanInstruction(MI
, Count
);
198 LLVM_DEBUG(dbgs() << "Observe: ");
199 LLVM_DEBUG(MI
.dump());
200 LLVM_DEBUG(dbgs() << "\tRegs:");
202 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
203 for (unsigned Reg
= 1; Reg
!= TRI
->getNumRegs(); ++Reg
) {
204 // If Reg is current live, then mark that it can't be renamed as
205 // we don't know the extent of its live-range anymore (now that it
206 // has been scheduled). If it is not live but was defined in the
207 // previous schedule region, then set its def index to the most
208 // conservative location (i.e. the beginning of the previous
210 if (State
->IsLive(Reg
)) {
211 LLVM_DEBUG(if (State
->GetGroup(Reg
) != 0) dbgs()
212 << " " << printReg(Reg
, TRI
) << "=g" << State
->GetGroup(Reg
)
213 << "->g0(region live-out)");
214 State
->UnionGroups(Reg
, 0);
215 } else if ((DefIndices
[Reg
] < InsertPosIndex
)
216 && (DefIndices
[Reg
] >= Count
)) {
217 DefIndices
[Reg
] = Count
;
220 LLVM_DEBUG(dbgs() << '\n');
223 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr
&MI
,
224 MachineOperand
&MO
) {
225 if (!MO
.isReg() || !MO
.isImplicit())
228 Register Reg
= MO
.getReg();
232 MachineOperand
*Op
= nullptr;
234 Op
= MI
.findRegisterUseOperand(Reg
, true);
236 Op
= MI
.findRegisterDefOperand(Reg
);
238 return(Op
&& Op
->isImplicit());
241 void AggressiveAntiDepBreaker::GetPassthruRegs(
242 MachineInstr
&MI
, std::set
<unsigned> &PassthruRegs
) {
243 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
244 MachineOperand
&MO
= MI
.getOperand(i
);
245 if (!MO
.isReg()) continue;
246 if ((MO
.isDef() && MI
.isRegTiedToUseOperand(i
)) ||
247 IsImplicitDefUse(MI
, MO
)) {
248 const Register Reg
= MO
.getReg();
249 for (MCPhysReg SubReg
: TRI
->subregs_inclusive(Reg
))
250 PassthruRegs
.insert(SubReg
);
255 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
256 /// in SU that we want to consider for breaking.
257 static void AntiDepEdges(const SUnit
*SU
, std::vector
<const SDep
*> &Edges
) {
258 SmallSet
<unsigned, 4> RegSet
;
259 for (const SDep
&Pred
: SU
->Preds
) {
260 if ((Pred
.getKind() == SDep::Anti
) || (Pred
.getKind() == SDep::Output
)) {
261 if (RegSet
.insert(Pred
.getReg()).second
)
262 Edges
.push_back(&Pred
);
267 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
269 static const SUnit
*CriticalPathStep(const SUnit
*SU
) {
270 const SDep
*Next
= nullptr;
271 unsigned NextDepth
= 0;
272 // Find the predecessor edge with the greatest depth.
274 for (const SDep
&Pred
: SU
->Preds
) {
275 const SUnit
*PredSU
= Pred
.getSUnit();
276 unsigned PredLatency
= Pred
.getLatency();
277 unsigned PredTotalLatency
= PredSU
->getDepth() + PredLatency
;
278 // In the case of a latency tie, prefer an anti-dependency edge over
279 // other types of edges.
280 if (NextDepth
< PredTotalLatency
||
281 (NextDepth
== PredTotalLatency
&& Pred
.getKind() == SDep::Anti
)) {
282 NextDepth
= PredTotalLatency
;
288 return (Next
) ? Next
->getSUnit() : nullptr;
291 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg
, unsigned KillIdx
,
294 const char *footer
) {
295 std::vector
<unsigned> &KillIndices
= State
->GetKillIndices();
296 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
297 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
298 RegRefs
= State
->GetRegRefs();
300 // FIXME: We must leave subregisters of live super registers as live, so that
301 // we don't clear out the register tracking information for subregisters of
302 // super registers we're still tracking (and with which we're unioning
303 // subregister definitions).
304 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
)
305 if (TRI
->isSuperRegister(Reg
, *AI
) && State
->IsLive(*AI
)) {
306 LLVM_DEBUG(if (!header
&& footer
) dbgs() << footer
);
310 if (!State
->IsLive(Reg
)) {
311 KillIndices
[Reg
] = KillIdx
;
312 DefIndices
[Reg
] = ~0u;
314 State
->LeaveGroup(Reg
);
315 LLVM_DEBUG(if (header
) {
316 dbgs() << header
<< printReg(Reg
, TRI
);
319 LLVM_DEBUG(dbgs() << "->g" << State
->GetGroup(Reg
) << tag
);
320 // Repeat for subregisters. Note that we only do this if the superregister
321 // was not live because otherwise, regardless whether we have an explicit
322 // use of the subregister, the subregister's contents are needed for the
323 // uses of the superregister.
324 for (MCPhysReg SubregReg
: TRI
->subregs(Reg
)) {
325 if (!State
->IsLive(SubregReg
)) {
326 KillIndices
[SubregReg
] = KillIdx
;
327 DefIndices
[SubregReg
] = ~0u;
328 RegRefs
.erase(SubregReg
);
329 State
->LeaveGroup(SubregReg
);
330 LLVM_DEBUG(if (header
) {
331 dbgs() << header
<< printReg(Reg
, TRI
);
334 LLVM_DEBUG(dbgs() << " " << printReg(SubregReg
, TRI
) << "->g"
335 << State
->GetGroup(SubregReg
) << tag
);
340 LLVM_DEBUG(if (!header
&& footer
) dbgs() << footer
);
343 void AggressiveAntiDepBreaker::PrescanInstruction(
344 MachineInstr
&MI
, unsigned Count
, std::set
<unsigned> &PassthruRegs
) {
345 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
346 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
347 RegRefs
= State
->GetRegRefs();
349 // Handle dead defs by simulating a last-use of the register just
350 // after the def. A dead def can occur because the def is truly
351 // dead, or because only a subregister is live at the def. If we
352 // don't do this the dead def will be incorrectly merged into the
354 for (const MachineOperand
&MO
: MI
.all_defs()) {
355 Register Reg
= MO
.getReg();
356 if (Reg
== 0) continue;
358 HandleLastUse(Reg
, Count
+ 1, "", "\tDead Def: ", "\n");
361 LLVM_DEBUG(dbgs() << "\tDef Groups:");
362 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
363 MachineOperand
&MO
= MI
.getOperand(i
);
364 if (!MO
.isReg() || !MO
.isDef()) continue;
365 Register Reg
= MO
.getReg();
366 if (Reg
== 0) continue;
368 LLVM_DEBUG(dbgs() << " " << printReg(Reg
, TRI
) << "=g"
369 << State
->GetGroup(Reg
));
371 // If MI's defs have a special allocation requirement, don't allow
372 // any def registers to be changed. Also assume all registers
373 // defined in a call must not be changed (ABI). Inline assembly may
374 // reference either system calls or the register directly. Skip it until we
375 // can tell user specified registers from compiler-specified.
376 if (MI
.isCall() || MI
.hasExtraDefRegAllocReq() || TII
->isPredicated(MI
) ||
378 LLVM_DEBUG(if (State
->GetGroup(Reg
) != 0) dbgs() << "->g0(alloc-req)");
379 State
->UnionGroups(Reg
, 0);
382 // Any aliased that are live at this point are completely or
383 // partially defined here, so group those aliases with Reg.
384 for (MCRegAliasIterator
AI(Reg
, TRI
, false); AI
.isValid(); ++AI
) {
385 unsigned AliasReg
= *AI
;
386 if (State
->IsLive(AliasReg
)) {
387 State
->UnionGroups(Reg
, AliasReg
);
388 LLVM_DEBUG(dbgs() << "->g" << State
->GetGroup(Reg
) << "(via "
389 << printReg(AliasReg
, TRI
) << ")");
393 // Note register reference...
394 const TargetRegisterClass
*RC
= nullptr;
395 if (i
< MI
.getDesc().getNumOperands())
396 RC
= TII
->getRegClass(MI
.getDesc(), i
, TRI
, MF
);
397 AggressiveAntiDepState::RegisterReference RR
= { &MO
, RC
};
398 RegRefs
.insert(std::make_pair(Reg
, RR
));
401 LLVM_DEBUG(dbgs() << '\n');
403 // Scan the register defs for this instruction and update
405 for (const MachineOperand
&MO
: MI
.operands()) {
406 if (!MO
.isReg() || !MO
.isDef()) continue;
407 Register Reg
= MO
.getReg();
408 if (Reg
== 0) continue;
409 // Ignore KILLs and passthru registers for liveness...
410 if (MI
.isKill() || (PassthruRegs
.count(Reg
) != 0))
413 // Update def for Reg and aliases.
414 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
) {
415 // We need to be careful here not to define already-live super registers.
416 // If the super register is already live, then this definition is not
417 // a definition of the whole super register (just a partial insertion
418 // into it). Earlier subregister definitions (which we've not yet visited
419 // because we're iterating bottom-up) need to be linked to the same group
420 // as this definition.
421 if (TRI
->isSuperRegister(Reg
, *AI
) && State
->IsLive(*AI
))
424 DefIndices
[*AI
] = Count
;
429 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr
&MI
,
431 LLVM_DEBUG(dbgs() << "\tUse Groups:");
432 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
433 RegRefs
= State
->GetRegRefs();
435 // If MI's uses have special allocation requirement, don't allow
436 // any use registers to be changed. Also assume all registers
437 // used in a call must not be changed (ABI).
438 // Inline Assembly register uses also cannot be safely changed.
439 // FIXME: The issue with predicated instruction is more complex. We are being
440 // conservatively here because the kill markers cannot be trusted after
442 // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]
444 // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]
445 // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]
446 // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)
448 // The first R6 kill is not really a kill since it's killed by a predicated
449 // instruction which may not be executed. The second R6 def may or may not
450 // re-define R6 so it's not safe to change it since the last R6 use cannot be
452 bool Special
= MI
.isCall() || MI
.hasExtraSrcRegAllocReq() ||
453 TII
->isPredicated(MI
) || MI
.isInlineAsm();
455 // Scan the register uses for this instruction and update
456 // live-ranges, groups and RegRefs.
457 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
458 MachineOperand
&MO
= MI
.getOperand(i
);
459 if (!MO
.isReg() || !MO
.isUse()) continue;
460 Register Reg
= MO
.getReg();
461 if (Reg
== 0) continue;
463 LLVM_DEBUG(dbgs() << " " << printReg(Reg
, TRI
) << "=g"
464 << State
->GetGroup(Reg
));
466 // It wasn't previously live but now it is, this is a kill. Forget
467 // the previous live-range information and start a new live-range
469 HandleLastUse(Reg
, Count
, "(last-use)");
472 LLVM_DEBUG(if (State
->GetGroup(Reg
) != 0) dbgs() << "->g0(alloc-req)");
473 State
->UnionGroups(Reg
, 0);
476 // Note register reference...
477 const TargetRegisterClass
*RC
= nullptr;
478 if (i
< MI
.getDesc().getNumOperands())
479 RC
= TII
->getRegClass(MI
.getDesc(), i
, TRI
, MF
);
480 AggressiveAntiDepState::RegisterReference RR
= { &MO
, RC
};
481 RegRefs
.insert(std::make_pair(Reg
, RR
));
484 LLVM_DEBUG(dbgs() << '\n');
486 // Form a group of all defs and uses of a KILL instruction to ensure
487 // that all registers are renamed as a group.
489 LLVM_DEBUG(dbgs() << "\tKill Group:");
491 unsigned FirstReg
= 0;
492 for (const MachineOperand
&MO
: MI
.operands()) {
493 if (!MO
.isReg()) continue;
494 Register Reg
= MO
.getReg();
495 if (Reg
== 0) continue;
498 LLVM_DEBUG(dbgs() << "=" << printReg(Reg
, TRI
));
499 State
->UnionGroups(FirstReg
, Reg
);
501 LLVM_DEBUG(dbgs() << " " << printReg(Reg
, TRI
));
506 LLVM_DEBUG(dbgs() << "->g" << State
->GetGroup(FirstReg
) << '\n');
510 BitVector
AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg
) {
511 BitVector
BV(TRI
->getNumRegs(), false);
514 // Check all references that need rewriting for Reg. For each, use
515 // the corresponding register class to narrow the set of registers
516 // that are appropriate for renaming.
517 for (const auto &Q
: make_range(State
->GetRegRefs().equal_range(Reg
))) {
518 const TargetRegisterClass
*RC
= Q
.second
.RC
;
521 BitVector RCBV
= TRI
->getAllocatableSet(MF
, RC
);
529 LLVM_DEBUG(dbgs() << " " << TRI
->getRegClassName(RC
));
535 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
536 unsigned AntiDepGroupIndex
,
537 RenameOrderType
& RenameOrder
,
538 std::map
<unsigned, unsigned> &RenameMap
) {
539 std::vector
<unsigned> &KillIndices
= State
->GetKillIndices();
540 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
541 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
542 RegRefs
= State
->GetRegRefs();
544 // Collect all referenced registers in the same group as
545 // AntiDepReg. These all need to be renamed together if we are to
546 // break the anti-dependence.
547 std::vector
<unsigned> Regs
;
548 State
->GetGroupRegs(AntiDepGroupIndex
, Regs
, &RegRefs
);
549 assert(!Regs
.empty() && "Empty register group!");
553 // Find the "superest" register in the group. At the same time,
554 // collect the BitVector of registers that can be used to rename
556 LLVM_DEBUG(dbgs() << "\tRename Candidates for Group g" << AntiDepGroupIndex
558 std::map
<unsigned, BitVector
> RenameRegisterMap
;
559 unsigned SuperReg
= 0;
560 for (unsigned Reg
: Regs
) {
561 if ((SuperReg
== 0) || TRI
->isSuperRegister(SuperReg
, Reg
))
564 // If Reg has any references, then collect possible rename regs
565 if (RegRefs
.count(Reg
) > 0) {
566 LLVM_DEBUG(dbgs() << "\t\t" << printReg(Reg
, TRI
) << ":");
568 BitVector
&BV
= RenameRegisterMap
[Reg
];
570 BV
= GetRenameRegisters(Reg
);
574 for (unsigned r
: BV
.set_bits())
575 dbgs() << " " << printReg(r
, TRI
);
581 // All group registers should be a subreg of SuperReg.
582 for (unsigned Reg
: Regs
) {
583 if (Reg
== SuperReg
) continue;
584 bool IsSub
= TRI
->isSubRegister(SuperReg
, Reg
);
585 // FIXME: remove this once PR18663 has been properly fixed. For now,
586 // return a conservative answer:
587 // assert(IsSub && "Expecting group subregister");
593 // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
595 static int renamecnt
= 0;
596 if (renamecnt
++ % DebugDiv
!= DebugMod
)
599 dbgs() << "*** Performing rename " << printReg(SuperReg
, TRI
)
600 << " for debug ***\n";
604 // Check each possible rename register for SuperReg in round-robin
605 // order. If that register is available, and the corresponding
606 // registers are available for the other group subregisters, then we
607 // can use those registers to rename.
609 // FIXME: Using getMinimalPhysRegClass is very conservative. We should
610 // check every use of the register and find the largest register class
611 // that can be used in all of them.
612 const TargetRegisterClass
*SuperRC
=
613 TRI
->getMinimalPhysRegClass(SuperReg
, MVT::Other
);
615 ArrayRef
<MCPhysReg
> Order
= RegClassInfo
.getOrder(SuperRC
);
617 LLVM_DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
621 LLVM_DEBUG(dbgs() << "\tFind Registers:");
623 RenameOrder
.insert(RenameOrderType::value_type(SuperRC
, Order
.size()));
625 unsigned OrigR
= RenameOrder
[SuperRC
];
626 unsigned EndR
= ((OrigR
== Order
.size()) ? 0 : OrigR
);
629 if (R
== 0) R
= Order
.size();
631 const unsigned NewSuperReg
= Order
[R
];
632 // Don't consider non-allocatable registers
633 if (!MRI
.isAllocatable(NewSuperReg
)) continue;
634 // Don't replace a register with itself.
635 if (NewSuperReg
== SuperReg
) continue;
637 LLVM_DEBUG(dbgs() << " [" << printReg(NewSuperReg
, TRI
) << ':');
640 // For each referenced group register (which must be a SuperReg or
641 // a subregister of SuperReg), find the corresponding subregister
642 // of NewSuperReg and make sure it is free to be renamed.
643 for (unsigned Reg
: Regs
) {
645 if (Reg
== SuperReg
) {
646 NewReg
= NewSuperReg
;
648 unsigned NewSubRegIdx
= TRI
->getSubRegIndex(SuperReg
, Reg
);
649 if (NewSubRegIdx
!= 0)
650 NewReg
= TRI
->getSubReg(NewSuperReg
, NewSubRegIdx
);
653 LLVM_DEBUG(dbgs() << " " << printReg(NewReg
, TRI
));
655 // Check if Reg can be renamed to NewReg.
656 if (!RenameRegisterMap
[Reg
].test(NewReg
)) {
657 LLVM_DEBUG(dbgs() << "(no rename)");
661 // If NewReg is dead and NewReg's most recent def is not before
662 // Regs's kill, it's safe to replace Reg with NewReg. We
663 // must also check all aliases of NewReg, because we can't define a
664 // register when any sub or super is already live.
665 if (State
->IsLive(NewReg
) || (KillIndices
[Reg
] > DefIndices
[NewReg
])) {
666 LLVM_DEBUG(dbgs() << "(live)");
670 for (MCRegAliasIterator
AI(NewReg
, TRI
, false); AI
.isValid(); ++AI
) {
671 unsigned AliasReg
= *AI
;
672 if (State
->IsLive(AliasReg
) ||
673 (KillIndices
[Reg
] > DefIndices
[AliasReg
])) {
675 << "(alias " << printReg(AliasReg
, TRI
) << " live)");
684 // We cannot rename 'Reg' to 'NewReg' if one of the uses of 'Reg' also
685 // defines 'NewReg' via an early-clobber operand.
686 for (const auto &Q
: make_range(RegRefs
.equal_range(Reg
))) {
687 MachineInstr
*UseMI
= Q
.second
.Operand
->getParent();
688 int Idx
= UseMI
->findRegisterDefOperandIdx(NewReg
, false, true, TRI
);
692 if (UseMI
->getOperand(Idx
).isEarlyClobber()) {
693 LLVM_DEBUG(dbgs() << "(ec)");
698 // Also, we cannot rename 'Reg' to 'NewReg' if the instruction defining
699 // 'Reg' is an early-clobber define and that instruction also uses
701 for (const auto &Q
: make_range(RegRefs
.equal_range(Reg
))) {
702 if (!Q
.second
.Operand
->isDef() || !Q
.second
.Operand
->isEarlyClobber())
705 MachineInstr
*DefMI
= Q
.second
.Operand
->getParent();
706 if (DefMI
->readsRegister(NewReg
, TRI
)) {
707 LLVM_DEBUG(dbgs() << "(ec)");
712 // Record that 'Reg' can be renamed to 'NewReg'.
713 RenameMap
.insert(std::pair
<unsigned, unsigned>(Reg
, NewReg
));
716 // If we fall-out here, then every register in the group can be
717 // renamed, as recorded in RenameMap.
718 RenameOrder
.erase(SuperRC
);
719 RenameOrder
.insert(RenameOrderType::value_type(SuperRC
, R
));
720 LLVM_DEBUG(dbgs() << "]\n");
724 LLVM_DEBUG(dbgs() << ']');
727 LLVM_DEBUG(dbgs() << '\n');
729 // No registers are free and available!
733 /// BreakAntiDependencies - Identifiy anti-dependencies within the
734 /// ScheduleDAG and break them by renaming registers.
735 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
736 const std::vector
<SUnit
> &SUnits
,
737 MachineBasicBlock::iterator Begin
,
738 MachineBasicBlock::iterator End
,
739 unsigned InsertPosIndex
,
740 DbgValueVector
&DbgValues
) {
741 std::vector
<unsigned> &KillIndices
= State
->GetKillIndices();
742 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
743 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
744 RegRefs
= State
->GetRegRefs();
746 // The code below assumes that there is at least one instruction,
747 // so just duck out immediately if the block is empty.
748 if (SUnits
.empty()) return 0;
750 // For each regclass the next register to use for renaming.
751 RenameOrderType RenameOrder
;
753 // ...need a map from MI to SUnit.
754 std::map
<MachineInstr
*, const SUnit
*> MISUnitMap
;
755 for (const SUnit
&SU
: SUnits
)
756 MISUnitMap
.insert(std::make_pair(SU
.getInstr(), &SU
));
758 // Track progress along the critical path through the SUnit graph as
759 // we walk the instructions. This is needed for regclasses that only
760 // break critical-path anti-dependencies.
761 const SUnit
*CriticalPathSU
= nullptr;
762 MachineInstr
*CriticalPathMI
= nullptr;
763 if (CriticalPathSet
.any()) {
764 for (const SUnit
&SU
: SUnits
) {
765 if (!CriticalPathSU
||
766 ((SU
.getDepth() + SU
.Latency
) >
767 (CriticalPathSU
->getDepth() + CriticalPathSU
->Latency
))) {
768 CriticalPathSU
= &SU
;
771 assert(CriticalPathSU
&& "Failed to find SUnit critical path");
772 CriticalPathMI
= CriticalPathSU
->getInstr();
776 LLVM_DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
777 LLVM_DEBUG(dbgs() << "Available regs:");
778 for (unsigned Reg
= 1; Reg
< TRI
->getNumRegs(); ++Reg
) {
779 if (!State
->IsLive(Reg
))
780 LLVM_DEBUG(dbgs() << " " << printReg(Reg
, TRI
));
782 LLVM_DEBUG(dbgs() << '\n');
785 BitVector
RegAliases(TRI
->getNumRegs());
787 // Attempt to break anti-dependence edges. Walk the instructions
788 // from the bottom up, tracking information about liveness as we go
789 // to help determine which registers are available.
791 unsigned Count
= InsertPosIndex
- 1;
792 for (MachineBasicBlock::iterator I
= End
, E
= Begin
;
794 MachineInstr
&MI
= *--I
;
796 if (MI
.isDebugInstr())
799 LLVM_DEBUG(dbgs() << "Anti: ");
800 LLVM_DEBUG(MI
.dump());
802 std::set
<unsigned> PassthruRegs
;
803 GetPassthruRegs(MI
, PassthruRegs
);
805 // Process the defs in MI...
806 PrescanInstruction(MI
, Count
, PassthruRegs
);
808 // The dependence edges that represent anti- and output-
809 // dependencies that are candidates for breaking.
810 std::vector
<const SDep
*> Edges
;
811 const SUnit
*PathSU
= MISUnitMap
[&MI
];
812 AntiDepEdges(PathSU
, Edges
);
814 // If MI is not on the critical path, then we don't rename
815 // registers in the CriticalPathSet.
816 BitVector
*ExcludeRegs
= nullptr;
817 if (&MI
== CriticalPathMI
) {
818 CriticalPathSU
= CriticalPathStep(CriticalPathSU
);
819 CriticalPathMI
= (CriticalPathSU
) ? CriticalPathSU
->getInstr() : nullptr;
820 } else if (CriticalPathSet
.any()) {
821 ExcludeRegs
= &CriticalPathSet
;
824 // Ignore KILL instructions (they form a group in ScanInstruction
825 // but don't cause any anti-dependence breaking themselves)
827 // Attempt to break each anti-dependency...
828 for (const SDep
*Edge
: Edges
) {
829 SUnit
*NextSU
= Edge
->getSUnit();
831 if ((Edge
->getKind() != SDep::Anti
) &&
832 (Edge
->getKind() != SDep::Output
)) continue;
834 unsigned AntiDepReg
= Edge
->getReg();
835 LLVM_DEBUG(dbgs() << "\tAntidep reg: " << printReg(AntiDepReg
, TRI
));
836 assert(AntiDepReg
!= 0 && "Anti-dependence on reg0?");
838 if (!MRI
.isAllocatable(AntiDepReg
)) {
839 // Don't break anti-dependencies on non-allocatable registers.
840 LLVM_DEBUG(dbgs() << " (non-allocatable)\n");
842 } else if (ExcludeRegs
&& ExcludeRegs
->test(AntiDepReg
)) {
843 // Don't break anti-dependencies for critical path registers
844 // if not on the critical path
845 LLVM_DEBUG(dbgs() << " (not critical-path)\n");
847 } else if (PassthruRegs
.count(AntiDepReg
) != 0) {
848 // If the anti-dep register liveness "passes-thru", then
849 // don't try to change it. It will be changed along with
850 // the use if required to break an earlier antidep.
851 LLVM_DEBUG(dbgs() << " (passthru)\n");
854 // No anti-dep breaking for implicit deps
855 MachineOperand
*AntiDepOp
= MI
.findRegisterDefOperand(AntiDepReg
);
856 assert(AntiDepOp
&& "Can't find index for defined register operand");
857 if (!AntiDepOp
|| AntiDepOp
->isImplicit()) {
858 LLVM_DEBUG(dbgs() << " (implicit)\n");
862 // If the SUnit has other dependencies on the SUnit that
863 // it anti-depends on, don't bother breaking the
864 // anti-dependency since those edges would prevent such
865 // units from being scheduled past each other
868 // Also, if there are dependencies on other SUnits with the
869 // same register as the anti-dependency, don't attempt to
871 for (const SDep
&Pred
: PathSU
->Preds
) {
872 if (Pred
.getSUnit() == NextSU
? (Pred
.getKind() != SDep::Anti
||
873 Pred
.getReg() != AntiDepReg
)
874 : (Pred
.getKind() == SDep::Data
&&
875 Pred
.getReg() == AntiDepReg
)) {
880 for (const SDep
&Pred
: PathSU
->Preds
) {
881 if ((Pred
.getSUnit() == NextSU
) && (Pred
.getKind() != SDep::Anti
) &&
882 (Pred
.getKind() != SDep::Output
)) {
883 LLVM_DEBUG(dbgs() << " (real dependency)\n");
886 } else if ((Pred
.getSUnit() != NextSU
) &&
887 (Pred
.getKind() == SDep::Data
) &&
888 (Pred
.getReg() == AntiDepReg
)) {
889 LLVM_DEBUG(dbgs() << " (other dependency)\n");
895 if (AntiDepReg
== 0) continue;
897 // If the definition of the anti-dependency register does not start
898 // a new live range, bail out. This can happen if the anti-dep
899 // register is a sub-register of another register whose live range
900 // spans over PathSU. In such case, PathSU defines only a part of
901 // the larger register.
903 for (MCRegAliasIterator
AI(AntiDepReg
, TRI
, true); AI
.isValid(); ++AI
)
905 for (SDep S
: PathSU
->Succs
) {
906 SDep::Kind K
= S
.getKind();
907 if (K
!= SDep::Data
&& K
!= SDep::Output
&& K
!= SDep::Anti
)
909 unsigned R
= S
.getReg();
912 if (R
== AntiDepReg
|| TRI
->isSubRegister(AntiDepReg
, R
))
918 if (AntiDepReg
== 0) continue;
921 assert(AntiDepReg
!= 0);
923 // Determine AntiDepReg's register group.
924 const unsigned GroupIndex
= State
->GetGroup(AntiDepReg
);
925 if (GroupIndex
== 0) {
926 LLVM_DEBUG(dbgs() << " (zero group)\n");
930 LLVM_DEBUG(dbgs() << '\n');
932 // Look for a suitable register to use to break the anti-dependence.
933 std::map
<unsigned, unsigned> RenameMap
;
934 if (FindSuitableFreeRegisters(GroupIndex
, RenameOrder
, RenameMap
)) {
935 LLVM_DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
936 << printReg(AntiDepReg
, TRI
) << ":");
938 // Handle each group register...
939 for (const auto &P
: RenameMap
) {
940 unsigned CurrReg
= P
.first
;
941 unsigned NewReg
= P
.second
;
943 LLVM_DEBUG(dbgs() << " " << printReg(CurrReg
, TRI
) << "->"
944 << printReg(NewReg
, TRI
) << "("
945 << RegRefs
.count(CurrReg
) << " refs)");
947 // Update the references to the old register CurrReg to
948 // refer to the new register NewReg.
949 for (const auto &Q
: make_range(RegRefs
.equal_range(CurrReg
))) {
950 Q
.second
.Operand
->setReg(NewReg
);
951 // If the SU for the instruction being updated has debug
952 // information related to the anti-dependency register, make
953 // sure to update that as well.
954 const SUnit
*SU
= MISUnitMap
[Q
.second
.Operand
->getParent()];
956 UpdateDbgValues(DbgValues
, Q
.second
.Operand
->getParent(),
960 // We just went back in time and modified history; the
961 // liveness information for CurrReg is now inconsistent. Set
962 // the state as if it were dead.
963 State
->UnionGroups(NewReg
, 0);
964 RegRefs
.erase(NewReg
);
965 DefIndices
[NewReg
] = DefIndices
[CurrReg
];
966 KillIndices
[NewReg
] = KillIndices
[CurrReg
];
968 State
->UnionGroups(CurrReg
, 0);
969 RegRefs
.erase(CurrReg
);
970 DefIndices
[CurrReg
] = KillIndices
[CurrReg
];
971 KillIndices
[CurrReg
] = ~0u;
972 assert(((KillIndices
[CurrReg
] == ~0u) !=
973 (DefIndices
[CurrReg
] == ~0u)) &&
974 "Kill and Def maps aren't consistent for AntiDepReg!");
978 LLVM_DEBUG(dbgs() << '\n');
983 ScanInstruction(MI
, Count
);
989 AntiDepBreaker
*llvm::createAggressiveAntiDepBreaker(
990 MachineFunction
&MFi
, const RegisterClassInfo
&RCI
,
991 TargetSubtargetInfo::RegClassVector
&CriticalPathRCs
) {
992 return new AggressiveAntiDepBreaker(MFi
, RCI
, CriticalPathRCs
);