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