X86InsertPrefetch.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. //===------- X86InsertPrefetch.cpp - Insert cache prefetch hints ----------===//
  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. //
  9. // This pass applies cache prefetch instructions based on a profile. The pass
  10. // assumes DiscriminateMemOps ran immediately before, to ensure debug info
  11. // matches the one used at profile generation time. The profile is encoded in
  12. // afdo format (text or binary). It contains prefetch hints recommendations.
  13. // Each recommendation is made in terms of debug info locations, a type (i.e.
  14. // nta, t{0|1|2}) and a delta. The debug info identifies an instruction with a
  15. // memory operand (see X86DiscriminateMemOps). The prefetch will be made for
  16. // a location at that memory operand + the delta specified in the
  17. // recommendation.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #include "X86.h"
  21. #include "X86InstrBuilder.h"
  22. #include "X86InstrInfo.h"
  23. #include "X86MachineFunctionInfo.h"
  24. #include "X86Subtarget.h"
  25. #include "llvm/CodeGen/MachineFunctionPass.h"
  26. #include "llvm/CodeGen/MachineModuleInfo.h"
  27. #include "llvm/IR/DebugInfoMetadata.h"
  28. #include "llvm/ProfileData/SampleProf.h"
  29. #include "llvm/ProfileData/SampleProfReader.h"
  30. #include "llvm/Transforms/IPO/SampleProfile.h"
  31. using namespace llvm;
  32. using namespace sampleprof;
  33. static cl::opt<std::string>
  34. PrefetchHintsFile("prefetch-hints-file",
  35. cl::desc("Path to the prefetch hints profile. See also "
  36. "-x86-discriminate-memops"),
  37. cl::Hidden);
  38. namespace {
  39. class X86InsertPrefetch : public MachineFunctionPass {
  40. void getAnalysisUsage(AnalysisUsage &AU) const override;
  41. bool doInitialization(Module &) override;
  42. bool runOnMachineFunction(MachineFunction &MF) override;
  43. struct PrefetchInfo {
  44. unsigned InstructionID;
  45. int64_t Delta;
  46. };
  47. typedef SmallVectorImpl<PrefetchInfo> Prefetches;
  48. bool findPrefetchInfo(const FunctionSamples *Samples, const MachineInstr &MI,
  49. Prefetches &prefetches) const;
  50. public:
  51. static char ID;
  52. X86InsertPrefetch(const std::string &PrefetchHintsFilename);
  53. StringRef getPassName() const override {
  54. return "X86 Insert Cache Prefetches";
  55. }
  56. private:
  57. std::string Filename;
  58. std::unique_ptr<SampleProfileReader> Reader;
  59. };
  60. using PrefetchHints = SampleRecord::CallTargetMap;
  61. // Return any prefetching hints for the specified MachineInstruction. The hints
  62. // are returned as pairs (name, delta).
  63. ErrorOr<PrefetchHints> getPrefetchHints(const FunctionSamples *TopSamples,
  64. const MachineInstr &MI) {
  65. if (const auto &Loc = MI.getDebugLoc())
  66. if (const auto *Samples = TopSamples->findFunctionSamples(Loc))
  67. return Samples->findCallTargetMapAt(FunctionSamples::getOffset(Loc),
  68. Loc->getBaseDiscriminator());
  69. return std::error_code();
  70. }
  71. // The prefetch instruction can't take memory operands involving vector
  72. // registers.
  73. bool IsMemOpCompatibleWithPrefetch(const MachineInstr &MI, int Op) {
  74. Register BaseReg = MI.getOperand(Op + X86::AddrBaseReg).getReg();
  75. Register IndexReg = MI.getOperand(Op + X86::AddrIndexReg).getReg();
  76. return (BaseReg == 0 ||
  77. X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) ||
  78. X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg)) &&
  79. (IndexReg == 0 ||
  80. X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg) ||
  81. X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg));
  82. }
  83. } // end anonymous namespace
  84. //===----------------------------------------------------------------------===//
  85. // Implementation
  86. //===----------------------------------------------------------------------===//
  87. char X86InsertPrefetch::ID = 0;
  88. X86InsertPrefetch::X86InsertPrefetch(const std::string &PrefetchHintsFilename)
  89. : MachineFunctionPass(ID), Filename(PrefetchHintsFilename) {}
  90. /// Return true if the provided MachineInstruction has cache prefetch hints. In
  91. /// that case, the prefetch hints are stored, in order, in the Prefetches
  92. /// vector.
  93. bool X86InsertPrefetch::findPrefetchInfo(const FunctionSamples *TopSamples,
  94. const MachineInstr &MI,
  95. Prefetches &Prefetches) const {
  96. assert(Prefetches.empty() &&
  97. "Expected caller passed empty PrefetchInfo vector.");
  98. static constexpr std::pair<StringLiteral, unsigned> HintTypes[] = {
  99. {"_nta_", X86::PREFETCHNTA},
  100. {"_t0_", X86::PREFETCHT0},
  101. {"_t1_", X86::PREFETCHT1},
  102. {"_t2_", X86::PREFETCHT2},
  103. };
  104. static const char *SerializedPrefetchPrefix = "__prefetch";
  105. const ErrorOr<PrefetchHints> T = getPrefetchHints(TopSamples, MI);
  106. if (!T)
  107. return false;
  108. int16_t max_index = -1;
  109. // Convert serialized prefetch hints into PrefetchInfo objects, and populate
  110. // the Prefetches vector.
  111. for (const auto &S_V : *T) {
  112. StringRef Name = S_V.getKey();
  113. if (Name.consume_front(SerializedPrefetchPrefix)) {
  114. int64_t D = static_cast<int64_t>(S_V.second);
  115. unsigned IID = 0;
  116. for (const auto &HintType : HintTypes) {
  117. if (Name.startswith(HintType.first)) {
  118. Name = Name.drop_front(HintType.first.size());
  119. IID = HintType.second;
  120. break;
  121. }
  122. }
  123. if (IID == 0)
  124. return false;
  125. uint8_t index = 0;
  126. Name.consumeInteger(10, index);
  127. if (index >= Prefetches.size())
  128. Prefetches.resize(index + 1);
  129. Prefetches[index] = {IID, D};
  130. max_index = std::max(max_index, static_cast<int16_t>(index));
  131. }
  132. }
  133. assert(max_index + 1 >= 0 &&
  134. "Possible overflow: max_index + 1 should be positive.");
  135. assert(static_cast<size_t>(max_index + 1) == Prefetches.size() &&
  136. "The number of prefetch hints received should match the number of "
  137. "PrefetchInfo objects returned");
  138. return !Prefetches.empty();
  139. }
  140. bool X86InsertPrefetch::doInitialization(Module &M) {
  141. if (Filename.empty())
  142. return false;
  143. LLVMContext &Ctx = M.getContext();
  144. ErrorOr<std::unique_ptr<SampleProfileReader>> ReaderOrErr =
  145. SampleProfileReader::create(Filename, Ctx);
  146. if (std::error_code EC = ReaderOrErr.getError()) {
  147. std::string Msg = "Could not open profile: " + EC.message();
  148. Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg,
  149. DiagnosticSeverity::DS_Warning));
  150. return false;
  151. }
  152. Reader = std::move(ReaderOrErr.get());
  153. Reader->read();
  154. return true;
  155. }
  156. void X86InsertPrefetch::getAnalysisUsage(AnalysisUsage &AU) const {
  157. AU.setPreservesAll();
  158. MachineFunctionPass::getAnalysisUsage(AU);
  159. }
  160. bool X86InsertPrefetch::runOnMachineFunction(MachineFunction &MF) {
  161. if (!Reader)
  162. return false;
  163. const FunctionSamples *Samples = Reader->getSamplesFor(MF.getFunction());
  164. if (!Samples)
  165. return false;
  166. bool Changed = false;
  167. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  168. SmallVector<PrefetchInfo, 4> Prefetches;
  169. for (auto &MBB : MF) {
  170. for (auto MI = MBB.instr_begin(); MI != MBB.instr_end();) {
  171. auto Current = MI;
  172. ++MI;
  173. int Offset = X86II::getMemoryOperandNo(Current->getDesc().TSFlags);
  174. if (Offset < 0)
  175. continue;
  176. unsigned Bias = X86II::getOperandBias(Current->getDesc());
  177. int MemOpOffset = Offset + Bias;
  178. // FIXME(mtrofin): ORE message when the recommendation cannot be taken.
  179. if (!IsMemOpCompatibleWithPrefetch(*Current, MemOpOffset))
  180. continue;
  181. Prefetches.clear();
  182. if (!findPrefetchInfo(Samples, *Current, Prefetches))
  183. continue;
  184. assert(!Prefetches.empty() &&
  185. "The Prefetches vector should contain at least a value if "
  186. "findPrefetchInfo returned true.");
  187. for (auto &PrefInfo : Prefetches) {
  188. unsigned PFetchInstrID = PrefInfo.InstructionID;
  189. int64_t Delta = PrefInfo.Delta;
  190. const MCInstrDesc &Desc = TII->get(PFetchInstrID);
  191. MachineInstr *PFetch =
  192. MF.CreateMachineInstr(Desc, Current->getDebugLoc(), true);
  193. MachineInstrBuilder MIB(MF, PFetch);
  194. static_assert(X86::AddrBaseReg == 0 && X86::AddrScaleAmt == 1 &&
  195. X86::AddrIndexReg == 2 && X86::AddrDisp == 3 &&
  196. X86::AddrSegmentReg == 4,
  197. "Unexpected change in X86 operand offset order.");
  198. // This assumes X86::AddBaseReg = 0, {...}ScaleAmt = 1, etc.
  199. // FIXME(mtrofin): consider adding a:
  200. // MachineInstrBuilder::set(unsigned offset, op).
  201. MIB.addReg(Current->getOperand(MemOpOffset + X86::AddrBaseReg).getReg())
  202. .addImm(
  203. Current->getOperand(MemOpOffset + X86::AddrScaleAmt).getImm())
  204. .addReg(
  205. Current->getOperand(MemOpOffset + X86::AddrIndexReg).getReg())
  206. .addImm(Current->getOperand(MemOpOffset + X86::AddrDisp).getImm() +
  207. Delta)
  208. .addReg(Current->getOperand(MemOpOffset + X86::AddrSegmentReg)
  209. .getReg());
  210. if (!Current->memoperands_empty()) {
  211. MachineMemOperand *CurrentOp = *(Current->memoperands_begin());
  212. MIB.addMemOperand(MF.getMachineMemOperand(
  213. CurrentOp, CurrentOp->getOffset() + Delta, CurrentOp->getSize()));
  214. }
  215. // Insert before Current. This is because Current may clobber some of
  216. // the registers used to describe the input memory operand.
  217. MBB.insert(Current, PFetch);
  218. Changed = true;
  219. }
  220. }
  221. }
  222. return Changed;
  223. }
  224. FunctionPass *llvm::createX86InsertPrefetchPass() {
  225. return new X86InsertPrefetch(PrefetchHintsFile);
  226. }