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