LLVM 24.0.0git
AArch64A57FPLoadBalancing.cpp
Go to the documentation of this file.
1//===-- AArch64A57FPLoadBalancing.cpp - Balance FP ops statically on A57---===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8// For best-case performance on Cortex-A57, we should try to use a balanced
9// mix of odd and even D-registers when performing a critical sequence of
10// independent, non-quadword FP/ASIMD floating-point multiply or
11// multiply-accumulate operations.
12//
13// This pass attempts to detect situations where the register allocation may
14// adversely affect this load balancing and to change the registers used so as
15// to better utilize the CPU.
16//
17// Ideally we'd just take each multiply or multiply-accumulate in turn and
18// allocate it alternating even or odd registers. However, multiply-accumulates
19// are most efficiently performed in the same functional unit as their
20// accumulation operand. Therefore this pass tries to find maximal sequences
21// ("Chains") of multiply-accumulates linked via their accumulation operand,
22// and assign them all the same "color" (oddness/evenness).
23//
24// This optimization affects S-register and D-register floating point
25// multiplies and FMADD/FMAs, as well as vector (floating point only) muls and
26// FMADD/FMA. Q register instructions (and 128-bit vector instructions) are
27// not affected.
28//===----------------------------------------------------------------------===//
29
30#include "AArch64.h"
31#include "AArch64InstrInfo.h"
32#include "AArch64Subtarget.h"
42#include "llvm/Support/Debug.h"
44using namespace llvm;
45
46#define DEBUG_TYPE "aarch64-a57-fp-load-balancing"
47
48//===----------------------------------------------------------------------===//
49// Helper functions
50
51// Is the instruction a type of multiply on 64-bit (or 32-bit) FPRs?
52static bool isMul(MachineInstr *MI) {
53 switch (MI->getOpcode()) {
54 case AArch64::FMULSrr:
55 case AArch64::FNMULSrr:
56 case AArch64::FMULDrr:
57 case AArch64::FNMULDrr:
58 return true;
59 default:
60 return false;
61 }
62}
63
64// Is the instruction a type of FP multiply-accumulate on 64-bit (or 32-bit) FPRs?
65static bool isMla(MachineInstr *MI) {
66 switch (MI->getOpcode()) {
67 case AArch64::FMSUBSrrr:
68 case AArch64::FMADDSrrr:
69 case AArch64::FNMSUBSrrr:
70 case AArch64::FNMADDSrrr:
71 case AArch64::FMSUBDrrr:
72 case AArch64::FMADDDrrr:
73 case AArch64::FNMSUBDrrr:
74 case AArch64::FNMADDDrrr:
75 return true;
76 default:
77 return false;
78 }
79}
80
81//===----------------------------------------------------------------------===//
82
83namespace {
84/// A "color", which is either even or odd. Yes, these aren't really colors
85/// but the algorithm is conceptually doing two-color graph coloring.
86enum class Color { Even, Odd };
87#ifndef NDEBUG
88static const char *ColorNames[2] = { "Even", "Odd" };
89#endif
90
91class Chain;
92
93class AArch64A57FPLoadBalancingImpl {
94public:
95 explicit AArch64A57FPLoadBalancingImpl(RegisterClassInfo *RCI) : RCI(RCI) {}
96
97 bool run(MachineFunction &MF);
98
99private:
100 const AArch64Options *CLOpts;
101 const TargetRegisterInfo *TRI;
102 RegisterClassInfo *RCI = nullptr;
103
104 bool runOnBasicBlock(MachineBasicBlock &MBB);
105 bool colorChainSet(std::vector<Chain *> GV, MachineBasicBlock &MBB,
106 int &Balance);
107 bool colorChain(Chain *G, Color C, MachineBasicBlock &MBB);
108 int scavengeRegister(Chain *G, Color C, MachineBasicBlock &MBB);
109 void scanInstruction(MachineInstr *MI, unsigned Idx,
110 std::map<unsigned, Chain *> &Active,
111 std::vector<std::unique_ptr<Chain>> &AllChains);
112 void maybeKillChain(MachineInstr &MI, MachineOperand &MO, unsigned Idx,
113 std::map<unsigned, Chain *> &RegChains);
114 Color getColor(unsigned Register);
115 Chain *getAndEraseNext(Color PreferredColor, std::vector<Chain *> &L);
116};
117
118class AArch64A57FPLoadBalancingLegacy : public MachineFunctionPass {
119public:
120 static char ID;
121 explicit AArch64A57FPLoadBalancingLegacy() : MachineFunctionPass(ID) {}
122
123 bool runOnMachineFunction(MachineFunction &MF) override;
124
125 MachineFunctionProperties getRequiredProperties() const override {
126 return MachineFunctionProperties().setNoVRegs();
127 }
128
129 StringRef getPassName() const override {
130 return "A57 FP Anti-dependency breaker";
131 }
132
133 void getAnalysisUsage(AnalysisUsage &AU) const override {
134 AU.setPreservesCFG();
135 AU.addRequired<MachineRegisterClassInfoWrapperPass>();
137 }
138};
139}
140
141char AArch64A57FPLoadBalancingLegacy::ID = 0;
142
143INITIALIZE_PASS_BEGIN(AArch64A57FPLoadBalancingLegacy, DEBUG_TYPE,
144 "AArch64 A57 FP Load-Balancing", false, false)
146INITIALIZE_PASS_END(AArch64A57FPLoadBalancingLegacy, DEBUG_TYPE,
147 "AArch64 A57 FP Load-Balancing", false, false)
148
149namespace {
150/// A Chain is a sequence of instructions that are linked together by
151/// an accumulation operand. For example:
152///
153/// fmul def d0, ?
154/// fmla def d1, ?, ?, killed d0
155/// fmla def d2, ?, ?, killed d1
156///
157/// There may be other instructions interleaved in the sequence that
158/// do not belong to the chain. These other instructions must not use
159/// the "chain" register at any point.
160///
161/// We currently only support chains where the "chain" operand is killed
162/// at each link in the chain for simplicity.
163/// A chain has three important instructions - Start, Last and Kill.
164/// * The start instruction is the first instruction in the chain.
165/// * Last is the final instruction in the chain.
166/// * Kill may or may not be defined. If defined, Kill is the instruction
167/// where the outgoing value of the Last instruction is killed.
168/// This information is important as if we know the outgoing value is
169/// killed with no intervening uses, we can safely change its register.
170///
171/// Without a kill instruction, we must assume the outgoing value escapes
172/// beyond our model and either must not change its register or must
173/// create a fixup FMOV to keep the old register value consistent.
174///
175class Chain {
176public:
177 /// The important (marker) instructions.
179 /// The index, from the start of the basic block, that each marker
180 /// appears. These are stored so we can do quick interval tests.
182 /// All instructions in the chain.
183 std::set<MachineInstr*> Insts;
184 /// True if KillInst cannot be modified. If this is true,
185 /// we cannot change LastInst's outgoing register.
186 /// This will be true for tied values and regmasks.
188 /// The "color" of LastInst. This will be the preferred chain color,
189 /// as changing intermediate nodes is easy but changing the last
190 /// instruction can be more tricky.
192
193 Chain(MachineInstr *MI, unsigned Idx, Color C)
194 : StartInst(MI), LastInst(MI), KillInst(nullptr),
195 StartInstIdx(Idx), LastInstIdx(Idx), KillInstIdx(0),
196 LastColor(C) {
197 Insts.insert(MI);
198 }
199
200 /// Add a new instruction into the chain. The instruction's dest operand
201 /// has the given color.
202 void add(MachineInstr *MI, unsigned Idx, Color C) {
203 LastInst = MI;
204 LastInstIdx = Idx;
205 LastColor = C;
207 "Chain: broken invariant. A Chain can only be killed after its last "
208 "def");
209
210 Insts.insert(MI);
211 }
212
213 /// Return true if MI is a member of the chain.
214 bool contains(MachineInstr &MI) { return Insts.count(&MI) > 0; }
215
216 /// Return the number of instructions in the chain.
217 unsigned size() const {
218 return Insts.size();
219 }
220
221 /// Inform the chain that its last active register (the dest register of
222 /// LastInst) is killed by MI with no intervening uses or defs.
223 void setKill(MachineInstr *MI, unsigned Idx, bool Immutable) {
224 KillInst = MI;
225 KillInstIdx = Idx;
226 KillIsImmutable = Immutable;
228 "Chain: broken invariant. A Chain can only be killed after its last "
229 "def");
230 }
231
232 /// Return the first instruction in the chain.
233 MachineInstr *getStart() const { return StartInst; }
234 /// Return the last instruction in the chain.
235 MachineInstr *getLast() const { return LastInst; }
236 /// Return the "kill" instruction (as set with setKill()) or NULL.
237 MachineInstr *getKill() const { return KillInst; }
238 /// Return an instruction that can be used as an iterator for the end
239 /// of the chain. This is the maximum of KillInst (if set) and LastInst.
244
245 /// Can the Kill instruction (assuming one exists) be modified?
246 bool isKillImmutable() const { return KillIsImmutable; }
247
248 /// Return the preferred color of this chain.
249 Color getPreferredColor(unsigned Override) {
250 if (Override)
251 return Override == 1 ? Color::Even : Color::Odd;
252 return LastColor;
253 }
254
255 /// Return true if this chain (StartInst..KillInst) overlaps with Other.
256 bool rangeOverlapsWith(const Chain &Other) const {
257 unsigned End = KillInst ? KillInstIdx : LastInstIdx;
258 unsigned OtherEnd = Other.KillInst ?
259 Other.KillInstIdx : Other.LastInstIdx;
260
261 return StartInstIdx <= OtherEnd && Other.StartInstIdx <= End;
262 }
263
264 /// Return true if this chain starts before Other.
265 bool startsBefore(const Chain *Other) const {
266 return StartInstIdx < Other->StartInstIdx;
267 }
268
269 /// Return true if the group will require a fixup MOV at the end.
270 bool requiresFixup() const {
271 return (getKill() && isKillImmutable()) || !getKill();
272 }
273
274 /// Return a simple string representation of the chain.
275 std::string str() const {
276 std::string S;
277 raw_string_ostream OS(S);
278
279 OS << "{";
280 StartInst->print(OS, /* SkipOpers= */true);
281 OS << " -> ";
282 LastInst->print(OS, /* SkipOpers= */true);
283 if (KillInst) {
284 OS << " (kill @ ";
285 KillInst->print(OS, /* SkipOpers= */true);
286 OS << ")";
287 }
288 OS << "}";
289
290 return OS.str();
291 }
292
293};
294
295} // end anonymous namespace
296
297//===----------------------------------------------------------------------===//
298
299bool AArch64A57FPLoadBalancingImpl::run(MachineFunction &MF) {
300 const AArch64Subtarget &ST = MF.getSubtarget<AArch64Subtarget>();
301 if (!ST.balanceFPOps())
302 return false;
303 CLOpts = &ST.getCLOpts();
304
305 bool Changed = false;
306 LLVM_DEBUG(dbgs() << "***** AArch64A57FPLoadBalancing *****\n");
307
309
310 for (auto &MBB : MF) {
312 }
313
314 return Changed;
315}
316
317bool AArch64A57FPLoadBalancingLegacy::runOnMachineFunction(
318 MachineFunction &MF) {
319 if (skipFunction(MF.getFunction()))
320 return false;
321 RegisterClassInfo *RCI =
322 &getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
323 return AArch64A57FPLoadBalancingImpl(RCI).run(MF);
324}
325
326PreservedAnalyses
330 if (AArch64A57FPLoadBalancingImpl(RCI).run(MF)) {
333 return PA;
334 }
335 return PreservedAnalyses::all();
336}
337
338bool AArch64A57FPLoadBalancingImpl::runOnBasicBlock(MachineBasicBlock &MBB) {
339 bool Changed = false;
340 LLVM_DEBUG(dbgs() << "Running on MBB: " << MBB
341 << " - scanning instructions...\n");
342
343 // First, scan the basic block producing a set of chains.
344
345 // The currently "active" chains - chains that can be added to and haven't
346 // been killed yet. This is keyed by register - all chains can only have one
347 // "link" register between each inst in the chain.
348 std::map<unsigned, Chain*> ActiveChains;
349 std::vector<std::unique_ptr<Chain>> AllChains;
350 unsigned Idx = 0;
351 for (auto &MI : MBB)
352 scanInstruction(&MI, Idx++, ActiveChains, AllChains);
353
354 LLVM_DEBUG(dbgs() << "Scan complete, " << AllChains.size()
355 << " chains created.\n");
356
357 // Group the chains into disjoint sets based on their liveness range. This is
358 // a poor-man's version of graph coloring. Ideally we'd create an interference
359 // graph and perform full-on graph coloring on that, but;
360 // (a) That's rather heavyweight for only two colors.
361 // (b) We expect multiple disjoint interference regions - in practice the live
362 // range of chains is quite small and they are clustered between loads
363 // and stores.
365 for (auto &I : AllChains)
366 EC.insert(I.get());
367
368 for (auto &I : AllChains)
369 for (auto &J : AllChains)
370 if (I != J && I->rangeOverlapsWith(*J))
371 EC.unionSets(I.get(), J.get());
372 LLVM_DEBUG(dbgs() << "Created " << EC.getNumClasses() << " disjoint sets.\n");
373
374 // Now we assume that every member of an equivalence class interferes
375 // with every other member of that class, and with no members of other classes.
376
377 // Convert the EquivalenceClasses to a simpler set of sets.
378 std::vector<std::vector<Chain*> > V;
379 for (const auto &E : EC) {
380 if (!E->isLeader())
381 continue;
382 std::vector<Chain *> Cs(EC.member_begin(*E), EC.member_end());
383 if (Cs.empty()) continue;
384 V.push_back(std::move(Cs));
385 }
386
387 // Now we have a set of sets, order them by start address so
388 // we can iterate over them sequentially.
390 [](const std::vector<Chain *> &A, const std::vector<Chain *> &B) {
391 return A.front()->startsBefore(B.front());
392 });
393
394 // As we only have two colors, we can track the global (BB-level) balance of
395 // odds versus evens. We aim to keep this near zero to keep both execution
396 // units fed.
397 // Positive means we're even-heavy, negative we're odd-heavy.
398 //
399 // FIXME: If chains have interdependencies, for example:
400 // mul r0, r1, r2
401 // mul r3, r0, r1
402 // We do not model this and may color each one differently, assuming we'll
403 // get ILP when we obviously can't. This hasn't been seen to be a problem
404 // in practice so far, so we simplify the algorithm by ignoring it.
405 int Parity = 0;
406
407 for (auto &I : V)
408 Changed |= colorChainSet(std::move(I), MBB, Parity);
409
410 return Changed;
411}
412
413Chain *AArch64A57FPLoadBalancingImpl::getAndEraseNext(Color PreferredColor,
414 std::vector<Chain *> &L) {
415 if (L.empty())
416 return nullptr;
417
418 // We try and get the best candidate from L to color next, given that our
419 // preferred color is "PreferredColor". L is ordered from larger to smaller
420 // chains. It is beneficial to color the large chains before the small chains,
421 // but if we can't find a chain of the maximum length with the preferred color,
422 // we fuzz the size and look for slightly smaller chains before giving up and
423 // returning a chain that must be recolored.
424
425 // FIXME: Does this need to be configurable?
426 const unsigned SizeFuzz = 1;
427 unsigned MinSize = L.front()->size() - SizeFuzz;
428 for (auto I = L.begin(), E = L.end(); I != E; ++I) {
429 if ((*I)->size() <= MinSize) {
430 // We've gone past the size limit. Return the previous item.
431 Chain *Ch = *--I;
432 L.erase(I);
433 return Ch;
434 }
435
436 if ((*I)->getPreferredColor(CLOpts->a57_fp_load_balancing_override) ==
437 PreferredColor) {
438 Chain *Ch = *I;
439 L.erase(I);
440 return Ch;
441 }
442 }
443
444 // Bailout case - just return the first item.
445 Chain *Ch = L.front();
446 L.erase(L.begin());
447 return Ch;
448}
449
450bool AArch64A57FPLoadBalancingImpl::colorChainSet(std::vector<Chain *> GV,
451 MachineBasicBlock &MBB,
452 int &Parity) {
453 bool Changed = false;
454 LLVM_DEBUG(dbgs() << "colorChainSet(): #sets=" << GV.size() << "\n");
455
456 // Sort by descending size order so that we allocate the most important
457 // sets first.
458 // Tie-break equivalent sizes by sorting chains requiring fixups before
459 // those without fixups. The logic here is that we should look at the
460 // chains that we cannot change before we look at those we can,
461 // so the parity counter is updated and we know what color we should
462 // change them to!
463 // Final tie-break with instruction order so pass output is stable (i.e. not
464 // dependent on malloc'd pointer values).
465 llvm::sort(GV, [](const Chain *G1, const Chain *G2) {
466 if (G1->size() != G2->size())
467 return G1->size() > G2->size();
468 if (G1->requiresFixup() != G2->requiresFixup())
469 return G1->requiresFixup() > G2->requiresFixup();
470 // Make sure startsBefore() produces a stable final order.
471 assert((G1 == G2 || (G1->startsBefore(G2) ^ G2->startsBefore(G1))) &&
472 "Starts before not total order!");
473 return G1->startsBefore(G2);
474 });
475
476 unsigned Override = CLOpts->a57_fp_load_balancing_override;
477 Color PreferredColor = Parity < 0 ? Color::Even : Color::Odd;
478 while (Chain *G = getAndEraseNext(PreferredColor, GV)) {
479 // Start off by assuming we'll color to our own preferred color.
480 Color C = PreferredColor;
481 if (Parity == 0)
482 // But if we really don't care, use the chain's preferred color.
483 C = G->getPreferredColor(Override);
484
485 LLVM_DEBUG(dbgs() << " - Parity=" << Parity
486 << ", Color=" << ColorNames[(int)C] << "\n");
487
488 // If we'll need a fixup FMOV, don't bother. Testing has shown that this
489 // happens infrequently and when it does it has at least a 50% chance of
490 // slowing code down instead of speeding it up.
491 if (G->requiresFixup() && C != G->getPreferredColor(Override)) {
492 C = G->getPreferredColor(Override);
493 LLVM_DEBUG(dbgs() << " - " << G->str()
494 << " - not worthwhile changing; "
495 "color remains "
496 << ColorNames[(int)C] << "\n");
497 }
498
499 Changed |= colorChain(G, C, MBB);
500
501 Parity += (C == Color::Even) ? G->size() : -G->size();
502 PreferredColor = Parity < 0 ? Color::Even : Color::Odd;
503 }
504
505 return Changed;
506}
507
508int AArch64A57FPLoadBalancingImpl::scavengeRegister(Chain *G, Color C,
509 MachineBasicBlock &MBB) {
510 // Can we find an appropriate register that is available throughout the life
511 // of the chain? Simulate liveness backwards until the end of the chain.
512 LiveRegUnits Units(*TRI);
513 Units.addLiveOuts(MBB);
515 MachineBasicBlock::iterator ChainEnd = G->end();
516 while (I != ChainEnd) {
517 --I;
518 if (!I->isDebugInstr())
519 Units.stepBackward(*I);
520 }
521
522 // Check which register units are alive throughout the chain.
523 MachineBasicBlock::iterator ChainBegin = G->begin();
524 assert(ChainBegin != ChainEnd && "Chain should contain instructions");
525 do {
526 --I;
527 Units.accumulate(*I);
528 } while (I != ChainBegin);
529
530 // Make sure we allocate in-order, to get the cheapest registers first.
531 unsigned RegClassID = ChainBegin->getDesc().operands()[0].RegClass;
532 auto Ord = RCI->getOrder(TRI->getRegClass(RegClassID));
533 for (auto Reg : Ord) {
534 if (!Units.available(Reg))
535 continue;
536 if (C == getColor(Reg))
537 return Reg;
538 }
539
540 return -1;
541}
542
543bool AArch64A57FPLoadBalancingImpl::colorChain(Chain *G, Color C,
544 MachineBasicBlock &MBB) {
545 bool Changed = false;
546 LLVM_DEBUG(dbgs() << " - colorChain(" << G->str() << ", "
547 << ColorNames[(int)C] << ")\n");
548
549 // Try and obtain a free register of the right class. Without a register
550 // to play with we cannot continue.
551 int Reg = scavengeRegister(G, C, MBB);
552 if (Reg == -1) {
553 LLVM_DEBUG(dbgs() << "Scavenging (thus coloring) failed!\n");
554 return false;
555 }
556 LLVM_DEBUG(dbgs() << " - Scavenged register: " << printReg(Reg, TRI) << "\n");
557
558 std::map<unsigned, unsigned> Substs;
559 for (MachineInstr &I : *G) {
560 if (!G->contains(I) && (&I != G->getKill() || G->isKillImmutable()))
561 continue;
562
563 // I is a member of G, or I is a mutable instruction that kills G.
564
565 std::vector<unsigned> ToErase;
566 for (auto &U : I.operands()) {
567 if (U.isReg() && U.isUse() && Substs.find(U.getReg()) != Substs.end()) {
568 Register OrigReg = U.getReg();
569 U.setReg(Substs[OrigReg]);
570 if (U.isKill())
571 // Don't erase straight away, because there may be other operands
572 // that also reference this substitution!
573 ToErase.push_back(OrigReg);
574 } else if (U.isRegMask()) {
575 for (auto J : Substs) {
576 if (U.clobbersPhysReg(J.first))
577 ToErase.push_back(J.first);
578 }
579 }
580 }
581 // Now it's safe to remove the substs identified earlier.
582 for (auto J : ToErase)
583 Substs.erase(J);
584
585 // Only change the def if this isn't the last instruction.
586 if (&I != G->getKill()) {
587 MachineOperand &MO = I.getOperand(0);
588
589 bool Change =
590 CLOpts->a57_fp_load_balancing_force_all || getColor(MO.getReg()) != C;
591 if (G->requiresFixup() && &I == G->getLast())
592 Change = false;
593
594 if (Change) {
595 Substs[MO.getReg()] = Reg;
596 MO.setReg(Reg);
597
598 Changed = true;
599 }
600 }
601 }
602 assert(Substs.size() == 0 && "No substitutions should be left active!");
603
604 if (G->getKill()) {
605 LLVM_DEBUG(dbgs() << " - Kill instruction seen.\n");
606 } else {
607 // We didn't have a kill instruction, but we didn't seem to need to change
608 // the destination register anyway.
609 LLVM_DEBUG(dbgs() << " - Destination register not changed.\n");
610 }
611 return Changed;
612}
613
614void AArch64A57FPLoadBalancingImpl::scanInstruction(
615 MachineInstr *MI, unsigned Idx, std::map<unsigned, Chain *> &ActiveChains,
616 std::vector<std::unique_ptr<Chain>> &AllChains) {
617 // Inspect "MI", updating ActiveChains and AllChains.
618
619 if (isMul(MI)) {
620
621 for (auto &I : MI->uses())
622 maybeKillChain(*MI, I, Idx, ActiveChains);
623 for (auto &I : MI->defs())
624 maybeKillChain(*MI, I, Idx, ActiveChains);
625
626 // Create a new chain. Multiplies don't require forwarding so can go on any
627 // unit.
628 Register DestReg = MI->getOperand(0).getReg();
629
630 LLVM_DEBUG(dbgs() << "New chain started for register "
631 << printReg(DestReg, TRI) << " at " << *MI);
632
633 auto G = std::make_unique<Chain>(MI, Idx, getColor(DestReg));
634 ActiveChains[DestReg] = G.get();
635 AllChains.push_back(std::move(G));
636
637 } else if (isMla(MI)) {
638
639 // It is beneficial to keep MLAs on the same functional unit as their
640 // accumulator operand.
641 Register DestReg = MI->getOperand(0).getReg();
642 Register AccumReg = MI->getOperand(3).getReg();
643
644 maybeKillChain(*MI, MI->getOperand(1), Idx, ActiveChains);
645 maybeKillChain(*MI, MI->getOperand(2), Idx, ActiveChains);
646 if (DestReg != AccumReg)
647 maybeKillChain(*MI, MI->getOperand(0), Idx, ActiveChains);
648
649 if (ActiveChains.find(AccumReg) != ActiveChains.end()) {
650 LLVM_DEBUG(dbgs() << "Chain found for accumulator register "
651 << printReg(AccumReg, TRI) << " in MI " << *MI);
652
653 // For simplicity we only chain together sequences of MULs/MLAs where the
654 // accumulator register is killed on each instruction. This means we don't
655 // need to track other uses of the registers we want to rewrite.
656 //
657 // FIXME: We could extend to handle the non-kill cases for more coverage.
658 if (MI->getOperand(3).isKill()) {
659 // Add to chain.
660 LLVM_DEBUG(dbgs() << "Instruction was successfully added to chain.\n");
661 ActiveChains[AccumReg]->add(MI, Idx, getColor(DestReg));
662 // Handle cases where the destination is not the same as the accumulator.
663 if (DestReg != AccumReg) {
664 ActiveChains[DestReg] = ActiveChains[AccumReg];
665 ActiveChains.erase(AccumReg);
666 }
667 return;
668 }
669
671 dbgs() << "Cannot add to chain because accumulator operand wasn't "
672 << "marked <kill>!\n");
673 maybeKillChain(*MI, MI->getOperand(3), Idx, ActiveChains);
674 }
675
676 LLVM_DEBUG(dbgs() << "Creating new chain for dest register "
677 << printReg(DestReg, TRI) << "\n");
678 auto G = std::make_unique<Chain>(MI, Idx, getColor(DestReg));
679 ActiveChains[DestReg] = G.get();
680 AllChains.push_back(std::move(G));
681
682 } else {
683
684 // Non-MUL or MLA instruction. Invalidate any chain in the uses or defs
685 // lists.
686 for (auto &I : MI->uses())
687 maybeKillChain(*MI, I, Idx, ActiveChains);
688 for (auto &I : MI->defs())
689 maybeKillChain(*MI, I, Idx, ActiveChains);
690 }
691}
692
693void AArch64A57FPLoadBalancingImpl::maybeKillChain(
694 MachineInstr &MI, MachineOperand &MO, unsigned Idx,
695 std::map<unsigned, Chain *> &ActiveChains) {
696 // Given an operand and the set of active chains (keyed by register),
697 // determine if a chain should be ended and remove from ActiveChains.
698 if (MO.isReg()) {
699
700 // If this is a KILL of a current chain, record it.
701 if (MO.isKill() && ActiveChains.find(MO.getReg()) != ActiveChains.end()) {
702 LLVM_DEBUG(dbgs() << "Kill seen for chain " << printReg(MO.getReg(), TRI)
703 << "\n");
704 ActiveChains[MO.getReg()]->setKill(&MI, Idx, /*Immutable=*/MO.isTied());
705 }
706 ActiveChains.erase(MO.getReg());
707
708 } else if (MO.isRegMask()) {
709
710 for (auto I = ActiveChains.begin(), E = ActiveChains.end();
711 I != E;) {
712 if (MO.clobbersPhysReg(I->first)) {
713 LLVM_DEBUG(dbgs() << "Kill (regmask) seen for chain "
714 << printReg(I->first, TRI) << "\n");
715 I->second->setKill(&MI, Idx, /*Immutable=*/true);
716 ActiveChains.erase(I++);
717 } else
718 ++I;
719 }
720
721 }
722}
723
724Color AArch64A57FPLoadBalancingImpl::getColor(unsigned Reg) {
725 if ((TRI->getEncodingValue(Reg) % 2) == 0)
726 return Color::Even;
727 else
728 return Color::Odd;
729}
730
731// Factory function used by AArch64TargetMachine to add the pass to the passmanager.
733 return new AArch64A57FPLoadBalancingLegacy();
734}
static bool isMul(MachineInstr *MI)
static bool isMla(MachineInstr *MI)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static bool runOnBasicBlock(MachineBasicBlock *MBB, unsigned BasicBlockNum, VRegRenamer &Renamer)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file declares the machine register scavenger class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
MachineInstr * StartInst
The important (marker) instructions.
MachineBasicBlock::iterator begin() const
bool isKillImmutable() const
Can the Kill instruction (assuming one exists) be modified?
void add(MachineInstr *MI, unsigned Idx, Color C)
Add a new instruction into the chain.
bool contains(MachineInstr &MI)
Return true if MI is a member of the chain.
Color LastColor
The "color" of LastInst.
bool requiresFixup() const
Return true if the group will require a fixup MOV at the end.
MachineInstr * getLast() const
Return the last instruction in the chain.
bool KillIsImmutable
True if KillInst cannot be modified.
bool rangeOverlapsWith(const Chain &Other) const
Return true if this chain (StartInst..KillInst) overlaps with Other.
MachineInstr * getStart() const
Return the first instruction in the chain.
unsigned size() const
Return the number of instructions in the chain.
MachineBasicBlock::iterator end() const
Return an instruction that can be used as an iterator for the end of the chain.
void setKill(MachineInstr *MI, unsigned Idx, bool Immutable)
Inform the chain that its last active register (the dest register of LastInst) is killed by MI with n...
MachineInstr * getKill() const
Return the "kill" instruction (as set with setKill()) or NULL.
unsigned StartInstIdx
The index, from the start of the basic block, that each marker appears.
std::string str() const
Return a simple string representation of the chain.
Color getPreferredColor(unsigned Override)
Return the preferred color of this chain.
std::set< MachineInstr * > Insts
All instructions in the chain.
Chain(MachineInstr *MI, unsigned Idx, Color C)
bool startsBefore(const Chain *Other) const
Return true if this chain starts before Other.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
This represents a collection of equivalence classes and supports three efficient operations: insert a...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const TargetRegisterInfo * getTargetRegisterInfo() const
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:152
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
FunctionPass * createAArch64A57FPLoadBalancingLegacyPass()
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
@ Other
Any other memory.
Definition ModRef.h:68
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.