[llvm] 2f422a5 - [Codegen, X86] Add prefetch insertion based on Propeller profile (#166324)
via llvm-commits
llvm-commits at lists.llvm.org
Fri Apr 10 15:58:20 PDT 2026
Author: Rahman Lavaee
Date: 2026-04-10T15:58:16-07:00
New Revision: 2f422a52fde267757ce48041af6e731421fed2a3
URL: https://github.com/llvm/llvm-project/commit/2f422a52fde267757ce48041af6e731421fed2a3
DIFF: https://github.com/llvm/llvm-project/commit/2f422a52fde267757ce48041af6e731421fed2a3.diff
LOG: [Codegen, X86] Add prefetch insertion based on Propeller profile (#166324)
This PR implements the prefetch insertion in the InsertCodePrefetch pass
based on the
[RFC](https://discourse.llvm.org/t/rfc-code-prefetch-insertion/88668).
If the prefetch target is not defined in the same module (i.e, prefetch
target function is not defined in the same module), we emit a fallback
weak symbol after the prefetch instruction so that if the symbol is not
ever defined, we don't get undefined symbol error and the prefetch
instruction prefetches the next address:
```
prefetchit1 __llvm_prefetch_target_foo(%rip)
.weak __llvm_prefetch_target_foo
__llvm_prefetch_target_foo:
```
The weak symbol semantic is tied to ELF, so this makes this PR
target-dependent.
Added:
llvm/include/llvm/CodeGen/InsertCodePrefetch.h
Modified:
llvm/include/llvm/CodeGen/AsmPrinter.h
llvm/include/llvm/CodeGen/BasicBlockSectionsProfileReader.h
llvm/include/llvm/CodeGen/MachineBasicBlock.h
llvm/include/llvm/CodeGen/Passes.h
llvm/include/llvm/CodeGen/TargetInstrInfo.h
llvm/include/llvm/Support/UniqueBBID.h
llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
llvm/lib/CodeGen/BasicBlockSections.cpp
llvm/lib/CodeGen/BasicBlockSectionsProfileReader.cpp
llvm/lib/CodeGen/InsertCodePrefetch.cpp
llvm/lib/Target/X86/X86InstrInfo.cpp
llvm/lib/Target/X86/X86InstrInfo.h
llvm/test/CodeGen/X86/basic-block-sections-code-prefetch-call-terminates-block.ll
llvm/test/CodeGen/X86/basic-block-sections-code-prefetch.ll
Removed:
################################################################################
diff --git a/llvm/include/llvm/CodeGen/AsmPrinter.h b/llvm/include/llvm/CodeGen/AsmPrinter.h
index 260de40ac3e42..7b480e45cab88 100644
--- a/llvm/include/llvm/CodeGen/AsmPrinter.h
+++ b/llvm/include/llvm/CodeGen/AsmPrinter.h
@@ -489,7 +489,7 @@ class LLVM_ABI AsmPrinter : public MachineFunctionPass {
/// Helper to emit a symbol for the prefetch target associated with the given
/// BBID and callsite index. The symbol is emitted as a label and its linkage
/// is set based on the function's linkage.
- void emitPrefetchTargetSymbol(unsigned BaseID, unsigned CallsiteIndex);
+ void emitPrefetchTargetSymbol(const UniqueBBID &BBID, unsigned CallsiteIndex);
/// Emit prefetch targets that were not mapped to any basic block. These
/// targets are emitted at the beginning of the function body.
diff --git a/llvm/include/llvm/CodeGen/BasicBlockSectionsProfileReader.h b/llvm/include/llvm/CodeGen/BasicBlockSectionsProfileReader.h
index 830f99cd661bc..c4b2fd59793bd 100644
--- a/llvm/include/llvm/CodeGen/BasicBlockSectionsProfileReader.h
+++ b/llvm/include/llvm/CodeGen/BasicBlockSectionsProfileReader.h
@@ -75,6 +75,7 @@ struct CFGProfile {
// including CFG data (block and edge counts) and layout directives (clustering
// and cloning paths).
struct FunctionOptimizationProfile {
+ // This represents the raw input profile for one function.
// BB Cluster information specified by `UniqueBBID`s.
SmallVector<BBClusterInfo> ClusterInfo;
// Paths to clone. A path a -> b -> c -> d implies cloning b, c, and d along
@@ -86,6 +87,9 @@ struct FunctionOptimizationProfile {
// Code prefetch targets, specified by the callsite ID. The target is the code
// immediately following this callsite.
SmallVector<CallsiteID> PrefetchTargets;
+ // Code prefetch hints, specified by the injection site ID, the target
+ // function and the target site ID.
+ SmallVector<PrefetchHint> PrefetchHints;
// Node counts for each basic block.
DenseMap<UniqueBBID, uint64_t> NodeCounts;
// Edge counts for each edge.
@@ -134,6 +138,10 @@ class BasicBlockSectionsProfileReader {
SmallVector<CallsiteID>
getPrefetchTargetsForFunction(StringRef FuncName) const;
+ // Returns the prefetch hints to be injected in function `FuncName`.
+ SmallVector<PrefetchHint>
+ getPrefetchHintsForFunction(StringRef FuncName) const;
+
private:
StringRef getAliasName(StringRef FuncName) const {
auto R = FuncAliasMap.find(FuncName);
@@ -240,6 +248,9 @@ class BasicBlockSectionsProfileReaderWrapperPass : public ImmutablePass {
SmallVector<CallsiteID>
getPrefetchTargetsForFunction(StringRef FuncName) const;
+ SmallVector<PrefetchHint>
+ getPrefetchHintsForFunction(StringRef FuncName) const;
+
// Initializes the FunctionNameToDIFilename map for the current module and
// then reads the profile for the matching functions.
bool doInitialization(Module &M) override;
diff --git a/llvm/include/llvm/CodeGen/InsertCodePrefetch.h b/llvm/include/llvm/CodeGen/InsertCodePrefetch.h
new file mode 100644
index 0000000000000..a3913ba659d03
--- /dev/null
+++ b/llvm/include/llvm/CodeGen/InsertCodePrefetch.h
@@ -0,0 +1,31 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file contains common utilities for code prefetch insertion.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_INSERTCODEPREFETCH_H
+#define LLVM_CODEGEN_INSERTCODEPREFETCH_H
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/UniqueBBID.h"
+
+namespace llvm {
+
+// Returns the symbol name for a prefetch target at function `FunctionName`,
+// basic block `BBID` and callsite index `CallsiteIndex`.
+SmallString<128> getPrefetchTargetSymbolName(StringRef FunctionName,
+ const UniqueBBID &BBID,
+ unsigned CallsiteIndex);
+
+} // end namespace llvm
+
+#endif // LLVM_CODEGEN_INSERTCODEPREFETCH_H
diff --git a/llvm/include/llvm/CodeGen/MachineBasicBlock.h b/llvm/include/llvm/CodeGen/MachineBasicBlock.h
index 0308cdc1e64b9..a7e072c273efb 100644
--- a/llvm/include/llvm/CodeGen/MachineBasicBlock.h
+++ b/llvm/include/llvm/CodeGen/MachineBasicBlock.h
@@ -218,6 +218,8 @@ class MachineBasicBlock
/// basic block sections and basic block labels.
std::optional<UniqueBBID> BBID;
+ SmallVector<unsigned> PrefetchTargets;
+
/// With basic block sections, this stores the Section ID of the basic block.
MBBSectionID SectionID{0};
diff --git a/llvm/include/llvm/CodeGen/Passes.h b/llvm/include/llvm/CodeGen/Passes.h
index bd5844f715de5..d9cfe065ffbec 100644
--- a/llvm/include/llvm/CodeGen/Passes.h
+++ b/llvm/include/llvm/CodeGen/Passes.h
@@ -73,6 +73,8 @@ LLVM_ABI MachineFunctionPass *createBasicBlockPathCloningPass();
/// and inference when using propeller.
LLVM_ABI MachineFunctionPass *createBasicBlockMatchingAndInferencePass();
+/// createInsertCodePrefetchPass - This pass enables inserting code prefetch
+/// hints based on the basic block section profile.
LLVM_ABI MachineFunctionPass *createInsertCodePrefetchPass();
/// createMachineBlockHashInfoPass - This pass computes basic block hashes.
diff --git a/llvm/include/llvm/CodeGen/TargetInstrInfo.h b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
index cd5561e57d033..f721af808149e 100644
--- a/llvm/include/llvm/CodeGen/TargetInstrInfo.h
+++ b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
@@ -2388,6 +2388,15 @@ class LLVM_ABI TargetInstrInfo : public MCInstrInfo {
llvm_unreachable("unknown number of operands necessary");
}
+ /// Inserts a code prefetch instruction before `InsertBefore` in block `MBB`
+ /// targetting `GV`.
+ virtual MachineInstr *
+ insertCodePrefetchInstr(MachineBasicBlock &MBB,
+ MachineBasicBlock::iterator InsertBefore,
+ const GlobalValue *GV) const {
+ llvm_unreachable("target did not implement");
+ }
+
private:
mutable std::unique_ptr<MIRFormatter> Formatter;
unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
diff --git a/llvm/include/llvm/Support/UniqueBBID.h b/llvm/include/llvm/Support/UniqueBBID.h
index 23a9467534318..87c89ff7eb0cc 100644
--- a/llvm/include/llvm/Support/UniqueBBID.h
+++ b/llvm/include/llvm/Support/UniqueBBID.h
@@ -33,6 +33,14 @@ struct CallsiteID {
unsigned CallsiteIndex;
};
+// This represents a prefetch hint to be injected at site `SiteID`, targeting
+// `TargetID` in function `TargetFunction`.
+struct PrefetchHint {
+ CallsiteID SiteID;
+ StringRef TargetFunction;
+ CallsiteID TargetID;
+};
+
// Provides DenseMapInfo for UniqueBBID.
template <> struct DenseMapInfo<UniqueBBID> {
static inline UniqueBBID getEmptyKey() {
diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index 66a95a16e9538..cb4e4ea8a3177 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -39,6 +39,7 @@
#include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
#include "llvm/CodeGen/GCMetadata.h"
#include "llvm/CodeGen/GCMetadataPrinter.h"
+#include "llvm/CodeGen/InsertCodePrefetch.h"
#include "llvm/CodeGen/LazyMachineBlockFrequencyInfo.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineBlockHashInfo.h"
@@ -2019,13 +2020,12 @@ void AsmPrinter::handleCallsiteForCallgraph(
/// Helper to emit a symbol for the prefetch target associated with the given
/// BBID and callsite index.
-void AsmPrinter::emitPrefetchTargetSymbol(unsigned BaseID,
+void AsmPrinter::emitPrefetchTargetSymbol(const UniqueBBID &BBID,
unsigned CallsiteIndex) {
SmallString<128> FunctionName;
getNameWithPrefix(FunctionName, &MF->getFunction());
MCSymbol *PrefetchTargetSymbol = OutContext.getOrCreateSymbol(
- "__llvm_prefetch_target_" + FunctionName + "_" + Twine(BaseID) + "_" +
- Twine(CallsiteIndex));
+ getPrefetchTargetSymbolName(FunctionName, BBID, CallsiteIndex));
// If the function is weak-linkage it may be replaced by a strong
// version, in which case the prefetch targets should also be replaced.
OutStreamer->emitSymbolAttribute(
@@ -2049,7 +2049,7 @@ void AsmPrinter::emitDanglingPrefetchTargets() {
if (MFBBIDs.contains(BBID))
continue;
for (unsigned CallsiteIndex : CallsiteIndexes)
- emitPrefetchTargetSymbol(BBID.BaseID, CallsiteIndex);
+ emitPrefetchTargetSymbol(BBID, CallsiteIndex);
}
}
@@ -2124,7 +2124,7 @@ void AsmPrinter::emitFunctionBody() {
for (auto &MI : MBB) {
if (PrefetchTargetIt != PrefetchTargetEnd &&
*PrefetchTargetIt == LastCallsiteIndex) {
- emitPrefetchTargetSymbol(MBB.getBBID()->BaseID, *PrefetchTargetIt);
+ emitPrefetchTargetSymbol(*MBB.getBBID(), *PrefetchTargetIt);
++PrefetchTargetIt;
}
@@ -2335,8 +2335,15 @@ void AsmPrinter::emitFunctionBody() {
handleCallsiteForCallgraph(FuncCGInfo, CallSitesInfoMap, MI);
// If there is a post-instruction symbol, emit a label for it here.
- if (MCSymbol *S = MI.getPostInstrSymbol())
+ if (MCSymbol *S = MI.getPostInstrSymbol()) {
+ // Emit the weak symbol attribute used for the prefetch target fallback.
+ if (TM.getTargetTriple().isOSBinFormatELF()) {
+ MCSymbolELF *ESym = static_cast<MCSymbolELF *>(S);
+ if (ESym->getBinding() == ELF::STB_WEAK)
+ OutStreamer->emitSymbolAttribute(S, MCSA_Weak);
+ }
OutStreamer->emitLabel(S);
+ }
for (auto &Handler : Handlers)
Handler->endInstruction();
@@ -2344,7 +2351,7 @@ void AsmPrinter::emitFunctionBody() {
// Emit the remaining prefetch targets for this block. This includes
// nonexisting callsite indexes.
while (PrefetchTargetIt != PrefetchTargetEnd) {
- emitPrefetchTargetSymbol(MBB.getBBID()->BaseID, *PrefetchTargetIt);
+ emitPrefetchTargetSymbol(*MBB.getBBID(), *PrefetchTargetIt);
++PrefetchTargetIt;
}
diff --git a/llvm/lib/CodeGen/BasicBlockSections.cpp b/llvm/lib/CodeGen/BasicBlockSections.cpp
index 69e752e43a70d..9972d431aae8b 100644
--- a/llvm/lib/CodeGen/BasicBlockSections.cpp
+++ b/llvm/lib/CodeGen/BasicBlockSections.cpp
@@ -108,9 +108,9 @@ class BasicBlockSections : public MachineFunctionPass {
public:
static char ID;
- BasicBlockSectionsProfileReaderWrapperPass *BBSectionsProfileReader = nullptr;
-
- BasicBlockSections() : MachineFunctionPass(ID) {}
+ BasicBlockSections() : MachineFunctionPass(ID) {
+ initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
+ }
StringRef getPassName() const override {
return "Basic Block Sections Analysis";
diff --git a/llvm/lib/CodeGen/BasicBlockSectionsProfileReader.cpp b/llvm/lib/CodeGen/BasicBlockSectionsProfileReader.cpp
index 693a9bdf74e60..e5935c8d2ea8f 100644
--- a/llvm/lib/CodeGen/BasicBlockSectionsProfileReader.cpp
+++ b/llvm/lib/CodeGen/BasicBlockSectionsProfileReader.cpp
@@ -101,6 +101,15 @@ BasicBlockSectionsProfileReader::getPrefetchTargetsForFunction(
: SmallVector<CallsiteID>();
}
+SmallVector<PrefetchHint>
+BasicBlockSectionsProfileReader::getPrefetchHintsForFunction(
+ StringRef FuncName) const {
+ StringMap<FunctionOptimizationProfile>::const_iterator It =
+ ProgramOptimizationProfile.find(getAliasName(FuncName));
+ return It != ProgramOptimizationProfile.end() ? It->second.PrefetchHints
+ : SmallVector<PrefetchHint>();
+}
+
// Reads the version 1 basic block sections profile. Profile for each function
// is encoded as follows:
// m <module_name>
@@ -157,7 +166,10 @@ BasicBlockSectionsProfileReader::getPrefetchTargetsForFunction(
// ....
// ****************************************************************************
// This profile can also specify prefetch targets (starting with 't') which
-// instruct the compiler to emit a prefetch symbol for the given target.
+// instruct the compiler to emit a prefetch symbol for the given target and
+// prefetch hints (starting with 'i') which instruct the compiler to insert a
+// prefetch hint instruction at the given site for the given target.
+//
// A prefetch target is specified by a pair "<bbid>,<subblock_index>" where
// bbid specifies the target basic block and subblock_index is a zero-based
// index. Subblock 0 refers to the region at the beginning of the block up to
@@ -167,13 +179,18 @@ BasicBlockSectionsProfileReader::getPrefetchTargetsForFunction(
// This is the beginning of the basic block for `i = 0` and immediately after
// the `i`-th call for every `i > 0`.
//
+// A prefetch hint is specified by a pair "site target", where site is
+// specified as a pair "<bbid>,<callsite_index>" similar to prefetch
+// targets, and target is specified as a triple
+// "<function_name>,<bbid>,<callsite_index>".
+//
// Example: A basic block in function "foo" with BBID 10 and two call
// instructions (call_A, call_B). This block is conceptually split into
-// subblocks, with the prefetch target symbol emitted at the beginning of each
-// subblock.
+// subblocks, with the prefetch target symbol emitted at the beginning of
+// each subblock.
//
// +----------------------------------+
-// | __llvm_prefetch_target_foo_10_0: | <- Subblock 0 (before call_A)
+// | __llvm_prefetch_target_foo_10_0: | <--- Subblock 0 (before call_A)
// | Instruction 1 |
// | Instruction 2 |
// | call_A (Callsite 0) |
@@ -186,6 +203,18 @@ BasicBlockSectionsProfileReader::getPrefetchTargetsForFunction(
// | Instruction 4 |
// +----------------------------------+
//
+// A prefetch hint specified in function "bar" as "120,1 foo,10,2" results
+// in a hint inserted after the first call in block #120 of bar targeting the
+// address immediately after the second call in block #10 of function foo.
+//
+// B
+// +----------------------------------------------------+
+// | Instruction 1 |
+// | call_C (Callsite 1) |
+// | code_prefetch __llvm_prefetch_target_foo_10 |
+// | Instruction 2 |
+// +----------------------------------------------------+
+//
Error BasicBlockSectionsProfileReader::ReadV1Profile() {
auto FI = ProgramOptimizationProfile.end();
@@ -367,6 +396,51 @@ Error BasicBlockSectionsProfileReader::ReadV1Profile() {
CallsiteID{*TargetBBID, static_cast<unsigned>(CallsiteIndex)});
continue;
}
+
+ case 'i': { // Prefetch hint specifier.
+ // Skip the profile when the profile iterator (FI) refers to the
+ // past-the-end element.
+ if (FI == ProgramOptimizationProfile.end())
+ continue;
+ if (Values.size() != 2)
+ return createProfileParseError(
+ Twine("Prefetch hint expected of format '<prefetch-site> "
+ "<prefetch-target>': " +
+ S));
+ SmallVector<StringRef, 2> PrefetchSiteStr;
+ Values[0].split(PrefetchSiteStr, ',');
+ if (PrefetchSiteStr.size() != 2)
+ return createProfileParseError(Twine("Prefetch site expected of format "
+ "'<block-id>,<callsite-id>': ") +
+ Values[0]);
+ auto SiteBBID = parseUniqueBBID(PrefetchSiteStr[0]);
+ if (!SiteBBID)
+ return SiteBBID.takeError();
+ unsigned long long SiteCallsiteIndex;
+ if (getAsUnsignedInteger(PrefetchSiteStr[1], 10, SiteCallsiteIndex))
+ return createProfileParseError(Twine("unsigned integer expected: '") +
+ PrefetchSiteStr[1]);
+
+ SmallVector<StringRef, 3> PrefetchTargetStr;
+ Values[1].split(PrefetchTargetStr, ',');
+ if (PrefetchTargetStr.size() != 3)
+ return createProfileParseError(
+ Twine("Prefetch target expected of format "
+ "'<function-name>,<block-id>,<callsite-id>': ") +
+ Values[1]);
+ auto TargetBBID = parseUniqueBBID(PrefetchTargetStr[1]);
+ if (!TargetBBID)
+ return TargetBBID.takeError();
+ unsigned long long TargetCallsiteIndex;
+ if (getAsUnsignedInteger(PrefetchTargetStr[2], 10, TargetCallsiteIndex))
+ return createProfileParseError(Twine("unsigned integer expected: '") +
+ PrefetchTargetStr[2]);
+ FI->second.PrefetchHints.push_back(PrefetchHint{
+ CallsiteID{*SiteBBID, static_cast<unsigned>(SiteCallsiteIndex)},
+ PrefetchTargetStr[0],
+ CallsiteID{*TargetBBID, static_cast<unsigned>(TargetCallsiteIndex)}});
+ continue;
+ }
default:
return createProfileParseError(Twine("invalid specifier: '") +
Twine(Specifier) + "'");
@@ -585,6 +659,12 @@ BasicBlockSectionsProfileReaderWrapperPass::getPrefetchTargetsForFunction(
return BBSPR.getPrefetchTargetsForFunction(FuncName);
}
+SmallVector<PrefetchHint>
+BasicBlockSectionsProfileReaderWrapperPass::getPrefetchHintsForFunction(
+ StringRef FuncName) const {
+ return BBSPR.getPrefetchHintsForFunction(FuncName);
+}
+
BasicBlockSectionsProfileReader &
BasicBlockSectionsProfileReaderWrapperPass::getBBSPR() {
return BBSPR;
diff --git a/llvm/lib/CodeGen/InsertCodePrefetch.cpp b/llvm/lib/CodeGen/InsertCodePrefetch.cpp
index cd220347257a8..7e06db3974f69 100644
--- a/llvm/lib/CodeGen/InsertCodePrefetch.cpp
+++ b/llvm/lib/CodeGen/InsertCodePrefetch.cpp
@@ -14,9 +14,13 @@
/// be the beginning of any dynamic basic block, that is the beginning of a
/// machine basic block, or immediately after a callsite. A global symbol is
/// emitted at the position of the target so it can be addressed from the
-/// prefetch instruction from any module.
+/// prefetch instruction from any module. In order to insert prefetch hints,
+/// `TargetInstrInfo::insertCodePrefetchInstr` must be implemented by the
+/// target.
//===----------------------------------------------------------------------===//
+#include "llvm/CodeGen/InsertCodePrefetch.h"
+
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
@@ -27,11 +31,27 @@
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/Passes.h"
+#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/InitializePasses.h"
+#include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCSymbolELF.h"
+#include "llvm/Object/ELFTypes.h"
using namespace llvm;
#define DEBUG_TYPE "insert-code-prefetch"
+SmallString<128> llvm::getPrefetchTargetSymbolName(StringRef FunctionName,
+ const UniqueBBID &BBID,
+ unsigned CallsiteIndex) {
+ SmallString<128> R("__llvm_prefetch_target_");
+ R += FunctionName;
+ R += "_";
+ R += utostr(BBID.BaseID);
+ R += "_";
+ R += utostr(CallsiteIndex);
+ return R;
+}
+
namespace {
class InsertCodePrefetch : public MachineFunctionPass {
public:
@@ -62,16 +82,12 @@ INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReaderWrapperPass)
INITIALIZE_PASS_END(InsertCodePrefetch, DEBUG_TYPE, "Code prefetch insertion",
true, false)
-bool InsertCodePrefetch::runOnMachineFunction(MachineFunction &MF) {
- assert(MF.getTarget().getBBSectionsType() == BasicBlockSection::List &&
- "BB Sections list not enabled!");
- if (hasInstrProfHashMismatch(MF))
+static bool setPrefetchTargets(MachineFunction &MF,
+ const SmallVector<CallsiteID> &PrefetchTargets) {
+ if (PrefetchTargets.empty())
return false;
// Set each block's prefetch targets so AsmPrinter can emit a special symbol
// there.
- SmallVector<CallsiteID> PrefetchTargets =
- getAnalysis<BasicBlockSectionsProfileReaderWrapperPass>()
- .getPrefetchTargetsForFunction(MF.getName());
DenseMap<UniqueBBID, SmallVector<unsigned>> PrefetchTargetsByBBID;
for (const auto &Target : PrefetchTargets)
PrefetchTargetsByBBID[Target.BBID].push_back(Target.CallsiteIndex);
@@ -81,7 +97,93 @@ bool InsertCodePrefetch::runOnMachineFunction(MachineFunction &MF) {
V.erase(llvm::unique(V), V.end());
}
MF.setPrefetchTargets(PrefetchTargetsByBBID);
- return false;
+ return true;
+}
+
+static bool
+insertPrefetchHints(MachineFunction &MF,
+ const SmallVector<PrefetchHint> &PrefetchHints) {
+ bool PrefetchInserted = false;
+ bool IsELF = MF.getTarget().getTargetTriple().isOSBinFormatELF();
+ const Module *M = MF.getFunction().getParent();
+ DenseMap<UniqueBBID, SmallVector<PrefetchHint>> PrefetchHintsBySiteBBID;
+ for (const auto &H : PrefetchHints)
+ PrefetchHintsBySiteBBID[H.SiteID.BBID].push_back(H);
+ // Sort prefetch hints by their callsite index so we can insert them by one
+ // pass over the block's instructions.
+ for (auto &[SiteBBID, Hints] : PrefetchHintsBySiteBBID) {
+ llvm::sort(Hints, [](const PrefetchHint &H1, const PrefetchHint &H2) {
+ return H1.SiteID.CallsiteIndex < H2.SiteID.CallsiteIndex;
+ });
+ }
+ auto PtrTy =
+ PointerType::getUnqual(MF.getFunction().getParent()->getContext());
+ const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
+ for (auto &BB : MF) {
+ auto It = PrefetchHintsBySiteBBID.find(*BB.getBBID());
+ if (It == PrefetchHintsBySiteBBID.end())
+ continue;
+ const auto &BBHints = It->second;
+ unsigned NumCallsInBB = 0;
+ auto InstrIt = BB.begin();
+ for (auto HintIt = BBHints.begin(); HintIt != BBHints.end();) {
+ auto NextInstrIt = InstrIt == BB.end() ? BB.end() : std::next(InstrIt);
+ // Insert all the prefetch hints which must be placed after this call (or
+ // at the beginning of the block if `NumCallsInBB` is zero.
+ while (HintIt != BBHints.end() &&
+ HintIt->SiteID.CallsiteIndex == NumCallsInBB) {
+ bool TargetFunctionDefined = false;
+ if (Function *TargetFunction = M->getFunction(HintIt->TargetFunction))
+ TargetFunctionDefined = !TargetFunction->isDeclaration();
+
+ auto TargetSymbolName = getPrefetchTargetSymbolName(
+ HintIt->TargetFunction, HintIt->TargetID.BBID,
+ HintIt->TargetID.CallsiteIndex);
+ auto *GV = MF.getFunction().getParent()->getOrInsertGlobal(
+ TargetSymbolName, PtrTy);
+ MachineInstr *PrefetchInstr =
+ TII->insertCodePrefetchInstr(BB, InstrIt, GV);
+ if (!TargetFunctionDefined && IsELF) {
+ // If the target function is not defined in this module, we guard
+ // against undefined prefetch target symbol by emitting a fallback
+ // symbol with weak linkage right after the prefetch instruction. If
+ // there is no strong symbol, the fallback will be used and we
+ // prefetch the next address:
+ //
+ // prefetchit1 __llvm_prefetch_target_foo_x_y(%rip)
+ // .weak __llvm_prefetch_target_foo_x_y
+ // __llvm_prefetch_target_foo_x_y:
+ MCSymbolELF *WeakFallbackSym = static_cast<MCSymbolELF *>(
+ MF.getContext().getOrCreateSymbol(TargetSymbolName));
+ WeakFallbackSym->setBinding(ELF::STB_WEAK);
+ PrefetchInstr->setPostInstrSymbol(MF, WeakFallbackSym);
+ }
+ PrefetchInserted = true;
+ ++HintIt;
+ }
+ if (InstrIt == BB.end())
+ break;
+ if (InstrIt->isCall())
+ ++NumCallsInBB;
+ InstrIt = NextInstrIt;
+ }
+ }
+ return PrefetchInserted;
+}
+
+bool InsertCodePrefetch::runOnMachineFunction(MachineFunction &MF) {
+ assert(MF.getTarget().getBBSectionsType() == BasicBlockSection::List &&
+ "BB Sections list not enabled!");
+ if (hasInstrProfHashMismatch(MF))
+ return false;
+
+ auto &ProfileReader =
+ getAnalysis<BasicBlockSectionsProfileReaderWrapperPass>();
+ bool R = setPrefetchTargets(
+ MF, ProfileReader.getPrefetchTargetsForFunction(MF.getName()));
+ bool S = insertPrefetchHints(
+ MF, ProfileReader.getPrefetchHintsForFunction(MF.getName()));
+ return R || S;
}
void InsertCodePrefetch::getAnalysisUsage(AnalysisUsage &AU) const {
diff --git a/llvm/lib/Target/X86/X86InstrInfo.cpp b/llvm/lib/Target/X86/X86InstrInfo.cpp
index 5b6858f59e6d6..11a8db9d39541 100644
--- a/llvm/lib/Target/X86/X86InstrInfo.cpp
+++ b/llvm/lib/Target/X86/X86InstrInfo.cpp
@@ -10812,5 +10812,26 @@ void X86InstrInfo::getFrameIndexOperands(SmallVectorImpl<MachineOperand> &Ops,
M.getFullAddress(Ops);
}
+MachineInstr *
+X86InstrInfo::insertCodePrefetchInstr(MachineBasicBlock &MBB,
+ MachineBasicBlock::iterator InsertBefore,
+ const GlobalValue *GV) const {
+ MachineFunction &MF = *MBB.getParent();
+ MachineInstr *PrefetchInstr = MF.CreateMachineInstr(
+ get(X86::PREFETCHIT1),
+ InsertBefore == MBB.instr_end() ? MBB.findPrevDebugLoc(InsertBefore)
+ : InsertBefore->getDebugLoc(),
+ true);
+ MachineInstrBuilder MIB(MF, PrefetchInstr);
+ MIB.addMemOperand(MF.getMachineMemOperand(MachinePointerInfo(GV),
+ MachineMemOperand::MOLoad, /*s=*/8,
+ /*base_alignment=*/llvm::Align(1)));
+ MIB.addReg(X86::RIP).addImm(1).addReg(X86::NoRegister);
+ MIB.addGlobalAddress(GV);
+ MIB.addReg(X86::NoRegister);
+ MBB.insert(InsertBefore, PrefetchInstr);
+ return PrefetchInstr;
+}
+
#define GET_INSTRINFO_HELPERS
#include "X86GenInstrInfo.inc"
diff --git a/llvm/lib/Target/X86/X86InstrInfo.h b/llvm/lib/Target/X86/X86InstrInfo.h
index 9695d9a79ec96..1e2a94a700c3e 100644
--- a/llvm/lib/Target/X86/X86InstrInfo.h
+++ b/llvm/lib/Target/X86/X86InstrInfo.h
@@ -767,6 +767,11 @@ class X86InstrInfo final : public X86GenInstrInfo {
/// \returns the index of operand that is commuted with \p Idx1. If the method
/// fails to commute the operands, it will return \p Idx1.
unsigned commuteOperandsForFold(MachineInstr &MI, unsigned Idx1) const;
+
+ MachineInstr *
+ insertCodePrefetchInstr(MachineBasicBlock &MBB,
+ MachineBasicBlock::iterator InsertBefore,
+ const GlobalValue *GV) const override;
};
} // namespace llvm
diff --git a/llvm/test/CodeGen/X86/basic-block-sections-code-prefetch-call-terminates-block.ll b/llvm/test/CodeGen/X86/basic-block-sections-code-prefetch-call-terminates-block.ll
index bf98076770b5b..b3c8069d96f03 100644
--- a/llvm/test/CodeGen/X86/basic-block-sections-code-prefetch-call-terminates-block.ll
+++ b/llvm/test/CodeGen/X86/basic-block-sections-code-prefetch-call-terminates-block.ll
@@ -1,9 +1,10 @@
-;; Check prefetch directives properly handle a block terminating with a call.
+;; Check prefetch directives properly handles prefetch targets and instructions after a call which terminates a block.
;;
;; Specify the bb sections profile:
; RUN: echo 'v1' > %t
; RUN: echo 'f foo' >> %t
; RUN: echo 't 0,1' >> %t
+; RUN: echo 'i 0,1 other,30,30' >> %t
;;
; RUN: llc < %s -mtriple=x86_64-pc-linux -asm-verbose=false -function-sections -basic-block-sections=%t -O1 | FileCheck %s
@@ -15,6 +16,7 @@ entry:
; CHECK: callq explode at PLT
; CHECK-NEXT: .globl __llvm_prefetch_target_foo_0_1
; CHECK-NEXT: __llvm_prefetch_target_foo_0_1:
+; CHECK-NEXT: prefetchit1 __llvm_prefetch_target_other_30_30(%rip)
continue:
ret i32 0
diff --git a/llvm/test/CodeGen/X86/basic-block-sections-code-prefetch.ll b/llvm/test/CodeGen/X86/basic-block-sections-code-prefetch.ll
index bef121aecf483..dec7557181090 100644
--- a/llvm/test/CodeGen/X86/basic-block-sections-code-prefetch.ll
+++ b/llvm/test/CodeGen/X86/basic-block-sections-code-prefetch.ll
@@ -9,9 +9,14 @@
; RUN: echo 't 2,1' >> %t
; RUN: echo 't 3,0' >> %t
; RUN: echo 't 3,1' >> %t
+; RUN: echo 'i 3,0 bar,0,0' >> %t
+; RUN: echo 'i 2,1 foo,1,0' >> %t
+; RUN: echo 'i 1,1 extfunc,5,5' >> %t
+; RUN: echo 'i 1,1 bar,0,0' >> %t
; RUN: echo 'f bar' >> %t
; RUN: echo 't 0,0' >> %t
; RUN: echo 't 21,1' >> %t
+; RUN: echo 'i 0,1 foo,0,0' >> %t
; RUN: echo 'f qux' >> %t
; RUN: echo 't 0,0' >> %t
; RUN: echo 't 0,1' >> %t
@@ -32,6 +37,10 @@ cond.true: ; preds = %1
; CHECK-NEXT: callq bar at PLT
; CHECK-NEXT: .globl __llvm_prefetch_target_foo_1_1
; CHECK-NEXT: __llvm_prefetch_target_foo_1_1:
+; CHECK-NEXT: prefetchit1 __llvm_prefetch_target_extfunc_5_5(%rip)
+; CHECK-NEXT: .weak __llvm_prefetch_target_extfunc_5_5
+; CHECK-NEXT: __llvm_prefetch_target_extfunc_5_5:
+; CHECK-NEXT: prefetchit1 __llvm_prefetch_target_bar_0_0(%rip)
cond.false: ; preds = %1
call i32 @baz()
@@ -39,12 +48,14 @@ cond.false: ; preds = %1
; CHECK: callq baz at PLT
; CHECK-NEXT: .globl __llvm_prefetch_target_foo_2_1
; CHECK-NEXT: __llvm_prefetch_target_foo_2_1:
+; CHECK-NEXT: prefetchit1 __llvm_prefetch_target_foo_1_0(%rip)
end: ; preds = %11, %9
ret void
; CHECK: .LBB0_3:
; CHECK-NEXT: .globl __llvm_prefetch_target_foo_3_0
; CHECK-NEXT: __llvm_prefetch_target_foo_3_0:
+; CHECK-NEXT: prefetchit1 __llvm_prefetch_target_bar_0_0(%rip)
; CHECK: .globl __llvm_prefetch_target_foo_3_1
; CHECK-NEXT: __llvm_prefetch_target_foo_3_1:
}
@@ -58,6 +69,7 @@ define weak i32 @bar() nounwind {
; CHECK-NEXT: .weak __llvm_prefetch_target_bar_0_0
; CHECK-NEXT: __llvm_prefetch_target_bar_0_0:
; CHECK: callq baz at PLT
+; CHECK-NEXT: prefetchit1 __llvm_prefetch_target_foo_0_0(%rip)
}
define internal i32 @qux() nounwind {
@@ -72,4 +84,3 @@ define internal i32 @qux() nounwind {
}
declare i32 @baz()
-declare i32 @dummy()
More information about the llvm-commits
mailing list