1 //===------- X86InsertPrefetch.cpp - Insert cache prefetch hints ----------===// 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 // 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 18 // recommendation. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #include "X86.h" 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" 32 using namespace llvm; 33 using namespace sampleprof; 34 35 static cl::opt<std::string> 36 PrefetchHintsFile("prefetch-hints-file", 37 cl::desc("Path to the prefetch hints profile."), 38 cl::Hidden); 39 namespace { 40 41 class X86InsertPrefetch : public MachineFunctionPass { 42 void getAnalysisUsage(AnalysisUsage &AU) const override; 43 bool doInitialization(Module &) override; 44 45 bool runOnMachineFunction(MachineFunction &MF) override; 46 struct PrefetchInfo { 47 unsigned InstructionID; 48 int64_t Delta; 49 }; 50 typedef SmallVectorImpl<PrefetchInfo> Prefetches; 51 bool findPrefetchInfo(const FunctionSamples *Samples, const MachineInstr &MI, 52 Prefetches &prefetches) const; 53 54 public: 55 static char ID; 56 X86InsertPrefetch(const std::string &PrefetchHintsFilename); 57 StringRef getPassName() const override { 58 return "X86 Insert Cache Prefetches"; 59 } 60 61 private: 62 std::string Filename; 63 std::unique_ptr<SampleProfileReader> Reader; 64 }; 65 66 using PrefetchHints = SampleRecord::CallTargetMap; 67 68 // Return any prefetching hints for the specified MachineInstruction. The hints 69 // are returned as pairs (name, delta). 70 ErrorOr<PrefetchHints> getPrefetchHints(const FunctionSamples *TopSamples, 71 const MachineInstr &MI) { 72 if (const auto &Loc = MI.getDebugLoc()) 73 if (const auto *Samples = TopSamples->findFunctionSamples(Loc)) 74 return Samples->findCallTargetMapAt(FunctionSamples::getOffset(Loc), 75 Loc->getBaseDiscriminator()); 76 return std::error_code(); 77 } 78 79 } // end anonymous namespace 80 81 //===----------------------------------------------------------------------===// 82 // Implementation 83 //===----------------------------------------------------------------------===// 84 85 char X86InsertPrefetch::ID = 0; 86 87 X86InsertPrefetch::X86InsertPrefetch(const std::string &PrefetchHintsFilename) 88 : MachineFunctionPass(ID), Filename(PrefetchHintsFilename) {} 89 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 const std::pair<const StringRef, 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 106 const ErrorOr<PrefetchHints> T = getPrefetchHints(TopSamples, MI); 107 if (!T) 108 return false; 109 int16_t max_index = -1; 110 // Convert serialized prefetch hints into PrefetchInfo objects, and populate 111 // the Prefetches vector. 112 for (const auto &S_V : *T) { 113 StringRef Name = S_V.getKey(); 114 if (Name.consume_front(SerializedPrefetchPrefix)) { 115 int64_t D = static_cast<int64_t>(S_V.second); 116 unsigned IID = 0; 117 for (const auto &HintType : HintTypes) { 118 if (Name.startswith(HintType.first)) { 119 Name = Name.drop_front(HintType.first.size()); 120 IID = HintType.second; 121 break; 122 } 123 } 124 if (IID == 0) 125 return false; 126 uint8_t index = 0; 127 Name.consumeInteger(10, index); 128 129 if (index >= Prefetches.size()) 130 Prefetches.resize(index + 1); 131 Prefetches[index] = {IID, D}; 132 max_index = std::max(max_index, static_cast<int16_t>(index)); 133 } 134 } 135 assert(max_index + 1 >= 0 && 136 "Possible overflow: max_index + 1 should be positive."); 137 assert(static_cast<size_t>(max_index + 1) == Prefetches.size() && 138 "The number of prefetch hints received should match the number of " 139 "PrefetchInfo objects returned"); 140 return !Prefetches.empty(); 141 } 142 143 bool X86InsertPrefetch::doInitialization(Module &M) { 144 if (Filename.empty()) 145 return false; 146 147 LLVMContext &Ctx = M.getContext(); 148 ErrorOr<std::unique_ptr<SampleProfileReader>> ReaderOrErr = 149 SampleProfileReader::create(Filename, Ctx); 150 if (std::error_code EC = ReaderOrErr.getError()) { 151 std::string Msg = "Could not open profile: " + EC.message(); 152 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg, 153 DiagnosticSeverity::DS_Warning)); 154 return false; 155 } 156 Reader = std::move(ReaderOrErr.get()); 157 Reader->read(); 158 return true; 159 } 160 161 void X86InsertPrefetch::getAnalysisUsage(AnalysisUsage &AU) const { 162 AU.setPreservesAll(); 163 AU.addRequired<MachineModuleInfo>(); 164 } 165 166 bool X86InsertPrefetch::runOnMachineFunction(MachineFunction &MF) { 167 if (!Reader) 168 return false; 169 const FunctionSamples *Samples = Reader->getSamplesFor(MF.getFunction()); 170 if (!Samples) 171 return false; 172 173 bool Changed = false; 174 175 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 176 SmallVector<PrefetchInfo, 4> Prefetches; 177 for (auto &MBB : MF) { 178 for (auto MI = MBB.instr_begin(); MI != MBB.instr_end();) { 179 auto Current = MI; 180 ++MI; 181 182 int Offset = X86II::getMemoryOperandNo(Current->getDesc().TSFlags); 183 if (Offset < 0) 184 continue; 185 Prefetches.clear(); 186 if (!findPrefetchInfo(Samples, *Current, Prefetches)) 187 continue; 188 assert(!Prefetches.empty() && 189 "The Prefetches vector should contain at least a value if " 190 "findPrefetchInfo returned true."); 191 for (auto &PrefInfo : Prefetches) { 192 unsigned PFetchInstrID = PrefInfo.InstructionID; 193 int64_t Delta = PrefInfo.Delta; 194 const MCInstrDesc &Desc = TII->get(PFetchInstrID); 195 MachineInstr *PFetch = 196 MF.CreateMachineInstr(Desc, Current->getDebugLoc(), true); 197 MachineInstrBuilder MIB(MF, PFetch); 198 unsigned Bias = X86II::getOperandBias(Current->getDesc()); 199 int MemOpOffset = Offset + Bias; 200 201 assert(X86::AddrBaseReg == 0 && X86::AddrScaleAmt == 1 && 202 X86::AddrIndexReg == 2 && X86::AddrDisp == 3 && 203 X86::AddrSegmentReg == 4 && 204 "Unexpected change in X86 operand offset order."); 205 206 // This assumes X86::AddBaseReg = 0, {...}ScaleAmt = 1, etc. 207 // FIXME(mtrofin): consider adding a: 208 // MachineInstrBuilder::set(unsigned offset, op). 209 MIB.addReg(Current->getOperand(MemOpOffset + X86::AddrBaseReg).getReg()) 210 .addImm( 211 Current->getOperand(MemOpOffset + X86::AddrScaleAmt).getImm()) 212 .addReg( 213 Current->getOperand(MemOpOffset + X86::AddrIndexReg).getReg()) 214 .addImm(Current->getOperand(MemOpOffset + X86::AddrDisp).getImm() + 215 Delta) 216 .addReg(Current->getOperand(MemOpOffset + X86::AddrSegmentReg) 217 .getReg()); 218 219 if (!Current->memoperands_empty()) { 220 MachineMemOperand *CurrentOp = *(Current->memoperands_begin()); 221 MIB.addMemOperand(MF.getMachineMemOperand( 222 CurrentOp, CurrentOp->getOffset() + Delta, CurrentOp->getSize())); 223 } 224 225 // Insert before Current. This is because Current may clobber some of 226 // the registers used to describe the input memory operand. 227 MBB.insert(Current, PFetch); 228 Changed = true; 229 } 230 } 231 } 232 return Changed; 233 } 234 235 FunctionPass *llvm::createX86InsertPrefetchPass() { 236 return new X86InsertPrefetch(PrefetchHintsFile); 237 } 238