AArch64A57FPLoadBalancing.cpp 26 KB

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