[clang] [llvm] [Clang][CodeGen] Add -gbtf: target-independent BTF emission for ELF targets (PR #183929)
Can H. Tartanoglu via cfe-commits
cfe-commits at lists.llvm.org
Sun Dec 6 03:35:08 PST 2026
https://github.com/caniko updated https://github.com/llvm/llvm-project/pull/183929
>From 27bacf58eadb66eb41bbd9704d2e1dc497342932 Mon Sep 17 00:00:00 2001
From: "Can H. Tartanoglu" <gpg at rotas.mozmail.com>
Date: Sun, 6 Dec 2026 12:03:16 +0100
Subject: [PATCH 1/3] [CodeGen][BPF] Move BTFDebug into CodeGen/AsmPrinter
(NFC)
Split the target-independent BTF type/string encoding in BTFDebug out of
lib/Target/BPF into include/llvm/CodeGen/BTFDebug.h and
lib/CodeGen/AsmPrinter/BTFDebug.cpp, leaving BPF-specific CO-RE
relocations, .maps global handling, DW_CC_nocall register recovery, and
.BTF.ext emission in BPFBTFDebug.
No functional change for BPF targets; shared code contains no target
triple checks.
Assisted-by: Antigravity (Gemini 4 Neon)
---
.../BPF => include/llvm/CodeGen}/BTFDebug.h | 45 +-
llvm/include/llvm/CodeGen/BTFUtils.h | 32 +
.../BPF => CodeGen/AsmPrinter}/BTFDebug.cpp | 545 ++---------------
llvm/lib/CodeGen/AsmPrinter/CMakeLists.txt | 1 +
llvm/lib/Target/BPF/BPFAsmPrinter.cpp | 6 +-
llvm/lib/Target/BPF/BPFAsmPrinter.h | 4 +-
llvm/lib/Target/BPF/BPFBTFDebug.cpp | 550 ++++++++++++++++++
llvm/lib/Target/BPF/BPFBTFDebug.h | 76 +++
llvm/lib/Target/BPF/BPFCORE.h | 16 +-
llvm/lib/Target/BPF/CMakeLists.txt | 2 +-
llvm/test/CodeGen/BPF/BTF/map-atomic.ll | 41 ++
.../test/CodeGen/BPF/BTF/trap-global-order.ll | 23 +
12 files changed, 802 insertions(+), 539 deletions(-)
rename llvm/{lib/Target/BPF => include/llvm/CodeGen}/BTFDebug.h (92%)
create mode 100644 llvm/include/llvm/CodeGen/BTFUtils.h
rename llvm/lib/{Target/BPF => CodeGen/AsmPrinter}/BTFDebug.cpp (72%)
create mode 100644 llvm/lib/Target/BPF/BPFBTFDebug.cpp
create mode 100644 llvm/lib/Target/BPF/BPFBTFDebug.h
create mode 100644 llvm/test/CodeGen/BPF/BTF/map-atomic.ll
create mode 100644 llvm/test/CodeGen/BPF/BTF/trap-global-order.ll
diff --git a/llvm/lib/Target/BPF/BTFDebug.h b/llvm/include/llvm/CodeGen/BTFDebug.h
similarity index 92%
rename from llvm/lib/Target/BPF/BTFDebug.h
rename to llvm/include/llvm/CodeGen/BTFDebug.h
index b29a0cb88624d1..367c911d2c6e42 100644
--- a/llvm/lib/Target/BPF/BTFDebug.h
+++ b/llvm/include/llvm/CodeGen/BTFDebug.h
@@ -11,8 +11,8 @@
///
//===----------------------------------------------------------------------===//
-#ifndef LLVM_LIB_TARGET_BPF_BTFDEBUG_H
-#define LLVM_LIB_TARGET_BPF_BTFDEBUG_H
+#ifndef LLVM_CODEGEN_BTFDEBUG_H
+#define LLVM_CODEGEN_BTFDEBUG_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
@@ -294,13 +294,17 @@ struct BTFFieldReloc {
};
/// Collect and emit BTF information.
+///
+/// Target-independent base class for BTF generation from LLVM IR debug
+/// metadata. Target backends (such as BPF) subclass this to add target-only
+/// features like CO-RE relocations, .maps sections, and .BTF.ext emission.
class BTFDebug : public DebugHandlerBase {
+protected:
MCStreamer &OS;
bool SkipInstruction;
bool LineInfoGenerated;
uint32_t SecNameOff;
uint32_t ArrayIndexTypeId;
- bool MapDefNotCollected;
BTFStringTable StringTable;
std::vector<std::unique_ptr<BTFTypeBase>> TypeEntries;
DenseMap<const DIType *, uint32_t> DIToIdMap;
@@ -311,11 +315,10 @@ class BTFDebug : public DebugHandlerBase {
std::map<std::string, std::unique_ptr<BTFKindDataSec>, std::less<>>
DataSecEntries;
std::vector<BTFTypeStruct *> StructTypes;
- std::map<const GlobalVariable *, std::pair<int64_t, uint32_t>> PatchImms;
std::map<const DICompositeType *,
std::vector<std::pair<const DIDerivedType *, BTFTypeDerived *>>>
FixupDerivedTypes;
- std::set<const Function *>ProtoFunctions;
+ std::set<const Function *> ProtoFunctions;
/// Add types to TypeEntries.
/// @{
@@ -344,7 +347,6 @@ class BTFDebug : public DebugHandlerBase {
void visitEnumType(const DICompositeType *ETy, uint32_t &TypeId);
void visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
bool CheckPointer, bool SeenPointer);
- void visitMapDefType(const DIType *Ty, uint32_t &TypeId);
/// @}
/// Check whether the type is a forward declaration candidate or not.
@@ -358,8 +360,16 @@ class BTFDebug : public DebugHandlerBase {
void constructLineInfo(MCSymbol *Label, const DIFile *File, uint32_t Line,
uint32_t Column);
+ /// Whether a global section is handled separately by a target subclass.
+ virtual bool shouldSkipGlobalSection(StringRef SecName) const {
+ return false;
+ }
+
+ /// Whether to collect and emit .BTF.ext (FuncInfo, LineInfo, FieldReloc).
+ virtual bool shouldEmitBTFExt() const { return false; }
+
/// Generate types and variables for globals.
- void processGlobals(bool ProcessingMapDef);
+ virtual void processGlobals();
/// Process global variable initializer in pursuit for function
/// pointers.
@@ -384,17 +394,9 @@ class BTFDebug : public DebugHandlerBase {
/// is returned.
int genBTFTypeTags(const DIDerivedType *DTy, int BaseTypeId);
- /// Generate one field relocation record.
- void generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
- const GlobalVariable *, bool IsAma);
-
/// Populating unprocessed type on demand.
unsigned populateType(const DIType *Ty);
- /// Process global variables referenced by relocation instructions
- /// and extern function references.
- void processGlobalValue(const MachineOperand &MO);
-
/// Emit common header of .BTF and .BTF.ext sections.
void emitCommonHeader();
@@ -404,7 +406,11 @@ class BTFDebug : public DebugHandlerBase {
/// Emit the .BTF.ext section.
void emitBTFExtSection();
-protected:
+ /// Construct a function's BTF type, allowing target-specific ABI handling.
+ virtual uint32_t
+ processFunctionType(const MachineFunction *MF, const DISubprogram *SP,
+ const SmallDenseMap<uint32_t, StringRef> &FuncArgNames);
+
/// Gather pre-function debug information.
void beginFunctionImpl(const MachineFunction *MF) override;
@@ -414,8 +420,8 @@ class BTFDebug : public DebugHandlerBase {
public:
BTFDebug(AsmPrinter *AP);
- ///
- bool InstLower(const MachineInstr *MI, MCInst &OutMI);
+ /// Strip DW_TAG_atomic_type wrapper if present.
+ static const DIType *tryRemoveAtomicType(const DIType *Ty);
/// Get the special array index type id.
uint32_t getArrayIndexTypeId() {
@@ -434,6 +440,9 @@ class BTFDebug : public DebugHandlerBase {
return DIToIdMap[Ty];
}
+ /// Called at the beginning of instruction processing, before line info.
+ virtual void processBeginInstruction(const MachineInstr *MI) {}
+
/// Process beginning of an instruction.
void beginInstruction(const MachineInstr *MI) override;
diff --git a/llvm/include/llvm/CodeGen/BTFUtils.h b/llvm/include/llvm/CodeGen/BTFUtils.h
new file mode 100644
index 00000000000000..5a782d8175d028
--- /dev/null
+++ b/llvm/include/llvm/CodeGen/BTFUtils.h
@@ -0,0 +1,32 @@
+//===- BTFUtils.h - Helpers for BTF emission -----------*- C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CODEGEN_BTFUTILS_H
+#define LLVM_CODEGEN_BTFUTILS_H
+
+#include "llvm/BinaryFormat/Dwarf.h"
+#include "llvm/IR/DebugInfoMetadata.h"
+#include "llvm/Support/ErrorHandling.h"
+
+namespace llvm {
+
+/// Return the bit offset used to order an element of a BTF structure record.
+inline uint64_t getBTFRecordElementOffset(const DINode *Element) {
+ switch (Element->getTag()) {
+ case dwarf::DW_TAG_member:
+ return cast<DIDerivedType>(Element)->getOffsetInBits();
+ case dwarf::DW_TAG_variant_part:
+ return cast<DICompositeType>(Element)->getOffsetInBits();
+ default:
+ llvm_unreachable("Unexpected DI tag of a struct element");
+ }
+}
+
+} // namespace llvm
+
+#endif
diff --git a/llvm/lib/Target/BPF/BTFDebug.cpp b/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
similarity index 72%
rename from llvm/lib/Target/BPF/BTFDebug.cpp
rename to llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
index 87def75d8d6008..76ff1c8150f3aa 100644
--- a/llvm/lib/Target/BPF/BTFDebug.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
@@ -10,10 +10,7 @@
//
//===----------------------------------------------------------------------===//
-#include "BTFDebug.h"
-#include "BPF.h"
-#include "BPFCORE.h"
-#include "MCTargetDesc/BPFMCTargetDesc.h"
+#include "llvm/CodeGen/BTFDebug.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
@@ -21,38 +18,31 @@
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/CodeGen/AsmPrinter.h"
-#include "llvm/CodeGen/MachineFrameInfo.h"
+#include "llvm/CodeGen/BTFUtils.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
-#include "llvm/CodeGen/TargetRegisterInfo.h"
-#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/Module.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCStreamer.h"
-#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/LineIterator.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
+#include "llvm/Target/TargetMachine.h"
#include <optional>
using namespace llvm;
-#define DEBUG_TYPE "btf-debug"
-
-#define GET_CC_REGISTER_LISTS
-#include "BPFGenCallingConv.inc"
-
static const char *BTFKindStr[] = {
#define HANDLE_BTF_KIND(ID, NAME) "BTF_KIND_" #NAME,
#include "llvm/DebugInfo/BTF/BTF.def"
};
-static const DIType *tryRemoveAtomicType(const DIType *Ty) {
+const DIType *BTFDebug::tryRemoveAtomicType(const DIType *Ty) {
if (!Ty)
return Ty;
auto DerivedTy = dyn_cast<DIDerivedType>(Ty);
@@ -61,200 +51,6 @@ static const DIType *tryRemoveAtomicType(const DIType *Ty) {
return Ty;
}
-static const DIType *stripDITypeAttributes(const DIType *Ty) {
- while (const auto *DTy = dyn_cast_or_null<DIDerivedType>(Ty)) {
- switch (DTy->getTag()) {
- case dwarf::DW_TAG_atomic_type:
- case dwarf::DW_TAG_const_type:
- case dwarf::DW_TAG_restrict_type:
- case dwarf::DW_TAG_typedef:
- case dwarf::DW_TAG_volatile_type:
- Ty = DTy->getBaseType();
- break;
- default:
- return Ty;
- }
- }
- return Ty;
-}
-
-static bool sourceArgMatchesIRType(const DIType *SourceTy, Type *IRTy) {
- SourceTy = stripDITypeAttributes(SourceTy);
-
- // All pointers are opaque in LLVM IR, so any source-level pointer matches any
- // IR pointer regardless of pointee type.
- if (const auto *DTy = dyn_cast<DIDerivedType>(SourceTy))
- return DTy->getTag() == dwarf::DW_TAG_pointer_type && IRTy->isPointerTy();
-
- if (const auto *BTy = dyn_cast<DIBasicType>(SourceTy)) {
- uint64_t SizeInBits = BTy->getSizeInBits();
- if (BTy->getEncoding() == dwarf::DW_ATE_float)
- return IRTy->isFloatingPointTy() &&
- IRTy->getPrimitiveSizeInBits() == SizeInBits;
- // _Bool is 8 bits in DWARF/source but lowered to i1 in LLVM IR.
- if (BTy->getEncoding() == dwarf::DW_ATE_boolean && IRTy->isIntegerTy(1))
- return true;
- return IRTy->isIntegerTy(SizeInBits);
- }
-
- const auto *CTy = dyn_cast<DICompositeType>(SourceTy);
- if (!CTy)
- return false;
-
- switch (CTy->getTag()) {
- case dwarf::DW_TAG_enumeration_type:
- return IRTy->isIntegerTy(CTy->getSizeInBits());
- default:
- return false;
- }
-}
-
-/// Collect the physical register each source argument lives in by scanning
-/// DBG_VALUE instructions in the entry block. A DBG_VALUE is only recorded
-/// when its register either (a) has not been redefined by any preceding
-/// non-debug instruction (i.e. it still holds the caller-passed value), or
-/// (b) was most recently loaded from the stack via $r11 (a stack-passed
-/// argument beyond the first five register args). For each argument only the
-/// first eligible DBG_VALUE is recorded, since that is its entry location.
-///
-/// There is another case where DBG_VALUE is not emitted due to
-/// AssignmentTrackingAnalysis which determines that a variable is
-/// always stack-homed, and describes the variable via MachineFunction's
-/// VariableDbgInfo (setVariableDbgInfo with a frame index). To recover the
-/// register for those arguments, we also track stores of un-redefined physical
-/// registers to stack frame objects during the entry-block walk (using
-/// MachineMemOperands to identify the target frame index), then match them
-/// against VariableDbgInfo entries after the scan.
-static SmallVector<std::pair<uint32_t, Register>, 8>
-collectNocallEntryArgRegs(const MachineFunction &MF) {
- SmallDenseMap<uint32_t, Register> EntryRegMap;
- const DISubprogram *SP = MF.getFunction().getSubprogram();
- SmallDenseSet<Register> DefinedRegs, StackLoadRegs;
-
- // Build a reverse map from IR alloca to frame index so we can
- // identify which frame object a store targets via its MachineMemOperand.
- const MachineFrameInfo &MFI = MF.getFrameInfo();
- SmallDenseMap<const Value *, int> AllocaToFI;
- for (int I = 0, N = MFI.getObjectIndexEnd(); I < N; ++I)
- if (const AllocaInst *AI = MFI.getObjectAllocation(I))
- AllocaToFI[AI] = I;
-
- // Maps frame index → first physical register stored there before
- // that register is redefined.
- SmallDenseMap<int, Register> FrameIndexToReg;
-
- for (const MachineInstr &MI : MF.front()) {
- if (MI.isDebugValue()) {
- // Skip indirect DBG_VALUEs — the register is a base address for a
- // memory location, not the argument value itself.
- if (MI.isIndirectDebugValue())
- continue;
-
- const DILocalVariable *DV = MI.getDebugVariable();
- if (!DV || !DV->getArg() || DV->getScope()->getSubprogram() != SP)
- continue;
-
- uint32_t Arg = DV->getArg();
- const MachineOperand &MO = MI.getDebugOperand(0);
- if (!MO.isReg() || !MO.getReg().isPhysical())
- continue;
-
- if (!DefinedRegs.contains(MO.getReg()) ||
- StackLoadRegs.contains(MO.getReg()))
- EntryRegMap.try_emplace(Arg, MO.getReg());
- continue;
- }
-
- // Track stores of unredefined physical registers to stack frame
- // objects. Use MachineMemOperands to identify the target frame
- // index rather than assuming a particular addressing mode.
- if (MI.mayStore() && !MI.isCall() && MI.getOperand(0).isReg()) {
- Register SrcReg = MI.getOperand(0).getReg();
- if (SrcReg.isPhysical() && !DefinedRegs.contains(SrcReg)) {
- for (const MachineMemOperand *MMO : MI.memoperands()) {
- const Value *V = MMO->getValue();
- if (!V)
- continue;
- auto It = AllocaToFI.find(V);
- if (It != AllocaToFI.end())
- FrameIndexToReg.try_emplace(It->second, SrcReg);
- }
- }
- }
-
- for (const MachineOperand &MO : MI.operands())
- if (MO.isReg() && MO.isDef() && MO.getReg().isPhysical()) {
- DefinedRegs.insert(MO.getReg());
- StackLoadRegs.erase(MO.getReg());
- }
-
- // Detect stack argument loads: $rX = LDD $r11, offset.
- if (MI.getOpcode() == BPF::LDD && MI.getOperand(1).getReg() == BPF::R11)
- StackLoadRegs.insert(MI.getOperand(0).getReg());
- }
-
- // Check VariableDbgInfo for args that AssignmentTrackingAnalysis described
- // via setVariableDbgInfo (single-loc stack-homed variables) rather than
- // DBG_VALUE instructions.
- for (const auto &VI : MF.getVariableDbgInfo()) {
- if (!VI.Var || !VI.Var->getArg() || !VI.inStackSlot())
- continue;
- if (VI.Var->getScope()->getSubprogram() != SP)
- continue;
- uint32_t Arg = VI.Var->getArg();
- if (EntryRegMap.count(Arg))
- continue;
- auto It = FrameIndexToReg.find(VI.getStackSlot());
- if (It != FrameIndexToReg.end())
- EntryRegMap[Arg] = It->second;
- }
-
- SmallVector<std::pair<uint32_t, Register>, 8> AliveArgs(EntryRegMap.begin(),
- EntryRegMap.end());
- llvm::sort(AliveArgs, llvm::less_first());
- return AliveArgs;
-}
-
-/// Check whether the optimized IR signature matches the surviving source
-/// arguments precisely enough to emit a filtered BTF prototype.
-/// Requires exact IR/source arg count match, matching types, and correct
-/// BPF register order (R1..R5) for register args.
-static bool canUseNocallOptimizedSignature(
- const MachineFunction &MF, DITypeArray Elements,
- ArrayRef<std::pair<uint32_t, Register>> AliveArgs,
- const TargetRegisterInfo &TRI) {
- if (MF.getFunction().arg_size() != AliveArgs.size()) {
- LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName() << ": IR arg count ("
- << MF.getFunction().arg_size() << ") != alive arg count ("
- << AliveArgs.size() << ")\n");
- return false;
- }
-
- auto ArgIt = MF.getFunction().arg_begin();
- for (unsigned I = 0, N = AliveArgs.size(); I < N; ++I, ++ArgIt) {
- auto [ArgNo, Reg] = AliveArgs[I];
- if (!sourceArgMatchesIRType(Elements[ArgNo], ArgIt->getType())) {
- LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName()
- << ": type mismatch for source arg " << ArgNo
- << " at IR position " << I << "\n");
- return false;
- }
-
- if (I >= std::size(CC_BPF64_ArgRegs))
- continue;
-
- int DwarfReg = TRI.getDwarfRegNum(Reg, false);
- if (DwarfReg != static_cast<int>(I + 1)) {
- LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName() << ": arg " << ArgNo
- << " in DWARF reg " << DwarfReg << ", expected "
- << (I + 1) << "\n");
- return false;
- }
- }
-
- return true;
-}
-
/// Emit a BTF common type.
void BTFTypeBase::emitType(MCStreamer &OS) {
OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
@@ -337,7 +133,7 @@ void BTFTypeDerived::completeType(BTFDebug &BDebug) {
return;
// A pointer, qualifier, or typedef can refer to void.
- const DIType *Base = tryRemoveAtomicType(DTy->getBaseType());
+ const DIType *Base = BTFDebug::tryRemoveAtomicType(DTy->getBaseType());
BTFType.Type = Base ? BDebug.getTypeId(Base) : 0;
}
@@ -572,7 +368,7 @@ void BTFTypeStruct::completeType(BTFDebug &BDebug) {
} else {
BTFMember.Offset = DDTy->getOffsetInBits();
}
- const auto *BaseTy = tryRemoveAtomicType(DDTy->getBaseType());
+ const auto *BaseTy = BTFDebug::tryRemoveAtomicType(DDTy->getBaseType());
BTFMember.Type = BDebug.getTypeId(BaseTy);
break;
}
@@ -629,14 +425,14 @@ void BTFTypeFuncProto::completeType(BTFDebug &BDebug) {
if (VoidReturn) {
BTFType.Type = 0;
} else {
- auto RetType = tryRemoveAtomicType(Elements[0]);
+ auto RetType = BTFDebug::tryRemoveAtomicType(Elements[0]);
BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
}
BTFType.NameOff = 0;
auto EmitParam = [&](uint32_t I) {
struct BTF::BTFParam Param;
- auto Element = tryRemoveAtomicType(Elements[I]);
+ auto Element = BTFDebug::tryRemoveAtomicType(Elements[I]);
if (Element) {
auto It = FuncArgNames.find(I);
Param.NameOff =
@@ -780,7 +576,8 @@ void BTFTypeTypeTag::completeType(BTFDebug &BDebug) {
IsCompleted = true;
BTFType.NameOff = BDebug.addString(Tag);
if (DTy) {
- const DIType *ResolvedType = tryRemoveAtomicType(DTy->getBaseType());
+ const DIType *ResolvedType =
+ BTFDebug::tryRemoveAtomicType(DTy->getBaseType());
if (!ResolvedType)
BTFType.Type = 0;
else
@@ -804,8 +601,7 @@ uint32_t BTFStringTable::addString(StringRef S) {
BTFDebug::BTFDebug(AsmPrinter *AP)
: DebugHandlerBase(AP), OS(*Asm->OutStreamer), SkipInstruction(false),
- LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0),
- MapDefNotCollected(true) {
+ LineInfoGenerated(false), SecNameOff(0), ArrayIndexTypeId(0) {
addString("\0");
}
@@ -1312,55 +1108,6 @@ void BTFDebug::visitTypeEntry(const DIType *Ty) {
visitTypeEntry(Ty, TypeId, false, false);
}
-void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
- if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
- TypeId = DIToIdMap[Ty];
- return;
- }
-
- uint32_t TmpId;
- switch (Ty->getTag()) {
- case dwarf::DW_TAG_typedef:
- case dwarf::DW_TAG_const_type:
- case dwarf::DW_TAG_volatile_type:
- case dwarf::DW_TAG_restrict_type:
- case dwarf::DW_TAG_pointer_type:
- visitMapDefType(dyn_cast<DIDerivedType>(Ty)->getBaseType(), TmpId);
- break;
- case dwarf::DW_TAG_array_type:
- // Visit nested map array and jump to the element type
- visitMapDefType(dyn_cast<DICompositeType>(Ty)->getBaseType(), TmpId);
- break;
- case dwarf::DW_TAG_structure_type: {
- // Visit all struct members to ensure their types are visited.
- const auto *CTy = cast<DICompositeType>(Ty);
- const DINodeArray Elements = CTy->getElements();
- for (const auto *Element : Elements) {
- const auto *MemberType = cast<DIDerivedType>(Element);
- const DIType *MemberBaseType = MemberType->getBaseType();
- // If the member is a composite type, that may indicate the currently
- // visited composite type is a wrapper, and the member represents the
- // actual map definition.
- // In that case, visit the member with `visitMapDefType` instead of
- // `visitTypeEntry`, treating it specifically as a map definition rather
- // than as a regular composite type.
- const auto *MemberCTy = dyn_cast<DICompositeType>(MemberBaseType);
- if (MemberCTy) {
- visitMapDefType(MemberBaseType, TmpId);
- } else {
- visitTypeEntry(MemberBaseType);
- }
- }
- break;
- }
- default:
- break;
- }
-
- // Visit this type, struct or a const/typedef/volatile/restrict type
- visitTypeEntry(Ty, TypeId, false, false);
-}
-
/// Read file contents from the actual file or from the source
std::string BTFDebug::populateFileContent(const DIFile *File) {
std::string FileName;
@@ -1563,30 +1310,6 @@ void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
}
SkipInstruction = false;
- // Collect MapDef types. Map definition needs to collect
- // pointee types. Do it first. Otherwise, for the following
- // case:
- // struct m { ...};
- // struct t {
- // struct m *key;
- // };
- // foo(struct t *arg);
- //
- // struct mapdef {
- // ...
- // struct m *key;
- // ...
- // } __attribute__((section(".maps"))) hash_map;
- //
- // If subroutine foo is traversed first, a type chain
- // "ptr->struct m(fwd)" will be created and later on
- // when traversing mapdef, since "ptr->struct m" exists,
- // the traversal of "struct m" will be omitted.
- if (MapDefNotCollected) {
- processGlobals(true);
- MapDefNotCollected = false;
- }
-
// Collect all types locally referenced in this function.
// Use RetainedNodes so we can collect all argument names
// even if the argument is not used.
@@ -1602,58 +1325,14 @@ void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
}
}
- // Construct subprogram func proto type.
- uint32_t ProtoTypeId, FuncTypeId;
- uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
- bool IsNocall = SP->getType()->getCC() == dwarf::DW_CC_nocall;
- bool UseFilteredParams = false;
- bool VoidReturn = MF->getFunction().getReturnType()->isVoidTy();
-
- if (IsNocall) {
- // For DW_CC_nocall functions, try to build a FUNC_PROTO reflecting
- // the true ABI: only parameters that survived optimization and whose
- // first 5 arguments map to the correct BPF registers (R1-R5).
- const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
- DITypeArray Elements = SP->getType()->getTypeArray();
-
- SmallVector<std::pair<uint32_t, Register>, 8> AliveArgs =
- collectNocallEntryArgRegs(*MF);
-
- UseFilteredParams =
- canUseNocallOptimizedSignature(*MF, Elements, AliveArgs, *TRI);
-
- if (UseFilteredParams) {
- SmallVector<uint32_t, 8> AliveParamIndices;
- SmallDenseMap<uint32_t, uint32_t> ArgIndexMap;
- for (auto [I, ArgReg] : llvm::enumerate(AliveArgs)) {
- AliveParamIndices.push_back(ArgReg.first);
- ArgIndexMap[ArgReg.first] = I;
- }
-
- if (!VoidReturn)
- visitTypeEntry(Elements[0]);
- for (uint32_t ArgNo : AliveParamIndices)
- visitTypeEntry(Elements[ArgNo]);
-
- auto TypeEntry = std::make_unique<BTFTypeFuncProto>(
- SP->getType(), AliveParamIndices.size(), FuncArgNames, true,
- AliveParamIndices, VoidReturn);
- ProtoTypeId = addType(std::move(TypeEntry));
- FuncTypeId = processDISubprogram(SP, ProtoTypeId, Scope, &ArgIndexMap);
- }
- }
-
- if (!UseFilteredParams) {
- // Fall back to the full source prototype, still voiding the return
- // type if compiler removed it.
- visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId,
- VoidReturn);
- FuncTypeId = processDISubprogram(SP, ProtoTypeId, Scope);
- }
+ uint32_t FuncTypeId = processFunctionType(MF, SP, FuncArgNames);
for (const auto &TypeEntry : TypeEntries)
TypeEntry->completeType(*this);
+ if (!shouldEmitBTFExt())
+ return;
+
// Construct funcinfo and the first lineinfo for the function.
MCSymbol *FuncLabel = Asm->getFunctionBegin();
BTFFuncInfo FuncInfo;
@@ -1665,7 +1344,19 @@ void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
} else {
SecNameOff = addString(".text");
}
- FuncInfoTable[SecNameOff].push_back(FuncInfo);
+ if (FuncTypeId)
+ FuncInfoTable[SecNameOff].push_back(FuncInfo);
+}
+
+uint32_t BTFDebug::processFunctionType(
+ const MachineFunction *MF, const DISubprogram *SP,
+ const SmallDenseMap<uint32_t, StringRef> &FuncArgNames) {
+ uint32_t ProtoTypeId = 0;
+ visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId);
+ if (!ProtoTypeId)
+ return 0;
+ uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
+ return processDISubprogram(SP, ProtoTypeId, Scope);
}
void BTFDebug::endFunctionImpl(const MachineFunction *MF) {
@@ -1684,52 +1375,6 @@ unsigned BTFDebug::populateType(const DIType *Ty) {
return Id;
}
-/// Generate a struct member field relocation.
-void BTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
- const GlobalVariable *GVar, bool IsAma) {
- BTFFieldReloc FieldReloc;
- FieldReloc.Label = ORSym;
- FieldReloc.TypeID = RootId;
-
- if (IsAma) {
- auto Reloc = BPFCoreSharedInfo::AmaRelocation::decode(GVar->getName());
- FieldReloc.OffsetNameOff = addString(Reloc.AccessString);
- FieldReloc.RelocKind = Reloc.Kind;
- PatchImms[GVar] = {Reloc.PatchImm, Reloc.Kind};
- } else {
- StringRef RelocStr = GVar->getName().split('$').second;
- FieldReloc.OffsetNameOff = addString("0");
- FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
- PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
- }
- FieldRelocTable[SecNameOff].push_back(FieldReloc);
-}
-
-void BTFDebug::processGlobalValue(const MachineOperand &MO) {
- // check whether this is a candidate or not
- if (MO.isGlobal()) {
- const GlobalValue *GVal = MO.getGlobal();
- auto *GVar = dyn_cast<GlobalVariable>(GVal);
- if (!GVar) {
- // Not a global variable. Maybe an extern function reference.
- processFuncPrototypes(dyn_cast<Function>(GVal));
- return;
- }
-
- if (!GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) &&
- !GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
- return;
-
- MCSymbol *ORSym = OS.getContext().createTempSymbol();
- OS.emitLabel(ORSym);
-
- MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
- uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
- generatePatchImmReloc(ORSym, RootId, GVar,
- GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr));
- }
-}
-
void BTFDebug::beginInstruction(const MachineInstr *MI) {
DebugHandlerBase::beginInstruction(MI);
@@ -1754,35 +1399,12 @@ void BTFDebug::beginInstruction(const MachineInstr *MI) {
}
}
- if (MI->getOpcode() == BPF::LD_imm64) {
- // If the insn is "r2 = LD_imm64 @<an AmaAttr global>",
- // add this insn into the .BTF.ext FieldReloc subsection.
- // Relocation looks like:
- // . SecName:
- // . InstOffset
- // . TypeID
- // . OffSetNameOff
- // . RelocType
- // Later, the insn is replaced with "r2 = <offset>"
- // where "<offset>" equals to the offset based on current
- // type definitions.
- //
- // If the insn is "r2 = LD_imm64 @<an TypeIdAttr global>",
- // The LD_imm64 result will be replaced with a btf type id.
- processGlobalValue(MI->getOperand(1));
- } else if (MI->getOpcode() == BPF::CORE_LD64 ||
- MI->getOpcode() == BPF::CORE_LD32 ||
- MI->getOpcode() == BPF::CORE_ST ||
- MI->getOpcode() == BPF::CORE_SHIFT) {
- // relocation insn is a load, store or shift insn.
- processGlobalValue(MI->getOperand(3));
- } else if (MI->getOpcode() == BPF::JAL) {
- // check extern function references
- const MachineOperand &MO = MI->getOperand(0);
- if (MO.isGlobal()) {
- processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
- }
- }
+ // Let subclasses process target-specific instructions before line info,
+ // to preserve string table ordering (type names before file paths).
+ processBeginInstruction(MI);
+
+ if (!shouldEmitBTFExt())
+ return;
if (!CurMI) // no debug info
return;
@@ -1816,7 +1438,7 @@ void BTFDebug::beginInstruction(const MachineInstr *MI) {
PrevInstLoc = DL;
}
-void BTFDebug::processGlobals(bool ProcessingMapDef) {
+void BTFDebug::processGlobals() {
// Collect all types referenced by globals.
const Module *M = MMI->getModule();
for (const GlobalVariable &Global : M->globals()) {
@@ -1837,7 +1459,7 @@ void BTFDebug::processGlobals(bool ProcessingMapDef) {
SecName = Sec->getName();
}
- if (ProcessingMapDef != SecName.starts_with(".maps"))
+ if (shouldSkipGlobalSection(SecName))
continue;
// Create a .rodata datasec if the global variable is an initialized
@@ -1863,12 +1485,8 @@ void BTFDebug::processGlobals(bool ProcessingMapDef) {
DIGlobalVariable *DIGlobal = nullptr;
for (auto *GVE : GVs) {
DIGlobal = GVE->getVariable();
- if (SecName.starts_with(".maps"))
- visitMapDefType(DIGlobal->getType(), GVTypeId);
- else {
- const DIType *Ty = tryRemoveAtomicType(DIGlobal->getType());
- visitTypeEntry(Ty, GVTypeId, false, false);
- }
+ const DIType *Ty = tryRemoveAtomicType(DIGlobal->getType());
+ visitTypeEntry(Ty, GVTypeId, false, false);
break;
}
@@ -1942,69 +1560,6 @@ void BTFDebug::processGlobalInitializer(const Constant *C) {
}
}
-/// Emit proper patchable instructions.
-bool BTFDebug::InstLower(const MachineInstr *MI, MCInst &OutMI) {
- if (MI->getOpcode() == BPF::LD_imm64) {
- const MachineOperand &MO = MI->getOperand(1);
- if (MO.isGlobal()) {
- const GlobalValue *GVal = MO.getGlobal();
- auto *GVar = dyn_cast<GlobalVariable>(GVal);
- if (GVar) {
- if (!GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) &&
- !GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
- return false;
-
- // Emit "mov ri, <imm>"
- auto [Imm, Reloc] = PatchImms[GVar];
- Register Reg = MI->getOperand(0).getReg();
- StringRef Imm32 =
- GVar->getAttribute(BPFCoreSharedInfo::EnumValueImm32Attr)
- .getValueAsString();
- if (Imm32 == "unsigned") {
- // Emit "w = <imm>", which zero-extends the immediate.
- OutMI.setOpcode(BPF::MOV_ri_32);
- Reg = MI->getMF()->getSubtarget().getRegisterInfo()->getSubReg(
- Reg, BPF::sub_32);
- } else if (Imm32 == "signed") {
- // Emit "r = <imm>", which sign-extends the immediate.
- OutMI.setOpcode(BPF::MOV_ri);
- } else if (Reloc == BTF::ENUM_VALUE_EXISTENCE ||
- Reloc == BTF::ENUM_VALUE ||
- Reloc == BTF::BTF_TYPE_ID_LOCAL ||
- Reloc == BTF::BTF_TYPE_ID_REMOTE) {
- OutMI.setOpcode(BPF::LD_imm64);
- } else {
- OutMI.setOpcode(BPF::MOV_ri);
- }
- OutMI.addOperand(MCOperand::createReg(Reg));
- OutMI.addOperand(MCOperand::createImm(Imm));
- return true;
- }
- }
- } else if (MI->getOpcode() == BPF::CORE_LD64 ||
- MI->getOpcode() == BPF::CORE_LD32 ||
- MI->getOpcode() == BPF::CORE_ST ||
- MI->getOpcode() == BPF::CORE_SHIFT) {
- const MachineOperand &MO = MI->getOperand(3);
- if (MO.isGlobal()) {
- const GlobalValue *GVal = MO.getGlobal();
- auto *GVar = dyn_cast<GlobalVariable>(GVal);
- if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
- uint32_t Imm = PatchImms[GVar].first;
- OutMI.setOpcode(MI->getOperand(1).getImm());
- if (MI->getOperand(0).isImm())
- OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
- else
- OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
- OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
- OutMI.addOperand(MCOperand::createImm(Imm));
- return true;
- }
- }
- }
- return false;
-}
-
void BTFDebug::processFuncPrototypes(const Function *F) {
if (!F)
return;
@@ -2020,6 +1575,8 @@ void BTFDebug::processFuncPrototypes(const Function *F) {
uint32_t ProtoTypeId;
const SmallDenseMap<uint32_t, StringRef> FuncArgNames;
visitSubroutineType(SP->getType(), false, FuncArgNames, ProtoTypeId);
+ if (!ProtoTypeId)
+ return;
uint32_t FuncId = processDISubprogram(SP, ProtoTypeId, BTF::FUNC_EXTERN);
if (F->hasSection()) {
@@ -2035,21 +1592,8 @@ void BTFDebug::processFuncPrototypes(const Function *F) {
}
void BTFDebug::endModule() {
- // Collect MapDef globals if not collected yet.
- if (MapDefNotCollected) {
- processGlobals(true);
- MapDefNotCollected = false;
- }
-
- // Collect global types/variables except MapDef globals.
- processGlobals(false);
-
- // In case that BPF_TRAP usage is removed during machine-level optimization,
- // generate btf for BPF_TRAP function here.
- for (const Function &F : *MMI->getModule()) {
- if (F.getName() == BPF_TRAP)
- processFuncPrototypes(&F);
- }
+ // Collect global types/variables.
+ processGlobals();
for (auto &DataSec : DataSecEntries)
addType(std::move(DataSec.second));
@@ -2086,11 +1630,12 @@ void BTFDebug::endModule() {
}
}
- // Complete BTF type cross refereences.
+ // Complete BTF type cross references.
for (const auto &TypeEntry : TypeEntries)
TypeEntry->completeType(*this);
// Emit BTF sections.
emitBTFSection();
- emitBTFExtSection();
+ if (shouldEmitBTFExt())
+ emitBTFExtSection();
}
diff --git a/llvm/lib/CodeGen/AsmPrinter/CMakeLists.txt b/llvm/lib/CodeGen/AsmPrinter/CMakeLists.txt
index 58fab8b634ad64..8715c619292bd4 100644
--- a/llvm/lib/CodeGen/AsmPrinter/CMakeLists.txt
+++ b/llvm/lib/CodeGen/AsmPrinter/CMakeLists.txt
@@ -6,6 +6,7 @@ add_llvm_component_library(LLVMAsmPrinter
AsmPrinter.cpp
AsmPrinterDwarf.cpp
AsmPrinterInlineAsm.cpp
+ BTFDebug.cpp
DbgEntityHistoryCalculator.cpp
DebugHandlerBase.cpp
DebugLocStream.cpp
diff --git a/llvm/lib/Target/BPF/BPFAsmPrinter.cpp b/llvm/lib/Target/BPF/BPFAsmPrinter.cpp
index 956d61dd101315..670253f29d662c 100644
--- a/llvm/lib/Target/BPF/BPFAsmPrinter.cpp
+++ b/llvm/lib/Target/BPF/BPFAsmPrinter.cpp
@@ -13,9 +13,9 @@
#include "BPFAsmPrinter.h"
#include "BPF.h"
+#include "BPFBTFDebug.h"
#include "BPFInstrInfo.h"
#include "BPFMCInstLower.h"
-#include "BTFDebug.h"
#include "MCTargetDesc/BPFInstPrinter.h"
#include "TargetInfo/BPFTargetInfo.h"
#include "llvm/BinaryFormat/ELF.h"
@@ -58,8 +58,8 @@ bool BPFAsmPrinter::doInitialization(Module &M) {
// Only emit BTF when debuginfo available.
if (MAI.doesSupportDebugInformation() && !M.debug_compile_units().empty()) {
- BTF = new BTFDebug(this);
- Handlers.push_back(std::unique_ptr<BTFDebug>(BTF));
+ BTF = new BPFBTFDebug(this);
+ Handlers.push_back(std::unique_ptr<BPFBTFDebug>(BTF));
}
return false;
diff --git a/llvm/lib/Target/BPF/BPFAsmPrinter.h b/llvm/lib/Target/BPF/BPFAsmPrinter.h
index 2730871734535d..08a0ebcd2548e5 100644
--- a/llvm/lib/Target/BPF/BPFAsmPrinter.h
+++ b/llvm/lib/Target/BPF/BPFAsmPrinter.h
@@ -9,8 +9,8 @@
#ifndef LLVM_LIB_TARGET_BPF_BPFASMPRINTER_H
#define LLVM_LIB_TARGET_BPF_BPFASMPRINTER_H
+#include "BPFBTFDebug.h"
#include "BPFTargetMachine.h"
-#include "BTFDebug.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionAnalysisManager.h"
@@ -41,7 +41,7 @@ class BPFAsmPrinter : public AsmPrinter {
static char ID;
private:
- BTFDebug *BTF;
+ BPFBTFDebug *BTF;
TargetMachine &TM;
bool SawTrapCall = false;
diff --git a/llvm/lib/Target/BPF/BPFBTFDebug.cpp b/llvm/lib/Target/BPF/BPFBTFDebug.cpp
new file mode 100644
index 00000000000000..eef4aab3a8bc55
--- /dev/null
+++ b/llvm/lib/Target/BPF/BPFBTFDebug.cpp
@@ -0,0 +1,550 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+//
+// BPF-specific BTF debug info generation. Handles CO-RE relocations,
+// .maps section processing, and BPF instruction lowering.
+//
+//===----------------------------------------------------------------------===//
+
+#include "BPFBTFDebug.h"
+#include "BPF.h"
+#include "BPFCORE.h"
+#include "MCTargetDesc/BPFMCTargetDesc.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/BinaryFormat/Dwarf.h"
+#include "llvm/CodeGen/AsmPrinter.h"
+#include "llvm/CodeGen/MachineFrameInfo.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/MachineOperand.h"
+#include "llvm/CodeGen/TargetRegisterInfo.h"
+#include "llvm/CodeGen/TargetSubtargetInfo.h"
+#include "llvm/IR/Module.h"
+#include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCInst.h"
+#include "llvm/MC/MCStreamer.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Target/TargetLoweringObjectFile.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "btf-debug"
+
+#define GET_CC_REGISTER_LISTS
+#include "BPFGenCallingConv.inc"
+
+static const DIType *stripDITypeAttributes(const DIType *Ty) {
+ while (const auto *DTy = dyn_cast_or_null<DIDerivedType>(Ty)) {
+ switch (DTy->getTag()) {
+ case dwarf::DW_TAG_atomic_type:
+ case dwarf::DW_TAG_const_type:
+ case dwarf::DW_TAG_restrict_type:
+ case dwarf::DW_TAG_typedef:
+ case dwarf::DW_TAG_volatile_type:
+ Ty = DTy->getBaseType();
+ break;
+ default:
+ return Ty;
+ }
+ }
+ return Ty;
+}
+
+static bool sourceArgMatchesIRType(const DIType *SourceTy, Type *IRTy) {
+ SourceTy = stripDITypeAttributes(SourceTy);
+
+ // All pointers are opaque in LLVM IR, so any source-level pointer matches any
+ // IR pointer regardless of pointee type.
+ if (const auto *DTy = dyn_cast<DIDerivedType>(SourceTy))
+ return DTy->getTag() == dwarf::DW_TAG_pointer_type && IRTy->isPointerTy();
+
+ if (const auto *BTy = dyn_cast<DIBasicType>(SourceTy)) {
+ uint64_t SizeInBits = BTy->getSizeInBits();
+ if (BTy->getEncoding() == dwarf::DW_ATE_float)
+ return IRTy->isFloatingPointTy() &&
+ IRTy->getPrimitiveSizeInBits() == SizeInBits;
+ // _Bool is 8 bits in DWARF/source but lowered to i1 in LLVM IR.
+ if (BTy->getEncoding() == dwarf::DW_ATE_boolean && IRTy->isIntegerTy(1))
+ return true;
+ return IRTy->isIntegerTy(SizeInBits);
+ }
+
+ const auto *CTy = dyn_cast<DICompositeType>(SourceTy);
+ if (!CTy)
+ return false;
+
+ switch (CTy->getTag()) {
+ case dwarf::DW_TAG_enumeration_type:
+ return IRTy->isIntegerTy(CTy->getSizeInBits());
+ default:
+ return false;
+ }
+}
+
+/// Collect the physical register each source argument lives in by scanning
+/// DBG_VALUE instructions in the entry block. A DBG_VALUE is only recorded
+/// when its register either (a) has not been redefined by any preceding
+/// non-debug instruction (i.e. it still holds the caller-passed value), or
+/// (b) was most recently loaded from the stack via $r11 (a stack-passed
+/// argument beyond the first five register args). For each argument only the
+/// first eligible DBG_VALUE is recorded, since that is its entry location.
+///
+/// There is another case where DBG_VALUE is not emitted due to
+/// AssignmentTrackingAnalysis which determines that a variable is
+/// always stack-homed, and describes the variable via MachineFunction's
+/// VariableDbgInfo (setVariableDbgInfo with a frame index). To recover the
+/// register for those arguments, we also track stores of un-redefined physical
+/// registers to stack frame objects during the entry-block walk (using
+/// MachineMemOperands to identify the target frame index), then match them
+/// against VariableDbgInfo entries after the scan.
+static SmallVector<std::pair<uint32_t, Register>, 8>
+collectNocallEntryArgRegs(const MachineFunction &MF) {
+ SmallDenseMap<uint32_t, Register> EntryRegMap;
+ const DISubprogram *SP = MF.getFunction().getSubprogram();
+ SmallDenseSet<Register> DefinedRegs, StackLoadRegs;
+
+ // Build a reverse map from IR alloca to frame index so we can
+ // identify which frame object a store targets via its MachineMemOperand.
+ const MachineFrameInfo &MFI = MF.getFrameInfo();
+ SmallDenseMap<const Value *, int> AllocaToFI;
+ for (int I = 0, N = MFI.getObjectIndexEnd(); I < N; ++I)
+ if (const AllocaInst *AI = MFI.getObjectAllocation(I))
+ AllocaToFI[AI] = I;
+
+ // Maps frame index → first physical register stored there before
+ // that register is redefined.
+ SmallDenseMap<int, Register> FrameIndexToReg;
+
+ for (const MachineInstr &MI : MF.front()) {
+ if (MI.isDebugValue()) {
+ // Skip indirect DBG_VALUEs — the register is a base address for a
+ // memory location, not the argument value itself.
+ if (MI.isIndirectDebugValue())
+ continue;
+
+ const DILocalVariable *DV = MI.getDebugVariable();
+ if (!DV || !DV->getArg() || DV->getScope()->getSubprogram() != SP)
+ continue;
+
+ uint32_t Arg = DV->getArg();
+ const MachineOperand &MO = MI.getDebugOperand(0);
+ if (!MO.isReg() || !MO.getReg().isPhysical())
+ continue;
+
+ if (!DefinedRegs.contains(MO.getReg()) ||
+ StackLoadRegs.contains(MO.getReg()))
+ EntryRegMap.try_emplace(Arg, MO.getReg());
+ continue;
+ }
+
+ // Track stores of unredefined physical registers to stack frame
+ // objects. Use MachineMemOperands to identify the target frame
+ // index rather than assuming a particular addressing mode.
+ if (MI.mayStore() && !MI.isCall() && MI.getOperand(0).isReg()) {
+ Register SrcReg = MI.getOperand(0).getReg();
+ if (SrcReg.isPhysical() && !DefinedRegs.contains(SrcReg)) {
+ for (const MachineMemOperand *MMO : MI.memoperands()) {
+ const Value *V = MMO->getValue();
+ if (!V)
+ continue;
+ auto It = AllocaToFI.find(V);
+ if (It != AllocaToFI.end())
+ FrameIndexToReg.try_emplace(It->second, SrcReg);
+ }
+ }
+ }
+
+ for (const MachineOperand &MO : MI.operands())
+ if (MO.isReg() && MO.isDef() && MO.getReg().isPhysical()) {
+ DefinedRegs.insert(MO.getReg());
+ StackLoadRegs.erase(MO.getReg());
+ }
+
+ // Detect stack argument loads: $rX = LDD $r11, offset.
+ if (MI.getOpcode() == BPF::LDD && MI.getOperand(1).getReg() == BPF::R11)
+ StackLoadRegs.insert(MI.getOperand(0).getReg());
+ }
+
+ // Check VariableDbgInfo for args that AssignmentTrackingAnalysis described
+ // via setVariableDbgInfo (single-loc stack-homed variables) rather than
+ // DBG_VALUE instructions.
+ for (const auto &VI : MF.getVariableDbgInfo()) {
+ if (!VI.Var || !VI.Var->getArg() || !VI.inStackSlot())
+ continue;
+ if (VI.Var->getScope()->getSubprogram() != SP)
+ continue;
+ uint32_t Arg = VI.Var->getArg();
+ if (EntryRegMap.count(Arg))
+ continue;
+ auto It = FrameIndexToReg.find(VI.getStackSlot());
+ if (It != FrameIndexToReg.end())
+ EntryRegMap[Arg] = It->second;
+ }
+
+ SmallVector<std::pair<uint32_t, Register>, 8> AliveArgs(EntryRegMap.begin(),
+ EntryRegMap.end());
+ llvm::sort(AliveArgs, llvm::less_first());
+ return AliveArgs;
+}
+
+/// Check whether the optimized IR signature matches the surviving source
+/// arguments precisely enough to emit a filtered BTF prototype.
+/// Requires exact IR/source arg count match, matching types, and correct
+/// BPF register order (R1..R5) for register args.
+static bool canUseNocallOptimizedSignature(
+ const MachineFunction &MF, DITypeArray Elements,
+ ArrayRef<std::pair<uint32_t, Register>> AliveArgs,
+ const TargetRegisterInfo &TRI) {
+ if (MF.getFunction().arg_size() != AliveArgs.size()) {
+ LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName() << ": IR arg count ("
+ << MF.getFunction().arg_size() << ") != alive arg count ("
+ << AliveArgs.size() << ")\n");
+ return false;
+ }
+
+ auto ArgIt = MF.getFunction().arg_begin();
+ for (unsigned I = 0, N = AliveArgs.size(); I < N; ++I, ++ArgIt) {
+ auto [ArgNo, Reg] = AliveArgs[I];
+ if (!sourceArgMatchesIRType(Elements[ArgNo], ArgIt->getType())) {
+ LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName()
+ << ": type mismatch for source arg " << ArgNo
+ << " at IR position " << I << "\n");
+ return false;
+ }
+
+ if (I >= std::size(CC_BPF64_ArgRegs))
+ continue;
+
+ int DwarfReg = TRI.getDwarfRegNum(Reg, false);
+ if (DwarfReg != static_cast<int>(I + 1)) {
+ LLVM_DEBUG(dbgs() << "BTF skip " << MF.getName() << ": arg " << ArgNo
+ << " in DWARF reg " << DwarfReg << ", expected "
+ << (I + 1) << "\n");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+BPFBTFDebug::BPFBTFDebug(AsmPrinter *AP)
+ : BTFDebug(AP), MapDefNotCollected(true) {}
+
+void BPFBTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
+ if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
+ TypeId = DIToIdMap[Ty];
+ return;
+ }
+
+ uint32_t TmpId;
+ switch (Ty->getTag()) {
+ case dwarf::DW_TAG_typedef:
+ case dwarf::DW_TAG_const_type:
+ case dwarf::DW_TAG_volatile_type:
+ case dwarf::DW_TAG_restrict_type:
+ case dwarf::DW_TAG_pointer_type:
+ visitMapDefType(dyn_cast<DIDerivedType>(Ty)->getBaseType(), TmpId);
+ break;
+ case dwarf::DW_TAG_array_type:
+ // Visit nested map array and jump to the element type
+ visitMapDefType(dyn_cast<DICompositeType>(Ty)->getBaseType(), TmpId);
+ break;
+ case dwarf::DW_TAG_structure_type: {
+ const DICompositeType *CTy = dyn_cast<DICompositeType>(Ty);
+ const DINodeArray Elements = CTy->getElements();
+ for (const auto *Element : Elements) {
+ const auto *MemberType = cast<DIDerivedType>(Element);
+ const DIType *MemberBaseType = MemberType->getBaseType();
+
+ // Check if the visited composite type is a wrapper, and the member
+ // represents the actual map definition.
+ const auto *MemberCTy = dyn_cast<DICompositeType>(MemberBaseType);
+ if (MemberCTy) {
+ visitMapDefType(MemberBaseType, TmpId);
+ } else {
+ visitTypeEntry(MemberBaseType);
+ }
+ }
+ break;
+ }
+ default:
+ break;
+ }
+
+ // Visit this type, struct or a const/typedef/volatile/restrict type
+ visitTypeEntry(Ty, TypeId, false, false);
+}
+
+void BPFBTFDebug::processMapDefGlobals() {
+ const Module *M = MMI->getModule();
+ for (const GlobalVariable &Global : M->globals()) {
+ StringRef SecName;
+ std::optional<SectionKind> GVKind;
+
+ if (!Global.isDeclarationForLinker())
+ GVKind = TargetLoweringObjectFile::getKindForGlobal(&Global, Asm->TM);
+
+ if (Global.isDeclarationForLinker())
+ SecName = Global.hasSection() ? Global.getSection() : "";
+ else if (GVKind->isCommon())
+ SecName = ".bss";
+ else {
+ TargetLoweringObjectFile *TLOF = Asm->TM.getObjFileLowering();
+ MCSection *Sec = TLOF->SectionForGlobal(&Global, Asm->TM);
+ SecName = Sec->getName();
+ }
+
+ // Only process .maps globals in this pass.
+ if (!SecName.starts_with(".maps"))
+ continue;
+
+ SmallVector<DIGlobalVariableExpression *, 1> GVs;
+ Global.getDebugInfo(GVs);
+ if (GVs.size() == 0)
+ continue;
+
+ uint32_t GVTypeId = 0;
+ DIGlobalVariable *DIGlobal = nullptr;
+ for (auto *GVE : GVs) {
+ DIGlobal = GVE->getVariable();
+ visitMapDefType(DIGlobal->getType(), GVTypeId);
+ break;
+ }
+
+ auto Linkage = Global.getLinkage();
+ if (Linkage != GlobalValue::InternalLinkage &&
+ Linkage != GlobalValue::ExternalLinkage &&
+ Linkage != GlobalValue::WeakAnyLinkage &&
+ Linkage != GlobalValue::WeakODRLinkage &&
+ Linkage != GlobalValue::ExternalWeakLinkage)
+ continue;
+
+ uint32_t GVarInfo;
+ if (Linkage == GlobalValue::InternalLinkage) {
+ GVarInfo = BTF::VAR_STATIC;
+ } else if (Global.hasInitializer()) {
+ GVarInfo = BTF::VAR_GLOBAL_ALLOCATED;
+ } else {
+ GVarInfo = BTF::VAR_GLOBAL_EXTERNAL;
+ }
+
+ auto VarEntry =
+ std::make_unique<BTFKindVar>(Global.getName(), GVTypeId, GVarInfo);
+ uint32_t VarId = addType(std::move(VarEntry));
+
+ processDeclAnnotations(DIGlobal->getAnnotations(), VarId, -1);
+
+ if (SecName.empty())
+ continue;
+
+ auto [It, Inserted] = DataSecEntries.try_emplace(std::string(SecName));
+ if (Inserted)
+ It->second = std::make_unique<BTFKindDataSec>(Asm, std::string(SecName));
+
+ const DataLayout &DL = Global.getDataLayout();
+ uint32_t Size = Global.getGlobalSize(DL);
+
+ It->second->addDataSecEntry(VarId, Asm->getSymbol(&Global), Size);
+
+ if (Global.hasInitializer())
+ processGlobalInitializer(Global.getInitializer());
+ }
+}
+
+void BPFBTFDebug::processGlobals() {
+ // First process .maps globals if not yet done.
+ if (MapDefNotCollected) {
+ processMapDefGlobals();
+ MapDefNotCollected = false;
+ }
+ // Then process all non-.maps globals via the base class.
+ BTFDebug::processGlobals();
+
+ // The trap call may have been removed during machine-level optimization.
+ for (const Function &F : *MMI->getModule())
+ if (F.getName() == BPF_TRAP)
+ processFuncPrototypes(&F);
+}
+
+void BPFBTFDebug::generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
+ const GlobalVariable *GVar,
+ bool IsAma) {
+ BTFFieldReloc FieldReloc;
+ FieldReloc.Label = ORSym;
+ FieldReloc.TypeID = RootId;
+
+ if (IsAma) {
+ auto Reloc = BPFCoreSharedInfo::AmaRelocation::decode(GVar->getName());
+ FieldReloc.OffsetNameOff = addString(Reloc.AccessString);
+ FieldReloc.RelocKind = Reloc.Kind;
+ PatchImms[GVar] = {Reloc.PatchImm, Reloc.Kind};
+ } else {
+ StringRef RelocStr = GVar->getName().split('$').second;
+ FieldReloc.OffsetNameOff = addString("0");
+ FieldReloc.RelocKind = std::stoull(std::string(RelocStr));
+ PatchImms[GVar] = std::make_pair(RootId, FieldReloc.RelocKind);
+ }
+ FieldRelocTable[SecNameOff].push_back(FieldReloc);
+}
+
+void BPFBTFDebug::processGlobalValue(const MachineOperand &MO) {
+ if (MO.isGlobal()) {
+ const GlobalValue *GVal = MO.getGlobal();
+ auto *GVar = dyn_cast<GlobalVariable>(GVal);
+ if (!GVar) {
+ processFuncPrototypes(dyn_cast<Function>(GVal));
+ return;
+ }
+
+ if (!GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) &&
+ !GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr))
+ return;
+
+ MCSymbol *ORSym = OS.getContext().createTempSymbol();
+ OS.emitLabel(ORSym);
+
+ MDNode *MDN = GVar->getMetadata(LLVMContext::MD_preserve_access_index);
+ uint32_t RootId = populateType(dyn_cast<DIType>(MDN));
+ generatePatchImmReloc(ORSym, RootId, GVar,
+ GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr));
+ }
+}
+
+uint32_t BPFBTFDebug::processFunctionType(
+ const MachineFunction *MF, const DISubprogram *SP,
+ const SmallDenseMap<uint32_t, StringRef> &FuncArgNames) {
+ uint32_t ProtoTypeId = 0;
+ uint8_t Scope = SP->isLocalToUnit() ? BTF::FUNC_STATIC : BTF::FUNC_GLOBAL;
+ bool IsNocall = SP->getType()->getCC() == dwarf::DW_CC_nocall;
+ bool VoidReturn = MF->getFunction().getReturnType()->isVoidTy();
+
+ if (IsNocall) {
+ // For DW_CC_nocall functions, try to build a FUNC_PROTO reflecting
+ // the true ABI: only parameters that survived optimization and whose
+ // first 5 arguments map to the correct BPF registers (R1-R5).
+ const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
+ DITypeArray Elements = SP->getType()->getTypeArray();
+ SmallVector<std::pair<uint32_t, Register>, 8> AliveArgs =
+ collectNocallEntryArgRegs(*MF);
+
+ if (canUseNocallOptimizedSignature(*MF, Elements, AliveArgs, *TRI)) {
+ SmallVector<uint32_t, 8> AliveParamIndices;
+ SmallDenseMap<uint32_t, uint32_t> ArgIndexMap;
+ for (auto [I, ArgReg] : llvm::enumerate(AliveArgs)) {
+ AliveParamIndices.push_back(ArgReg.first);
+ ArgIndexMap[ArgReg.first] = I;
+ }
+
+ if (!VoidReturn)
+ visitTypeEntry(Elements[0]);
+ for (uint32_t ArgNo : AliveParamIndices)
+ visitTypeEntry(Elements[ArgNo]);
+
+ auto TypeEntry = std::make_unique<BTFTypeFuncProto>(
+ SP->getType(), AliveParamIndices.size(), FuncArgNames, true,
+ AliveParamIndices, VoidReturn);
+ ProtoTypeId = addType(std::move(TypeEntry));
+ return processDISubprogram(SP, ProtoTypeId, Scope, &ArgIndexMap);
+ }
+ }
+
+ // Fall back to the full source prototype, still voiding the return
+ // type if compiler removed it.
+ visitSubroutineType(SP->getType(), true, FuncArgNames, ProtoTypeId,
+ VoidReturn);
+ if (!ProtoTypeId)
+ return 0;
+ return processDISubprogram(SP, ProtoTypeId, Scope);
+}
+
+void BPFBTFDebug::beginFunctionImpl(const MachineFunction *MF) {
+ if (MapDefNotCollected) {
+ processMapDefGlobals();
+ MapDefNotCollected = false;
+ }
+
+ BTFDebug::beginFunctionImpl(MF);
+}
+
+void BPFBTFDebug::processBeginInstruction(const MachineInstr *MI) {
+ // Handle CO-RE and extern function relocations.
+ if (MI->getOpcode() == BPF::LD_imm64) {
+ processGlobalValue(MI->getOperand(1));
+ } else if (MI->getOpcode() == BPF::CORE_LD64 ||
+ MI->getOpcode() == BPF::CORE_LD32 ||
+ MI->getOpcode() == BPF::CORE_ST ||
+ MI->getOpcode() == BPF::CORE_SHIFT) {
+ processGlobalValue(MI->getOperand(3));
+ } else if (MI->getOpcode() == BPF::JAL) {
+ const MachineOperand &MO = MI->getOperand(0);
+ if (MO.isGlobal()) {
+ processFuncPrototypes(dyn_cast<Function>(MO.getGlobal()));
+ }
+ }
+}
+
+bool BPFBTFDebug::InstLower(const MachineInstr *MI, MCInst &OutMI) {
+ if (MI->getOpcode() == BPF::LD_imm64) {
+ const MachineOperand &MO = MI->getOperand(1);
+ if (MO.isGlobal()) {
+ const GlobalVariable *GVar = dyn_cast<GlobalVariable>(MO.getGlobal());
+ if (GVar) {
+ // Emit "mov ri, <imm>" for patched insns.
+ if (GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr) ||
+ GVar->hasAttribute(BPFCoreSharedInfo::TypeIdAttr)) {
+ auto [Imm, Reloc] = PatchImms[GVar];
+ Register Reg = MI->getOperand(0).getReg();
+ StringRef Imm32 =
+ GVar->getAttribute(BPFCoreSharedInfo::EnumValueImm32Attr)
+ .getValueAsString();
+ if (Imm32 == "unsigned") {
+ // Emit "w = <imm>", which zero-extends the immediate.
+ OutMI.setOpcode(BPF::MOV_ri_32);
+ Reg = MI->getMF()->getSubtarget().getRegisterInfo()->getSubReg(
+ Reg, BPF::sub_32);
+ } else if (Imm32 == "signed") {
+ // Emit "r = <imm>", which sign-extends the immediate.
+ OutMI.setOpcode(BPF::MOV_ri);
+ } else if (Reloc == BTF::ENUM_VALUE_EXISTENCE ||
+ Reloc == BTF::ENUM_VALUE ||
+ Reloc == BTF::BTF_TYPE_ID_LOCAL ||
+ Reloc == BTF::BTF_TYPE_ID_REMOTE) {
+ OutMI.setOpcode(BPF::LD_imm64);
+ } else {
+ OutMI.setOpcode(BPF::MOV_ri);
+ }
+ OutMI.addOperand(MCOperand::createReg(Reg));
+ OutMI.addOperand(MCOperand::createImm(Imm));
+ return true;
+ }
+ }
+ }
+ } else if (MI->getOpcode() == BPF::CORE_LD64 ||
+ MI->getOpcode() == BPF::CORE_LD32 ||
+ MI->getOpcode() == BPF::CORE_ST ||
+ MI->getOpcode() == BPF::CORE_SHIFT) {
+ const MachineOperand &MO = MI->getOperand(3);
+ if (MO.isGlobal()) {
+ const GlobalValue *GVal = MO.getGlobal();
+ auto *GVar = dyn_cast<GlobalVariable>(GVal);
+ if (GVar && GVar->hasAttribute(BPFCoreSharedInfo::AmaAttr)) {
+ uint32_t Imm = PatchImms[GVar].first;
+ OutMI.setOpcode(MI->getOperand(1).getImm());
+ if (MI->getOperand(0).isImm())
+ OutMI.addOperand(MCOperand::createImm(MI->getOperand(0).getImm()));
+ else
+ OutMI.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
+ OutMI.addOperand(MCOperand::createReg(MI->getOperand(2).getReg()));
+ OutMI.addOperand(MCOperand::createImm(Imm));
+ return true;
+ }
+ }
+ }
+ return false;
+}
diff --git a/llvm/lib/Target/BPF/BPFBTFDebug.h b/llvm/lib/Target/BPF/BPFBTFDebug.h
new file mode 100644
index 00000000000000..46b09f25f18919
--- /dev/null
+++ b/llvm/lib/Target/BPF/BPFBTFDebug.h
@@ -0,0 +1,76 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+/// BPF-specific BTF debug info emission. Extends the target-independent
+/// BTFDebug with CO-RE relocations, .maps section handling, and BPF
+/// instruction processing.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIB_TARGET_BPF_BPFBTFDEBUG_H
+#define LLVM_LIB_TARGET_BPF_BPFBTFDEBUG_H
+
+#include "llvm/CodeGen/BTFDebug.h"
+
+namespace llvm {
+
+class MCInst;
+
+/// BPF-specific BTF debug handler.
+///
+/// Extends the target-independent BTFDebug with:
+/// - CO-RE (Compile-Once Run-Everywhere) field relocations
+/// - .maps section handling for BPF map definitions
+/// - BPF instruction lowering for patchable instructions
+class BPFBTFDebug : public BTFDebug {
+ bool MapDefNotCollected;
+ std::map<const GlobalVariable *, std::pair<int64_t, uint32_t>> PatchImms;
+
+ /// Visit a .maps type definition.
+ void visitMapDefType(const DIType *Ty, uint32_t &TypeId);
+
+ /// Process global variable references from BPF instructions (CO-RE).
+ void processGlobalValue(const MachineOperand &MO);
+
+ /// Generate a field relocation record for CO-RE.
+ void generatePatchImmReloc(const MCSymbol *ORSym, uint32_t RootId,
+ const GlobalVariable *GVar, bool IsAma);
+
+ /// Process .maps globals separately.
+ void processMapDefGlobals();
+
+ /// Skip .maps globals in the base pass (handled by processMapDefGlobals).
+ bool shouldSkipGlobalSection(StringRef SecName) const override {
+ return SecName.starts_with(".maps");
+ }
+
+ /// Emit .BTF.ext (FuncInfo, LineInfo, CO-RE FieldReloc) for BPF.
+ bool shouldEmitBTFExt() const override { return true; }
+
+ /// Process all globals including .maps handling.
+ void processGlobals() override;
+
+protected:
+ uint32_t processFunctionType(
+ const MachineFunction *MF, const DISubprogram *SP,
+ const SmallDenseMap<uint32_t, StringRef> &FuncArgNames) override;
+ void beginFunctionImpl(const MachineFunction *MF) override;
+
+public:
+ BPFBTFDebug(AsmPrinter *AP);
+
+ /// Emit proper patchable instructions (CO-RE lowering).
+ bool InstLower(const MachineInstr *MI, MCInst &OutMI);
+
+ void processBeginInstruction(const MachineInstr *MI) override;
+};
+
+} // end namespace llvm
+
+#endif
diff --git a/llvm/lib/Target/BPF/BPFCORE.h b/llvm/lib/Target/BPF/BPFCORE.h
index 741a0c656d1b66..2c91eb01fc671d 100644
--- a/llvm/lib/Target/BPF/BPFCORE.h
+++ b/llvm/lib/Target/BPF/BPFCORE.h
@@ -10,11 +10,9 @@
#define LLVM_LIB_TARGET_BPF_BPFCORE_H
#include "llvm/ADT/StringRef.h"
-#include "llvm/BinaryFormat/Dwarf.h"
+#include "llvm/CodeGen/BTFUtils.h"
#include "llvm/DebugInfo/BTF/BTF.h"
-#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Instructions.h"
-#include "llvm/Support/ErrorHandling.h"
namespace llvm {
@@ -22,18 +20,6 @@ class BasicBlock;
class Instruction;
class Module;
-/// Return the bit offset used to order an element of a BTF structure record.
-inline uint64_t getBTFRecordElementOffset(const DINode *Element) {
- switch (Element->getTag()) {
- case dwarf::DW_TAG_member:
- return cast<DIDerivedType>(Element)->getOffsetInBits();
- case dwarf::DW_TAG_variant_part:
- return cast<DICompositeType>(Element)->getOffsetInBits();
- default:
- llvm_unreachable("Unexpected DI tag of a struct element");
- }
-}
-
class BPFCoreSharedInfo {
public:
enum BTFTypeIdFlag : uint32_t {
diff --git a/llvm/lib/Target/BPF/CMakeLists.txt b/llvm/lib/Target/BPF/CMakeLists.txt
index 74a8b6b5813536..419c27fb1cdbd1 100644
--- a/llvm/lib/Target/BPF/CMakeLists.txt
+++ b/llvm/lib/Target/BPF/CMakeLists.txt
@@ -26,6 +26,7 @@ add_llvm_target(BPFCodeGen
BPFAdjustOpt.cpp
BPFAsmPrinter.cpp
BPFASpaceCastSimplifyPass.cpp
+ BPFBTFDebug.cpp
BPFCheckAndAdjustIR.cpp
BPFCodeGenPassBuilder.cpp
BPFFrameLowering.cpp
@@ -46,7 +47,6 @@ add_llvm_target(BPFCodeGen
BPFMIPeephole.cpp
BPFMIChecking.cpp
BPFMISimplifyPatchable.cpp
- BTFDebug.cpp
LINK_COMPONENTS
Analysis
diff --git a/llvm/test/CodeGen/BPF/BTF/map-atomic.ll b/llvm/test/CodeGen/BPF/BTF/map-atomic.ll
new file mode 100644
index 00000000000000..7c41096d108667
--- /dev/null
+++ b/llvm/test/CodeGen/BPF/BTF/map-atomic.ll
@@ -0,0 +1,41 @@
+; RUN: llc -mtriple=bpfel %s -o - | FileCheck %s
+; RUN: llc -mtriple=bpfeb %s -o - | FileCheck %s
+; CHECK: BTF_KIND_FWD
+; CHECK-NOT: BTF_KIND_STRUCT
+; CHECK: .ascii "Leaf"
+; ModuleID = 'map-atomic.c'
+source_filename = "map-atomic.c"
+target datalayout = "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128"
+target triple = "bpfel"
+
+%struct.Wrapper = type { %struct.Inner }
+%struct.Inner = type { ptr }
+
+ at m = dso_local global %struct.Wrapper zeroinitializer, section ".maps", align 8, !dbg !0
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!17, !18, !19, !20}
+!llvm.ident = !{!21}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "m", scope: !2, file: !3, line: 4, type: !5, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C11, file: !3, producer: "clang version 24.0.0git (git at github.com:caniko/llvm-project.git cd014203541ab1ec3cd7caed62e64ba403773d00)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, globals: !4, splitDebugInlining: false, nameTableKind: None)
+!3 = !DIFile(filename: "map-atomic.c", directory: "/")
+!4 = !{!0}
+!5 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper", file: !3, line: 3, size: 64, elements: !6)
+!6 = !{!7}
+!7 = !DIDerivedType(tag: DW_TAG_member, name: "member", scope: !5, file: !3, line: 3, baseType: !8, size: 64)
+!8 = !DIDerivedType(tag: DW_TAG_atomic_type, baseType: !9)
+!9 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Inner", file: !3, line: 2, size: 64, elements: !10)
+!10 = !{!11}
+!11 = !DIDerivedType(tag: DW_TAG_member, name: "p", scope: !9, file: !3, line: 2, baseType: !12, size: 64)
+!12 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !13, size: 64)
+!13 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Leaf", file: !3, line: 1, size: 32, elements: !14)
+!14 = !{!15}
+!15 = !DIDerivedType(tag: DW_TAG_member, name: "x", scope: !13, file: !3, line: 1, baseType: !16, size: 32)
+!16 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!17 = !{i32 7, !"Dwarf Version", i32 5}
+!18 = !{i32 2, !"Debug Info Version", i32 3}
+!19 = !{i32 2, !"debugger-tuning", !"gdb"}
+!20 = !{i32 7, !"frame-pointer", i32 2}
+!21 = !{!"clang version 24.0.0git (git at github.com:caniko/llvm-project.git cd014203541ab1ec3cd7caed62e64ba403773d00)"}
diff --git a/llvm/test/CodeGen/BPF/BTF/trap-global-order.ll b/llvm/test/CodeGen/BPF/BTF/trap-global-order.ll
new file mode 100644
index 00000000000000..ea324ec5b6b757
--- /dev/null
+++ b/llvm/test/CodeGen/BPF/BTF/trap-global-order.ll
@@ -0,0 +1,23 @@
+; RUN: llc -mtriple=bpfel -filetype=asm %s -o - | FileCheck %s
+; RUN: llc -mtriple=bpfeb -filetype=asm %s -o - | FileCheck %s
+; The fallback trap prototype must follow global types and variables.
+; CHECK: BTF_KIND_INT(id = 1)
+; CHECK: BTF_KIND_VAR(id = 2)
+; CHECK: BTF_KIND_FUNC_PROTO(id = 3)
+; CHECK: BTF_KIND_FUNC(id = 4)
+
+ at g = global i32 1, !dbg !0
+declare !dbg !8 void @__bpf_trap() section ".ksyms"
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!6, !7}
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "g", scope: !2, file: !3, line: 1, type: !4, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C11, file: !3, emissionKind: FullDebug, globals: !5)
+!3 = !DIFile(filename: "test.c", directory: "/")
+!4 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!5 = !{!0}
+!6 = !{i32 7, !"Dwarf Version", i32 5}
+!7 = !{i32 2, !"Debug Info Version", i32 3}
+!8 = !DISubprogram(name: "__bpf_trap", scope: !3, file: !3, type: !9, spFlags: 0)
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
>From 7f18d31c6d406ee15ed38ac4671852618fdfd76c Mon Sep 17 00:00:00 2001
From: "Can H. Tartanoglu" <gpg at rotas.mozmail.com>
Date: Sun, 6 Dec 2026 12:08:11 +0100
Subject: [PATCH 2/3] [BTF] Enforce BTF format limits and add pruning policy in
BTFDebug
Enforce BTF format representability uniformly in shared BTFDebug without
any target-triple checks:
- Reject integers > 128 bits and enums > 64 bits (BTF format limits).
- Map supported DW_ATE_complex_float sizes to BTF_KIND_FLOAT and omit
unrepresentable by-value types (with pointers to them resolving to void
or FWD, matching GCC -gbtf).
- Unwrap typedef/qualifier chains on enum base types and filter out C++
static members, methods, and virtual bases while preserving non-virtual
base subobjects.
- Use O(1) StringMap deduplication in BTFStringTable, idempotent
NumCompletedTypes tracking, and MapVector for deterministic deferred
pointee fixup order resolved by DIType/ODR identity rather than name.
- Add shouldPruneBTF() retention policy (default true in BPFBTFDebug to
preserve BPF behavior; false in base BTFDebug to retain CU/local types
and iteratively emit full definitions for deferred pointees).
Assisted-by: Antigravity (Gemini 4 Neon)
---
llvm/include/llvm/CodeGen/BTFDebug.h | 41 ++-
llvm/include/llvm/CodeGen/BTFUtils.h | 1 +
llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp | 339 ++++++++++++++++++++---
llvm/lib/Target/BPF/BPFBTFDebug.h | 6 +
4 files changed, 337 insertions(+), 50 deletions(-)
diff --git a/llvm/include/llvm/CodeGen/BTFDebug.h b/llvm/include/llvm/CodeGen/BTFDebug.h
index 367c911d2c6e42..f6f40307a13972 100644
--- a/llvm/include/llvm/CodeGen/BTFDebug.h
+++ b/llvm/include/llvm/CodeGen/BTFDebug.h
@@ -16,6 +16,8 @@
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/CodeGen/DebugHandlerBase.h"
#include "llvm/DebugInfo/BTF/BTF.h"
@@ -254,10 +256,8 @@ class BTFTypeTypeTag : public BTFTypeBase {
class BTFStringTable {
/// String table size in bytes.
uint32_t Size;
- /// A mapping from string table offset to the index
- /// of the Table. It is used to avoid putting
- /// duplicated strings in the table.
- std::map<uint32_t, uint32_t> OffsetToIdMap;
+ /// Map from string content to its byte offset in the string table.
+ StringMap<uint32_t> StringOffsets;
/// A vector of strings to represent the string table.
std::vector<std::string> Table;
@@ -307,17 +307,22 @@ class BTFDebug : public DebugHandlerBase {
uint32_t ArrayIndexTypeId;
BTFStringTable StringTable;
std::vector<std::unique_ptr<BTFTypeBase>> TypeEntries;
+ size_t NumCompletedTypes = 0;
DenseMap<const DIType *, uint32_t> DIToIdMap;
+ DenseSet<const DIType *> UnrepresentableTypes;
std::map<uint32_t, std::vector<BTFFuncInfo>> FuncInfoTable;
std::map<uint32_t, std::vector<BTFLineInfo>> LineInfoTable;
std::map<uint32_t, std::vector<BTFFieldReloc>> FieldRelocTable;
StringMap<std::vector<std::string>> FileContent;
std::map<std::string, std::unique_ptr<BTFKindDataSec>, std::less<>>
DataSecEntries;
- std::vector<BTFTypeStruct *> StructTypes;
- std::map<const DICompositeType *,
- std::vector<std::pair<const DIDerivedType *, BTFTypeDerived *>>>
- FixupDerivedTypes;
+ DenseSet<const DICompileUnit *> ProcessedCUs;
+ DenseSet<const DISubprogram *> ProcessedSubprograms;
+ DenseSet<const DICompositeType *> RepresentableRecords;
+ DenseMap<const MDString *, uint32_t> ODRRecordIds;
+ using DerivedTypeFixups =
+ std::vector<std::pair<const DIDerivedType *, BTFTypeDerived *>>;
+ MapVector<const DICompositeType *, DerivedTypeFixups> FixupDerivedTypes;
std::set<const Function *> ProtoFunctions;
/// Add types to TypeEntries.
@@ -347,6 +352,7 @@ class BTFDebug : public DebugHandlerBase {
void visitEnumType(const DICompositeType *ETy, uint32_t &TypeId);
void visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
bool CheckPointer, bool SeenPointer);
+ bool isRepresentableValueType(const DIType *Ty);
/// @}
/// Check whether the type is a forward declaration candidate or not.
@@ -368,6 +374,14 @@ class BTFDebug : public DebugHandlerBase {
/// Whether to collect and emit .BTF.ext (FuncInfo, LineInfo, FieldReloc).
virtual bool shouldEmitBTFExt() const { return false; }
+ /// Whether to prune unreferenced CU/local types and pointer-only struct
+ /// pointees into forward declarations (matching GCC -gprune-btf).
+ virtual bool shouldPruneBTF() const { return false; }
+
+ /// Whether unrepresentable array dimensions/elements should emit a backend
+ /// diagnostic rather than omitting the unrepresentable type.
+ virtual bool diagnoseUnsupportedArrays() const { return false; }
+
/// Generate types and variables for globals.
virtual void processGlobals();
@@ -378,6 +392,9 @@ class BTFDebug : public DebugHandlerBase {
/// Generate types for function prototypes.
void processFuncPrototypes(const Function *);
+ void processCompileUnitTypes(const DICompileUnit *Unit);
+ void processRetainedNodes(const DISubprogram *SP);
+
/// Generate types for decl annotations.
void processDeclAnnotations(DINodeArray Annotations, uint32_t BaseTypeId,
int ComponentId);
@@ -434,10 +451,10 @@ class BTFDebug : public DebugHandlerBase {
/// Get the type id for a particular DIType.
uint32_t getTypeId(const DIType *Ty) {
- assert(Ty && "Invalid null Type");
- assert(DIToIdMap.find(Ty) != DIToIdMap.end() &&
- "DIType not added in the BDIToIdMap");
- return DIToIdMap[Ty];
+ auto It = DIToIdMap.find(Ty);
+ assert((It != DIToIdMap.end() || UnrepresentableTypes.contains(Ty)) &&
+ "DIType not added");
+ return It == DIToIdMap.end() ? 0 : It->second;
}
/// Called at the beginning of instruction processing, before line info.
diff --git a/llvm/include/llvm/CodeGen/BTFUtils.h b/llvm/include/llvm/CodeGen/BTFUtils.h
index 5a782d8175d028..7f1b6d7fa8a962 100644
--- a/llvm/include/llvm/CodeGen/BTFUtils.h
+++ b/llvm/include/llvm/CodeGen/BTFUtils.h
@@ -18,6 +18,7 @@ namespace llvm {
/// Return the bit offset used to order an element of a BTF structure record.
inline uint64_t getBTFRecordElementOffset(const DINode *Element) {
switch (Element->getTag()) {
+ case dwarf::DW_TAG_inheritance:
case dwarf::DW_TAG_member:
return cast<DIDerivedType>(Element)->getOffsetInBits();
case dwarf::DW_TAG_variant_part:
diff --git a/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp b/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
index 76ff1c8150f3aa..0c8d977e253a08 100644
--- a/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
@@ -21,6 +21,9 @@
#include "llvm/CodeGen/BTFUtils.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
+#include "llvm/IR/Constants.h"
+#include "llvm/IR/DebugProgramInstruction.h"
+#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCObjectFileInfo.h"
@@ -28,6 +31,7 @@
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/LineIterator.h"
+#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
@@ -358,6 +362,7 @@ void BTFTypeStruct::completeType(BTFDebug &BDebug) {
struct BTF::BTFMember BTFMember;
switch (Element->getTag()) {
+ case dwarf::DW_TAG_inheritance:
case dwarf::DW_TAG_member: {
const auto *DDTy = cast<DIDerivedType>(Element);
@@ -490,6 +495,9 @@ BTFKindVar::BTFKindVar(StringRef VarName, uint32_t TypeId, uint32_t VarInfo)
}
void BTFKindVar::completeType(BTFDebug &BDebug) {
+ if (IsCompleted)
+ return;
+ IsCompleted = true;
BTFType.NameOff = BDebug.addString(Name);
}
@@ -506,6 +514,9 @@ BTFKindDataSec::BTFKindDataSec(AsmPrinter *AsmPrt, std::string SecName)
}
void BTFKindDataSec::completeType(BTFDebug &BDebug) {
+ if (IsCompleted)
+ return;
+ IsCompleted = true;
BTFType.NameOff = BDebug.addString(Name);
BTFType.Info |= Vars.size();
}
@@ -586,14 +597,10 @@ void BTFTypeTypeTag::completeType(BTFDebug &BDebug) {
}
uint32_t BTFStringTable::addString(StringRef S) {
- // Check whether the string already exists.
- for (auto &OffsetM : OffsetToIdMap) {
- if (Table[OffsetM.second] == S)
- return OffsetM.first;
- }
- // Not find, add to the string table.
+ auto [It, Inserted] = StringOffsets.try_emplace(S, Size);
+ if (!Inserted)
+ return It->second;
uint32_t Offset = Size;
- OffsetToIdMap[Offset] = Table.size();
Table.push_back(std::string(S));
Size += S.size() + 1;
return Offset;
@@ -621,8 +628,22 @@ uint32_t BTFDebug::addType(std::unique_ptr<BTFTypeBase> TypeEntry) {
return Id;
}
+static bool isSupportedComplexSize(const DIBasicType *Ty) {
+ switch (divideCeil(Ty->getSizeInBits(), 8)) {
+ case 2:
+ case 4:
+ case 8:
+ case 12:
+ case 16:
+ return true;
+ default:
+ return false;
+ }
+}
+
void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
- // Only int and binary floating point types are supported in BTF.
+ // Only int (<= 128 bits), binary float, and supported complex float types
+ // are representable in BTF.
uint32_t Encoding = BTy->getEncoding();
std::unique_ptr<BTFTypeBase> TypeEntry;
switch (Encoding) {
@@ -632,31 +653,78 @@ void BTFDebug::visitBasicType(const DIBasicType *BTy, uint32_t &TypeId) {
case dwarf::DW_ATE_unsigned:
case dwarf::DW_ATE_unsigned_char:
case dwarf::DW_ATE_UTF:
+ if (BTy->getSizeInBits() > 128) {
+ UnrepresentableTypes.insert(BTy);
+ return;
+ }
// Create a BTF type instance for this DIBasicType and put it into
// DIToIdMap for cross-type reference check.
TypeEntry = std::make_unique<BTFTypeInt>(
Encoding, BTy->getSizeInBits(), BTy->getOffsetInBits(), BTy->getName());
break;
+ case dwarf::DW_ATE_complex_float:
+ if (!isSupportedComplexSize(BTy)) {
+ UnrepresentableTypes.insert(BTy);
+ return;
+ }
+ [[fallthrough]];
case dwarf::DW_ATE_float:
TypeEntry =
std::make_unique<BTFTypeFloat>(BTy->getSizeInBits(), BTy->getName());
break;
default:
+ UnrepresentableTypes.insert(BTy);
return;
}
TypeId = addType(std::move(TypeEntry), BTy);
}
+// Strip only by-value wrappers; a pointer to an unrepresentable type is valid.
+static const DIType *getBTFValueType(const DIType *Ty) {
+ while (const auto *DTy = dyn_cast_or_null<DIDerivedType>(Ty)) {
+ switch (DTy->getTag()) {
+ case dwarf::DW_TAG_typedef:
+ case dwarf::DW_TAG_const_type:
+ case dwarf::DW_TAG_volatile_type:
+ case dwarf::DW_TAG_restrict_type:
+ case dwarf::DW_TAG_atomic_type:
+ Ty = DTy->getBaseType();
+ break;
+ default:
+ return Ty;
+ }
+ }
+ return Ty;
+}
+
/// Handle subprogram or subroutine types.
void BTFDebug::visitSubroutineType(
const DISubroutineType *STy, bool ForSubprog,
const SmallDenseMap<uint32_t, StringRef> &FuncArgNames, uint32_t &TypeId,
bool VoidReturn) {
+ TypeId = 0;
DITypeArray Elements = STy->getTypeArray();
+ if (Elements.empty() || Elements.size() - 1 > BTF::MAX_VLEN) {
+ if (!ForSubprog)
+ UnrepresentableTypes.insert(STy);
+ return;
+ }
uint32_t VLen = Elements.size() - 1;
- if (VLen > BTF::MAX_VLEN)
+ if (!VoidReturn && Elements[0] && !isRepresentableValueType(Elements[0])) {
+ if (!ForSubprog)
+ UnrepresentableTypes.insert(STy);
return;
+ }
+ for (unsigned I = 1; I < Elements.size(); ++I) {
+ if (!Elements[I] && I + 1 == Elements.size())
+ continue; // Variadic marker.
+ if (!isRepresentableValueType(Elements[I])) {
+ if (!ForSubprog)
+ UnrepresentableTypes.insert(STy);
+ return;
+ }
+ }
// Subprogram has a valid non-zero-length name, and the pointee of
// a function pointer has an empty name. The subprogram type will
@@ -765,14 +833,127 @@ int BTFDebug::genBTFTypeTags(const DIDerivedType *DTy, int BaseTypeId) {
return TmpTypeId;
}
+static const ConstantInt *getBTFArrayCount(const DINode *Dimension) {
+ const auto *Range = dyn_cast<DISubrange>(Dimension);
+ return Range ? dyn_cast_if_present<ConstantInt *>(Range->getCount())
+ : nullptr;
+}
+
+static bool isSupportedEnumBase(const DIBasicType *Base) {
+ return Base && (Base->getSizeInBits() <= 32 || Base->getSizeInBits() == 64);
+}
+
+// Check by-value subobjects against BTF format limits before registering a
+// record. Do not follow pointers: they may refer back to the record and can
+// point to void or a forward declaration in BTF.
+bool BTFDebug::isRepresentableValueType(const DIType *Ty) {
+ Ty = getBTFValueType(Ty);
+ if (!Ty || UnrepresentableTypes.contains(Ty))
+ return false;
+ if (const auto *BTy = dyn_cast<DIBasicType>(Ty)) {
+ switch (BTy->getEncoding()) {
+ case dwarf::DW_ATE_boolean:
+ case dwarf::DW_ATE_signed:
+ case dwarf::DW_ATE_signed_char:
+ case dwarf::DW_ATE_unsigned:
+ case dwarf::DW_ATE_unsigned_char:
+ case dwarf::DW_ATE_UTF:
+ return BTy->getSizeInBits() <= 128;
+ case dwarf::DW_ATE_float:
+ return true;
+ case dwarf::DW_ATE_complex_float:
+ return isSupportedComplexSize(BTy);
+ default:
+ return false;
+ }
+ }
+ const auto *CTy = dyn_cast<DICompositeType>(Ty);
+ if (!CTy)
+ return Ty->getTag() == dwarf::DW_TAG_pointer_type;
+
+ DINodeArray Elements = CTy->getElements();
+ switch (CTy->getTag()) {
+ case dwarf::DW_TAG_array_type:
+ if (diagnoseUnsupportedArrays())
+ return true;
+ return llvm::all_of(Elements,
+ [](const DINode *Dim) {
+ const ConstantInt *Count = getBTFArrayCount(Dim);
+ return Count && (Count->isMinusOne() ||
+ Count->getValue().isIntN(32));
+ }) &&
+ isRepresentableValueType(CTy->getBaseType());
+ case dwarf::DW_TAG_enumeration_type:
+ return CTy->getSizeInBits() <= 64 && Elements.size() <= BTF::MAX_VLEN &&
+ (!CTy->getBaseType() ||
+ isSupportedEnumBase(dyn_cast_or_null<DIBasicType>(
+ getBTFValueType(CTy->getBaseType()))));
+ case dwarf::DW_TAG_class_type:
+ case dwarf::DW_TAG_structure_type:
+ case dwarf::DW_TAG_union_type:
+ case dwarf::DW_TAG_variant_part:
+ break;
+ default:
+ return false;
+ }
+
+ if (CTy->isForwardDecl() || RepresentableRecords.contains(CTy))
+ return true;
+ unsigned VLen = 0;
+ if (const auto *D = CTy->getDiscriminator()) {
+ if (!isRepresentableValueType(D->getBaseType()))
+ return false;
+ ++VLen;
+ }
+ for (const DINode *Element : Elements) {
+ const DIType *Member;
+ switch (Element->getTag()) {
+ case dwarf::DW_TAG_inheritance:
+ if (cast<DIDerivedType>(Element)->isVirtual()) {
+ UnrepresentableTypes.insert(CTy);
+ return false;
+ }
+ [[fallthrough]];
+ case dwarf::DW_TAG_member:
+ if (cast<DIDerivedType>(Element)->isStaticMember())
+ continue;
+ Member = cast<DIDerivedType>(Element)->getBaseType();
+ break;
+ case dwarf::DW_TAG_variant_part:
+ Member = cast<DICompositeType>(Element);
+ break;
+ default:
+ continue;
+ }
+ if (++VLen > BTF::MAX_VLEN || !isRepresentableValueType(Member)) {
+ UnrepresentableTypes.insert(CTy);
+ return false;
+ }
+ }
+ RepresentableRecords.insert(CTy);
+ return true;
+}
+
/// Handle structure/union types.
void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
uint32_t &TypeId) {
+ if (!isRepresentableValueType(CTy)) {
+ UnrepresentableTypes.insert(CTy);
+ return;
+ }
DINodeArray DIElements = CTy->getElements();
SmallVector<const DINode *, 8> Elements(DIElements.begin(), DIElements.end());
+ llvm::erase_if(Elements, [](const DINode *Element) {
+ if (Element->getTag() == dwarf::DW_TAG_member &&
+ cast<DIDerivedType>(Element)->isStaticMember())
+ return true;
+ return Element->getTag() != dwarf::DW_TAG_member &&
+ Element->getTag() != dwarf::DW_TAG_variant_part &&
+ Element->getTag() != dwarf::DW_TAG_inheritance;
+ });
// Structure elements must have nondecreasing offsets in BTF. Preserve DI
// order for union and variant-part records.
- if (CTy->getTag() == dwarf::DW_TAG_structure_type)
+ if (IsStruct)
llvm::stable_sort(Elements, [](const DINode *LHS, const DINode *RHS) {
return getBTFRecordElementOffset(LHS) < getBTFRecordElementOffset(RHS);
});
@@ -787,8 +968,10 @@ void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
VLen++;
}
}
- if (VLen > BTF::MAX_VLEN)
+ if (VLen > BTF::MAX_VLEN) {
+ UnrepresentableTypes.insert(CTy);
return;
+ }
// Check whether we have any bitfield members or not
bool HasBitField = false;
@@ -804,8 +987,9 @@ void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
auto TypeEntry = std::make_unique<BTFTypeStruct>(CTy, Elements, IsStruct,
HasBitField, VLen);
- StructTypes.push_back(TypeEntry.get());
TypeId = addType(std::move(TypeEntry), CTy);
+ if (const auto *Identifier = CTy->getRawIdentifier())
+ ODRRecordIds.try_emplace(Identifier, TypeId);
// Check struct/union annotations
processDeclAnnotations(CTy->getAnnotations(), TypeId, -1);
@@ -814,6 +998,11 @@ void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
int FieldNo = 0;
for (const auto *Element : Elements) {
switch (Element->getTag()) {
+ case dwarf::DW_TAG_inheritance: {
+ const auto *Elem = cast<DIDerivedType>(Element);
+ visitTypeEntry(Elem->getBaseType());
+ break;
+ }
case dwarf::DW_TAG_member: {
const auto Elem = cast<DIDerivedType>(Element);
visitTypeEntry(Elem);
@@ -836,9 +1025,7 @@ void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
// After a diagnostic, use a placeholder length so enclosing types can still
// refer to the array during error recovery.
static uint32_t getBTFArrayLength(const DINode *Dimension, MCContext &Ctx) {
- const auto *Range = dyn_cast<DISubrange>(Dimension);
- const auto *Count =
- Range ? dyn_cast_if_present<ConstantInt *>(Range->getCount()) : nullptr;
+ const auto *Count = getBTFArrayCount(Dimension);
if (!Count) {
Ctx.reportError({},
"BTF array dimension requires a constant element count");
@@ -855,11 +1042,20 @@ static uint32_t getBTFArrayLength(const DINode *Dimension, MCContext &Ctx) {
}
void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
+ if (!diagnoseUnsupportedArrays() && !isRepresentableValueType(CTy)) {
+ UnrepresentableTypes.insert(CTy);
+ return;
+ }
+
// Visit array element type.
uint32_t ElemTypeId = 0;
const DIType *ElemType = tryRemoveAtomicType(CTy->getBaseType());
visitTypeEntry(ElemType, ElemTypeId, false, false);
if (!ElemTypeId) {
+ if (!diagnoseUnsupportedArrays()) {
+ UnrepresentableTypes.insert(CTy);
+ return;
+ }
SmallString<128> Message;
raw_svector_ostream Err(Message);
Err << "unsupported BTF array element type";
@@ -893,15 +1089,21 @@ void BTFDebug::visitArrayType(const DICompositeType *CTy, uint32_t &TypeId) {
void BTFDebug::visitEnumType(const DICompositeType *CTy, uint32_t &TypeId) {
DINodeArray Elements = CTy->getElements();
uint32_t VLen = Elements.size();
- if (VLen > BTF::MAX_VLEN)
+ if (VLen > BTF::MAX_VLEN || CTy->getSizeInBits() > 64) {
+ UnrepresentableTypes.insert(CTy);
return;
+ }
bool IsSigned = false;
unsigned NumBits = 32;
// No BaseType implies forward declaration in which case a
// BTFTypeEnum with Vlen = 0 is emitted.
- if (CTy->getBaseType() != nullptr) {
- const auto *BTy = cast<DIBasicType>(CTy->getBaseType());
+ if (const DIType *Base = CTy->getBaseType()) {
+ const auto *BTy = dyn_cast_or_null<DIBasicType>(getBTFValueType(Base));
+ if (!isSupportedEnumBase(BTy)) {
+ UnrepresentableTypes.insert(CTy);
+ return;
+ }
IsSigned = BTy->getEncoding() == dwarf::DW_ATE_signed ||
BTy->getEncoding() == dwarf::DW_ATE_signed_char;
NumBits = BTy->getSizeInBits();
@@ -930,6 +1132,7 @@ void BTFDebug::visitCompositeType(const DICompositeType *CTy,
uint32_t &TypeId) {
auto Tag = CTy->getTag();
switch (Tag) {
+ case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
case dwarf::DW_TAG_variant_part:
@@ -937,7 +1140,10 @@ void BTFDebug::visitCompositeType(const DICompositeType *CTy,
if (CTy->isForwardDecl())
visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
else
- visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
+ visitStructType(CTy,
+ Tag == dwarf::DW_TAG_structure_type ||
+ Tag == dwarf::DW_TAG_class_type,
+ TypeId);
break;
case dwarf::DW_TAG_array_type:
visitArrayType(CTy, TypeId);
@@ -946,7 +1152,8 @@ void BTFDebug::visitCompositeType(const DICompositeType *CTy,
visitEnumType(CTy, TypeId);
break;
default:
- llvm_unreachable("Unexpected DI tag of a composite type");
+ UnrepresentableTypes.insert(CTy);
+ break;
}
}
@@ -954,6 +1161,7 @@ bool BTFDebug::IsForwardDeclCandidate(const DIType *Base) {
if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
auto CTag = CTy->getTag();
if ((CTag == dwarf::DW_TAG_structure_type ||
+ CTag == dwarf::DW_TAG_class_type ||
CTag == dwarf::DW_TAG_union_type) &&
!CTy->getName().empty() && !CTy->isForwardDecl())
return true;
@@ -1010,6 +1218,7 @@ void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
TypeId = addType(std::move(TypeEntry), DTy);
} else if (Tag != dwarf::DW_TAG_member) {
+ UnrepresentableTypes.insert(DTy);
return;
}
@@ -1031,6 +1240,7 @@ void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
/// will be generated.
void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
bool CheckPointer, bool SeenPointer) {
+ TypeId = 0;
if (!Ty || DIToIdMap.find(Ty) != DIToIdMap.end()) {
TypeId = DIToIdMap[Ty];
@@ -1100,7 +1310,7 @@ void BTFDebug::visitTypeEntry(const DIType *Ty, uint32_t &TypeId,
else if (const auto *DTy = dyn_cast<DIDerivedType>(Ty))
visitDerivedType(DTy, TypeId, CheckPointer, SeenPointer);
else
- llvm_unreachable("Unknown DIType");
+ UnrepresentableTypes.insert(Ty);
}
void BTFDebug::visitTypeEntry(const DIType *Ty) {
@@ -1310,6 +1520,26 @@ void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
}
SkipInstruction = false;
+ if (!shouldPruneBTF()) {
+ processCompileUnitTypes(Unit);
+ processRetainedNodes(SP);
+ auto ProcessLocation = [this](const DILocation *Loc) {
+ for (; Loc; Loc = Loc->getInlinedAt())
+ processRetainedNodes(Loc->getScope()->getSubprogram());
+ };
+ for (const BasicBlock &BB : MF->getFunction())
+ for (const Instruction &I : BB) {
+ ProcessLocation(I.getDebugLoc().get());
+ if (const auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
+ visitTypeEntry(DVI->getVariable()->getType());
+ for (const DbgRecord &DR : I.getDbgRecordRange()) {
+ ProcessLocation(DR.getDebugLoc().get());
+ if (const auto *DVR = dyn_cast<DbgVariableRecord>(&DR))
+ visitTypeEntry(DVR->getVariable()->getType());
+ }
+ }
+ }
+
// Collect all types locally referenced in this function.
// Use RetainedNodes so we can collect all argument names
// even if the argument is not used.
@@ -1327,8 +1557,8 @@ void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
uint32_t FuncTypeId = processFunctionType(MF, SP, FuncArgNames);
- for (const auto &TypeEntry : TypeEntries)
- TypeEntry->completeType(*this);
+ for (; NumCompletedTypes < TypeEntries.size(); ++NumCompletedTypes)
+ TypeEntries[NumCompletedTypes]->completeType(*this);
if (!shouldEmitBTFExt())
return;
@@ -1370,8 +1600,8 @@ void BTFDebug::endFunctionImpl(const MachineFunction *MF) {
unsigned BTFDebug::populateType(const DIType *Ty) {
unsigned Id;
visitTypeEntry(Ty, Id, false, false);
- for (const auto &TypeEntry : TypeEntries)
- TypeEntry->completeType(*this);
+ for (; NumCompletedTypes < TypeEntries.size(); ++NumCompletedTypes)
+ TypeEntries[NumCompletedTypes]->completeType(*this);
return Id;
}
@@ -1486,9 +1716,13 @@ void BTFDebug::processGlobals() {
for (auto *GVE : GVs) {
DIGlobal = GVE->getVariable();
const DIType *Ty = tryRemoveAtomicType(DIGlobal->getType());
+ if (!isRepresentableValueType(Ty))
+ break;
visitTypeEntry(Ty, GVTypeId, false, false);
break;
}
+ if (!GVTypeId)
+ continue;
// Only support the following globals:
// . static variables
@@ -1591,34 +1825,63 @@ void BTFDebug::processFuncPrototypes(const Function *F) {
}
}
+void BTFDebug::processCompileUnitTypes(const DICompileUnit *Unit) {
+ if (!Unit || !ProcessedCUs.insert(Unit).second)
+ return;
+ for (const DICompositeType *EnumTy : Unit->getEnumTypes())
+ visitTypeEntry(EnumTy);
+ for (const DIScope *Scope : Unit->getRetainedTypes())
+ if (const auto *Ty = dyn_cast<DIType>(Scope))
+ visitTypeEntry(Ty);
+}
+
+void BTFDebug::processRetainedNodes(const DISubprogram *SP) {
+ if (!SP || !ProcessedSubprograms.insert(SP).second)
+ return;
+ for (const MDNode *DN : SP->getRetainedNodes())
+ if (const auto *DV = dyn_cast<DILocalVariable>(DN))
+ visitTypeEntry(DV->getType());
+ else if (const auto *Ty = dyn_cast<DIType>(DN))
+ visitTypeEntry(Ty);
+}
+
void BTFDebug::endModule() {
+ bool PruneBTF = shouldPruneBTF();
+ if (!PruneBTF)
+ for (const DICompileUnit *Unit : MMI->getModule()->debug_compile_units())
+ processCompileUnitTypes(Unit);
+
// Collect global types/variables.
processGlobals();
+ // When not pruning pointees (-gno-prune-btf), iteratively emit full
+ // definitions for deferred struct/union/class pointees before resolving
+ // fixups. Unrepresentable records still fall back to FWD below.
+ if (!PruneBTF) {
+ for (size_t I = 0; I < FixupDerivedTypes.size(); ++I) {
+ const DICompositeType *CTy = (FixupDerivedTypes.begin() + I)->first;
+ visitTypeEntry(CTy);
+ }
+ }
+
for (auto &DataSec : DataSecEntries)
addType(std::move(DataSec.second));
// Fixups
- for (auto &Fixup : FixupDerivedTypes) {
- const DICompositeType *CTy = Fixup.first;
+ for (const auto &[CTy, Fixups] : FixupDerivedTypes) {
StringRef TypeName = CTy->getName();
bool IsUnion = CTy->getTag() == dwarf::DW_TAG_union_type;
- // Search through struct types
- uint32_t StructTypeId = 0;
- for (const auto &StructType : StructTypes) {
- if (StructType->getName() == TypeName) {
- StructTypeId = StructType->getId();
- break;
- }
- }
+ uint32_t StructTypeId = DIToIdMap.lookup(CTy);
+ if (!StructTypeId && CTy->getRawIdentifier())
+ StructTypeId = ODRRecordIds.lookup(CTy->getRawIdentifier());
if (StructTypeId == 0) {
auto FwdTypeEntry = std::make_unique<BTFTypeFwd>(TypeName, IsUnion);
StructTypeId = addType(std::move(FwdTypeEntry));
}
- for (auto &TypeInfo : Fixup.second) {
+ for (const auto &TypeInfo : Fixups) {
const DIDerivedType *DTy = TypeInfo.first;
BTFTypeDerived *BDType = TypeInfo.second;
@@ -1631,8 +1894,8 @@ void BTFDebug::endModule() {
}
// Complete BTF type cross references.
- for (const auto &TypeEntry : TypeEntries)
- TypeEntry->completeType(*this);
+ for (; NumCompletedTypes < TypeEntries.size(); ++NumCompletedTypes)
+ TypeEntries[NumCompletedTypes]->completeType(*this);
// Emit BTF sections.
emitBTFSection();
diff --git a/llvm/lib/Target/BPF/BPFBTFDebug.h b/llvm/lib/Target/BPF/BPFBTFDebug.h
index 46b09f25f18919..503e369d36c01f 100644
--- a/llvm/lib/Target/BPF/BPFBTFDebug.h
+++ b/llvm/lib/Target/BPF/BPFBTFDebug.h
@@ -53,6 +53,12 @@ class BPFBTFDebug : public BTFDebug {
/// Emit .BTF.ext (FuncInfo, LineInfo, CO-RE FieldReloc) for BPF.
bool shouldEmitBTFExt() const override { return true; }
+ /// Default to pruned BTF on BPF (matching GCC -gprune-btf default on BPF).
+ bool shouldPruneBTF() const override { return true; }
+
+ /// Diagnose unrepresentable BTF array bounds/elements as backend errors.
+ bool diagnoseUnsupportedArrays() const override { return true; }
+
/// Process all globals including .maps handling.
void processGlobals() override;
>From 36f59c9f13312d5b5af393f0e5c8864d3f828984 Mon Sep 17 00:00:00 2001
From: "Can H. Tartanoglu" <gpg at rotas.mozmail.com>
Date: Sun, 6 Dec 2026 12:19:21 +0100
Subject: [PATCH 3/3] [Clang][CodeGen] Add -gbtf and -gprune-btf for non-BPF
ELF targets
Wire -gbtf, -gprune-btf, and -gno-prune-btf through the Clang driver,
LLVM IR module flags ("BTF" with Max, "BTF Prune" with Min), and
AsmPrinter:
- Match GCC 15.2 semantics: -gbtf alone emits .BTF without forcing DWARF
(-g -gbtf emits both), non-BPF targets do not emit .BTF.ext, and
pointee pruning defaults to off on non-BPF ELF and on for BPF.
- Non-ELF targets accept and ignore -gbtf; assembler invocations claim
-gbtf / -gprune-btf / -gno-prune-btf cleanly.
- Add Clang driver, CodeGen module-flag, X86 BTF, and BPF -gno-prune-btf
lit tests.
Assisted-by: Antigravity (Gemini 4 Neon)
---
clang/include/clang/Basic/DebugOptions.def | 8 +++
clang/include/clang/Options/Options.td | 12 ++++
clang/lib/CodeGen/CodeGenModule.cpp | 9 +++
clang/lib/Driver/ToolChains/Clang.cpp | 24 +++++++
clang/test/CodeGen/btf-module-flag.c | 22 ++++++
clang/test/Driver/gbtf.c | 65 +++++++++++++++++
llvm/include/llvm/CodeGen/BTFDebug.h | 5 +-
llvm/include/llvm/IR/Module.h | 6 ++
llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp | 9 ++-
llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp | 6 ++
llvm/lib/IR/Module.cpp | 14 ++++
llvm/lib/Target/BPF/BPFBTFDebug.h | 2 +-
llvm/test/CodeGen/BPF/BTF/no-prune-btf.ll | 30 ++++++++
llvm/test/CodeGen/X86/BTF/anonymous-enum.ll | 45 ++++++++++++
llvm/test/CodeGen/X86/BTF/btf-with-dwarf.ll | 34 +++++++++
.../test/CodeGen/X86/BTF/btf-without-dwarf.ll | 27 +++++++
.../CodeGen/X86/BTF/deferred-pointee-order.ll | 30 ++++++++
llvm/test/CodeGen/X86/BTF/deferred-pointee.ll | 51 ++++++++++++++
.../X86/BTF/deferred-unrepresentable.ll | 22 ++++++
llvm/test/CodeGen/X86/BTF/empty-prototype.ll | 19 +++++
llvm/test/CodeGen/X86/BTF/enum.ll | 59 ++++++++++++++++
llvm/test/CodeGen/X86/BTF/func.ll | 47 +++++++++++++
llvm/test/CodeGen/X86/BTF/global-var.ll | 60 ++++++++++++++++
llvm/test/CodeGen/X86/BTF/inheritance.ll | 46 ++++++++++++
llvm/test/CodeGen/X86/BTF/inlined-retained.ll | 38 ++++++++++
llvm/test/CodeGen/X86/BTF/int.ll | 42 +++++++++++
.../CodeGen/X86/BTF/local-enum-underlying.ll | 39 +++++++++++
llvm/test/CodeGen/X86/BTF/local-var-type.ll | 53 ++++++++++++++
.../CodeGen/X86/BTF/local-virtual-member.ll | 30 ++++++++
llvm/test/CodeGen/X86/BTF/local-vla.ll | 28 ++++++++
llvm/test/CodeGen/X86/BTF/maps-global.ll | 17 +++++
llvm/test/CodeGen/X86/BTF/no-btf-flag.ll | 28 ++++++++
llvm/test/CodeGen/X86/BTF/static-member.ll | 19 +++++
llvm/test/CodeGen/X86/BTF/struct-method.ll | 51 ++++++++++++++
llvm/test/CodeGen/X86/BTF/struct.ll | 70 +++++++++++++++++++
.../test/CodeGen/X86/BTF/unsupported-types.ll | 59 ++++++++++++++++
llvm/test/CodeGen/X86/BTF/wide-integer.ll | 22 ++++++
llvm/test/CodeGen/X86/BTF/wide-opaque-enum.ll | 22 ++++++
38 files changed, 1167 insertions(+), 3 deletions(-)
create mode 100644 clang/test/CodeGen/btf-module-flag.c
create mode 100644 clang/test/Driver/gbtf.c
create mode 100644 llvm/test/CodeGen/BPF/BTF/no-prune-btf.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/anonymous-enum.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/btf-with-dwarf.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/btf-without-dwarf.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/deferred-pointee-order.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/deferred-pointee.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/deferred-unrepresentable.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/empty-prototype.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/enum.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/func.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/global-var.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/inheritance.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/inlined-retained.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/int.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/local-enum-underlying.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/local-var-type.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/local-virtual-member.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/local-vla.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/maps-global.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/no-btf-flag.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/static-member.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/struct-method.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/struct.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/unsupported-types.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/wide-integer.ll
create mode 100644 llvm/test/CodeGen/X86/BTF/wide-opaque-enum.ll
diff --git a/clang/include/clang/Basic/DebugOptions.def b/clang/include/clang/Basic/DebugOptions.def
index 7774514f87e858..fbd6d30a2a800e 100644
--- a/clang/include/clang/Basic/DebugOptions.def
+++ b/clang/include/clang/Basic/DebugOptions.def
@@ -127,6 +127,14 @@ VALUE_DEBUGOPT(DwarfVersion, 3, 0, Compatible)
/// CodeView and DWARF into the same object.
DEBUGOPT(EmitCodeView, 1, 0, Compatible)
+/// Whether we should emit BTF debug information. BTF can stand alone or
+/// coexist with DWARF.
+DEBUGOPT(EmitBTF, 1, 0, Compatible)
+
+/// Explicit BTF pruning policy overrides (-gprune-btf / -gno-prune-btf).
+DEBUGOPT(BTFPrune, 1, 0, Compatible)
+DEBUGOPT(BTFNoPrune, 1, 0, Compatible)
+
/// Whether to emit the .debug$H section containing hashes of CodeView types.
DEBUGOPT(CodeViewGHash, 1, 0, Compatible)
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index f714c8913d7b7c..af5f3306bc6189 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -5382,6 +5382,18 @@ def gcodeview : Flag<["-"], "gcodeview">, Group<g_Group>,
HelpText<"Generate CodeView debug information">,
Visibility<[ClangOption, CC1Option, CC1AsOption, CLOption, DXCOption]>,
MarshallingInfoFlag<CodeGenOpts<"EmitCodeView">>;
+def gbtf : Flag<["-"], "gbtf">,
+ HelpText<"Generate BTF debug information">,
+ Visibility<[ClangOption, CC1Option, CC1AsOption]>,
+ MarshallingInfoFlag<CodeGenOpts<"EmitBTF">>;
+def gprune_btf : Flag<["-"], "gprune-btf">, Group<g_flags_Group>,
+ HelpText<"Prune unreferenced struct/union definitions in BTF">,
+ Visibility<[ClangOption, CC1Option, CC1AsOption]>,
+ MarshallingInfoFlag<CodeGenOpts<"BTFPrune">>;
+def gno_prune_btf : Flag<["-"], "gno-prune-btf">, Group<g_flags_Group>,
+ HelpText<"Emit full definitions for referenced struct/union pointees in BTF">,
+ Visibility<[ClangOption, CC1Option, CC1AsOption]>,
+ MarshallingInfoFlag<CodeGenOpts<"BTFNoPrune">>;
defm codeview_ghash : BoolOption<"g", "codeview-ghash",
CodeGenOpts<"CodeViewGHash">, DefaultFalse,
PosFlag<SetTrue, [], [ClangOption, CC1Option],
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 6fe83a03e54c23..5cf7fed97e5a0a 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1432,6 +1432,15 @@ void CodeGenModule::Release() {
// Indicate that we want CodeView in the metadata.
getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
}
+ if (CodeGenOpts.EmitBTF) {
+ // Indicate that we want BTF debug info in the metadata.
+ getModule().addModuleFlag(llvm::Module::Max, "BTF", 1);
+ }
+ if (CodeGenOpts.BTFNoPrune) {
+ getModule().addModuleFlag(llvm::Module::Min, "BTF Prune", 0);
+ } else if (CodeGenOpts.BTFPrune) {
+ getModule().addModuleFlag(llvm::Module::Min, "BTF Prune", 1);
+ }
if (CodeGenOpts.CodeViewGHash) {
getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
}
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index 399e9100e94e8b..9d05ee7105222e 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4877,6 +4877,16 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
+ // -gbtf on ELF targets enables IR debug metadata without forcing DWARF
+ // emission (matching GCC, where -gbtf alone emits .BTF and -g -gbtf emits
+ // both).
+ bool EmitBTF = false;
+ if (const Arg *A = Args.getLastArg(options::OPT_gbtf))
+ EmitBTF = TC.getTriple().isOSBinFormatELF() &&
+ checkDebugInfoOption(A, Args, D, TC);
+ if (EmitBTF && DebugInfoKind == llvm::codegenoptions::NoDebugInfo)
+ DebugInfoKind = llvm::codegenoptions::LimitedDebugInfo;
+
// strict DWARF is set to false by default. But for DBX, we need it to be set
// as true by default.
if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
@@ -5020,6 +5030,17 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
options::OPT_gno_codeview_command_line);
}
+ if (EmitBTF)
+ CmdArgs.push_back("-gbtf");
+
+ if (const Arg *A = Args.getLastArg(options::OPT_gprune_btf,
+ options::OPT_gno_prune_btf)) {
+ if ((EmitBTF || T.isBPF()) && checkDebugInfoOption(A, Args, D, TC))
+ CmdArgs.push_back(A->getOption().matches(options::OPT_gprune_btf)
+ ? "-gprune-btf"
+ : "-gno-prune-btf");
+ }
+
Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
options::OPT_gno_inline_line_tables);
@@ -9439,6 +9460,9 @@ void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
// Forward -g and handle debug info related flags, assuming we are dealing
// with an actual assembly file.
bool WantDebug = false;
+ Args.ClaimAllArgs(options::OPT_gbtf);
+ Args.ClaimAllArgs(options::OPT_gprune_btf);
+ Args.ClaimAllArgs(options::OPT_gno_prune_btf);
Args.ClaimAllArgs(options::OPT_g_Group);
if (Arg *A = Args.getLastArg(options::OPT_g_Group))
WantDebug = !A->getOption().matches(options::OPT_g0) &&
diff --git a/clang/test/CodeGen/btf-module-flag.c b/clang/test/CodeGen/btf-module-flag.c
new file mode 100644
index 00000000000000..e6d6309231cd53
--- /dev/null
+++ b/clang/test/CodeGen/btf-module-flag.c
@@ -0,0 +1,22 @@
+// Verify that -gbtf and -gprune-btf/-gno-prune-btf set the expected module
+// flags in LLVM IR.
+//
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -gbtf -debug-info-kind=limited -emit-llvm -o - %s \
+// RUN: | FileCheck %s --check-prefix=BTF
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -gbtf -gprune-btf -debug-info-kind=limited -emit-llvm -o - %s \
+// RUN: | FileCheck %s --check-prefix=BTF-PRUNE
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -gbtf -gno-prune-btf -debug-info-kind=limited -emit-llvm -o - %s \
+// RUN: | FileCheck %s --check-prefix=BTF-NOPRUNE
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -debug-info-kind=limited -emit-llvm -o - %s \
+// RUN: | FileCheck %s --check-prefix=NO-BTF
+
+// BTF-DAG: !{i32 7, !"BTF", i32 1}
+// BTF-NOT: !"BTF Prune"
+// BTF-NOT: !"Dwarf Version"
+// BTF-PRUNE-DAG: !{i32 7, !"BTF", i32 1}
+// BTF-PRUNE-DAG: !{i32 8, !"BTF Prune", i32 1}
+// BTF-NOPRUNE-DAG: !{i32 7, !"BTF", i32 1}
+// BTF-NOPRUNE-DAG: !{i32 8, !"BTF Prune", i32 0}
+// NO-BTF-NOT: !"BTF"
+
+int main(void) { return 0; }
diff --git a/clang/test/Driver/gbtf.c b/clang/test/Driver/gbtf.c
new file mode 100644
index 00000000000000..6f6979bbc99dbb
--- /dev/null
+++ b/clang/test/Driver/gbtf.c
@@ -0,0 +1,65 @@
+// Test the -gbtf and -gprune-btf/-gno-prune-btf flags in the Clang driver.
+// Claimed and ignored for assembler input.
+// RUN: %clang --target=x86_64-pc-windows-msvc -gbtf -gprune-btf -x assembler -c -### /dev/null 2>&1 \
+// RUN: | FileCheck -check-prefix=ASM %s
+// RUN: %clang --target=x86_64-linux-gnu -gbtf -gno-prune-btf -x assembler -c -### /dev/null 2>&1 \
+// RUN: | FileCheck -check-prefix=ASM %s
+// ASM: "-cc1as"
+// ASM-NOT: warning: argument unused
+// ASM-NOT: -debug-info-kind
+//
+// -gbtf alone on ELF enables BTF and IR debug metadata without forcing DWARF.
+// RUN: %clang --target=x86_64-linux-gnu -gbtf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=BTF-ONLY %s
+// RUN: %clang --target=aarch64-linux-gnu -gbtf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=BTF-ONLY %s
+// RUN: %clang --target=x86_64-linux-gnu -gbtf -g0 -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=BTF-ONLY %s
+// RUN: %clang --target=x86_64-linux-gnu -g0 -gbtf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=BTF-ONLY %s
+//
+// -g -gbtf emits both DWARF and BTF.
+// RUN: %clang --target=x86_64-linux-gnu -g -gbtf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=BTF-DWARF %s
+//
+// Non-ELF targets ignore -gbtf.
+// RUN: %clang --target=x86_64-pc-windows-msvc -g -gbtf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=WINDOWS %s
+// RUN: %clang --target=x86_64-pc-windows-msvc -gbtf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=WINDOWS-NODEBUG %s
+// RUN: %clang --target=x86_64-apple-darwin -gbtf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=DARWIN %s
+//
+// Without -gbtf, no -gbtf in cc1 args.
+// RUN: %clang --target=x86_64-linux-gnu -g -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=NO-BTF %s
+//
+// -gprune-btf / -gno-prune-btf forwarding (last wins; works on ELF and BPF).
+// RUN: %clang --target=x86_64-linux-gnu -gbtf -gprune-btf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=PRUNE %s
+// RUN: %clang --target=x86_64-linux-gnu -gbtf -gprune-btf -gno-prune-btf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=NO-PRUNE %s
+// RUN: %clang --target=bpf -g -gno-prune-btf -### %s 2>&1 \
+// RUN: | FileCheck -check-prefix=NO-PRUNE %s
+
+// BTF-ONLY: "-gbtf"
+// BTF-ONLY: "-debug-info-kind=limited"
+// BTF-ONLY-NOT: "-dwarf-version=
+// BTF-ONLY-NOT: "-gprune-btf"
+// BTF-ONLY-NOT: "-gno-prune-btf"
+// BTF-DWARF: "-gbtf"
+// BTF-DWARF: "-dwarf-version=
+// NO-BTF-NOT: "-gbtf"
+// WINDOWS-NOT: "-gbtf"
+// WINDOWS: "-gcodeview"
+// WINDOWS-NOT: "-gbtf"
+// WINDOWS-NODEBUG-NOT: "-gbtf"
+// WINDOWS-NODEBUG-NOT: "-debug-info-kind=
+// WINDOWS-NODEBUG-NOT: "-debug"
+// DARWIN-NOT: dsymutil
+// PRUNE: "-gprune-btf"
+// PRUNE-NOT: "-gno-prune-btf"
+// NO-PRUNE: "-gno-prune-btf"
+// NO-PRUNE-NOT: "-gprune-btf"
+
+int main(void) { return 0; }
diff --git a/llvm/include/llvm/CodeGen/BTFDebug.h b/llvm/include/llvm/CodeGen/BTFDebug.h
index f6f40307a13972..6afc018bea4785 100644
--- a/llvm/include/llvm/CodeGen/BTFDebug.h
+++ b/llvm/include/llvm/CodeGen/BTFDebug.h
@@ -374,9 +374,12 @@ class BTFDebug : public DebugHandlerBase {
/// Whether to collect and emit .BTF.ext (FuncInfo, LineInfo, FieldReloc).
virtual bool shouldEmitBTFExt() const { return false; }
+ /// Default BTF pruning policy when the "BTF Prune" module flag is absent.
+ virtual bool defaultPruneBTF() const { return false; }
+
/// Whether to prune unreferenced CU/local types and pointer-only struct
/// pointees into forward declarations (matching GCC -gprune-btf).
- virtual bool shouldPruneBTF() const { return false; }
+ bool shouldPruneBTF() const;
/// Whether unrepresentable array dimensions/elements should emit a backend
/// diagnostic rather than omitting the unrepresentable type.
diff --git a/llvm/include/llvm/IR/Module.h b/llvm/include/llvm/IR/Module.h
index 2b2c874f58d982..f2e6c0d7112d75 100644
--- a/llvm/include/llvm/IR/Module.h
+++ b/llvm/include/llvm/IR/Module.h
@@ -1039,6 +1039,12 @@ class LLVM_ABI Module {
/// Returns zero if not present in module.
unsigned getCodeViewFlag() const;
+ /// Returns true if BTF debug info emission is requested via module flags.
+ bool getBTFFlag() const;
+
+ /// Returns the BTF pruning policy module flag if explicitly set.
+ std::optional<bool> getBTFPruneFlag() const;
+
/// @}
/// @name Utility functions for querying and setting PIC level
/// @{
diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index 5e8349dc4850a5..34887354556d90 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -37,6 +37,7 @@
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/CodeGen/AsmPrinterAnalysis.h"
+#include "llvm/CodeGen/BTFDebug.h"
#include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
#include "llvm/CodeGen/GCMetadata.h"
#include "llvm/CodeGen/GCMetadataPrinter.h"
@@ -623,18 +624,24 @@ bool AsmPrinter::doInitialization(Module &M) {
if (MAI.doesSupportDebugInformation()) {
bool EmitCodeView = M.getCodeViewFlag();
+ bool EmitBTF = M.getBTFFlag() && Target.isOSBinFormatELF();
// On Windows and UEFI targets, emit minimal CodeView compiler info even
// when debug info is disabled. UEFI follows the MSVC toolchain
// conventions, so it is treated the same way as Windows here.
if ((Target.isOSWindows() || Target.isUEFI()) &&
M.getNamedMetadata("llvm.dbg.cu"))
Handlers.push_back(std::make_unique<CodeViewDebug>(this));
- if (!EmitCodeView || M.getDwarfVersion()) {
+ if ((!EmitCodeView && !EmitBTF) || M.getDwarfVersion()) {
if (hasDebugInfo()) {
DD = createDwarfDebug();
Handlers.push_back(std::unique_ptr<DwarfDebug>(DD));
}
}
+ // Emit BTF debug info if requested (via -gbtf) on ELF targets. BTF can
+ // stand alone or coexist with DWARF. BPF handles BTF through BPFAsmPrinter
+ // and BPFBTFDebug.
+ if (EmitBTF && !Target.isBPF() && hasDebugInfo())
+ Handlers.push_back(std::make_unique<BTFDebug>(this));
}
if (M.getNamedMetadata(PseudoProbeDescMetadataName))
diff --git a/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp b/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
index 0c8d977e253a08..2a8d753dc1116f 100644
--- a/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
@@ -1510,6 +1510,12 @@ void BTFDebug::emitBTFExtSection() {
}
}
+bool BTFDebug::shouldPruneBTF() const {
+ if (std::optional<bool> Flag = MMI->getModule()->getBTFPruneFlag())
+ return *Flag;
+ return defaultPruneBTF();
+}
+
void BTFDebug::beginFunctionImpl(const MachineFunction *MF) {
auto *SP = MF->getFunction().getSubprogram();
auto *Unit = SP->getUnit();
diff --git a/llvm/lib/IR/Module.cpp b/llvm/lib/IR/Module.cpp
index 49b4686060e86d..731c340731ef57 100644
--- a/llvm/lib/IR/Module.cpp
+++ b/llvm/lib/IR/Module.cpp
@@ -640,6 +640,20 @@ unsigned Module::getCodeViewFlag() const {
return cast<ConstantInt>(Val->getValue())->getZExtValue();
}
+bool Module::getBTFFlag() const {
+ auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("BTF"));
+ if (!Val)
+ return false;
+ return cast<ConstantInt>(Val->getValue())->getZExtValue() != 0;
+}
+
+std::optional<bool> Module::getBTFPruneFlag() const {
+ auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("BTF Prune"));
+ if (!Val)
+ return std::nullopt;
+ return cast<ConstantInt>(Val->getValue())->getZExtValue() != 0;
+}
+
unsigned Module::getInstructionCount() const {
unsigned NumInstrs = 0;
for (const Function &F : FunctionList)
diff --git a/llvm/lib/Target/BPF/BPFBTFDebug.h b/llvm/lib/Target/BPF/BPFBTFDebug.h
index 503e369d36c01f..cbce58250169b6 100644
--- a/llvm/lib/Target/BPF/BPFBTFDebug.h
+++ b/llvm/lib/Target/BPF/BPFBTFDebug.h
@@ -54,7 +54,7 @@ class BPFBTFDebug : public BTFDebug {
bool shouldEmitBTFExt() const override { return true; }
/// Default to pruned BTF on BPF (matching GCC -gprune-btf default on BPF).
- bool shouldPruneBTF() const override { return true; }
+ bool defaultPruneBTF() const override { return true; }
/// Diagnose unrepresentable BTF array bounds/elements as backend errors.
bool diagnoseUnsupportedArrays() const override { return true; }
diff --git a/llvm/test/CodeGen/BPF/BTF/no-prune-btf.ll b/llvm/test/CodeGen/BPF/BTF/no-prune-btf.ll
new file mode 100644
index 00000000000000..8eda5e776635d6
--- /dev/null
+++ b/llvm/test/CodeGen/BPF/BTF/no-prune-btf.ll
@@ -0,0 +1,30 @@
+; RUN: llc -mtriple=bpfel -filetype=obj %s -o %t
+; RUN: llvm-objcopy --dump-section .BTF=- %t | %python %p/print_btf.py - | FileCheck %s --check-prefix=PRUNE
+; RUN: sed -e 's/!{!10, !11}/!{!10, !11, !99}/' -e '$a !99 = !{i32 8, !"BTF Prune", i32 0}' %s \
+; RUN: | llc -mtriple=bpfel -filetype=obj -o %t.noprune
+; RUN: llvm-objcopy --dump-section .BTF=- %t.noprune | %python %p/print_btf.py - | FileCheck %s --check-prefix=NOPRUNE
+
+; Default on BPF prunes pointer-only struct pointees to FWD; explicit
+; -gno-prune-btf ("BTF Prune" = 0) emits the full pointee definition.
+; PRUNE: STRUCT 'outer' size=8 vlen=1
+; PRUNE: FWD 'inner' fwd_kind=struct
+; NOPRUNE: STRUCT 'outer' size=8 vlen=1
+; NOPRUNE: STRUCT 'inner' size=4 vlen=1
+
+define void @f(ptr %o) !dbg !4 { ret void }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!10, !11}
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !1, emissionKind: FullDebug)
+!1 = !DIFile(filename: "prune.c", directory: "/")
+!4 = distinct !DISubprogram(name: "f", scope: !1, file: !1, type: !5, unit: !0, spFlags: DISPFlagDefinition)
+!5 = !DISubroutineType(types: !{null, !6})
+!6 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !7, size: 64)
+!7 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "outer", file: !1, size: 64, elements: !{!8})
+!8 = !DIDerivedType(tag: DW_TAG_member, name: "p", scope: !7, baseType: !9, size: 64)
+!9 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !12, size: 64)
+!10 = !{i32 2, !"Debug Info Version", i32 3}
+!11 = !{i32 2, !"Dwarf Version", i32 4}
+!12 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "inner", file: !1, size: 32, elements: !{!13})
+!13 = !DIDerivedType(tag: DW_TAG_member, name: "x", scope: !12, baseType: !14, size: 32)
+!14 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
diff --git a/llvm/test/CodeGen/X86/BTF/anonymous-enum.ll b/llvm/test/CodeGen/X86/BTF/anonymous-enum.ll
new file mode 100644
index 00000000000000..a3fc7cffcd2bee
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/anonymous-enum.ll
@@ -0,0 +1,45 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck %s
+
+; Verify compile-unit-only anonymous enums are emitted on x86_64.
+;
+; Source:
+; enum { false, true };
+; void f1(void) {}
+; Compilation flag:
+; clang -target x86_64-linux-gnu -g -gbtf -S -emit-llvm t.c
+
+define dso_local void @f1() !dbg !7 {
+ ret void, !dbg !10
+}
+
+; CHECK: .section .BTF,"", at progbits
+; CHECK: # BTF_KIND_ENUM(
+; CHECK: .ascii "false"
+; CHECK: .ascii "true"
+; CHECK: .ascii "local_false"
+; CHECK: .ascii "local_true"
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5, !6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "t.c", directory: "/tmp")
+!2 = !{!11}
+!3 = !{i32 2, !"Dwarf Version", i32 4}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 4}
+!6 = !{i32 4, !"BTF", i32 1}
+!7 = distinct !DISubprogram(name: "f1", scope: !1, file: !1, line: 2, type: !8, isLocal: false, isDefinition: true, scopeLine: 2, flags: DIFlagPrototyped, isOptimized: true, unit: !0, retainedNodes: !12)
+!8 = !DISubroutineType(types: !9)
+!9 = !{null}
+!10 = !DILocation(line: 2, column: 16, scope: !7)
+!11 = !DICompositeType(tag: DW_TAG_enumeration_type, file: !1, line: 1, baseType: !13, size: 32, elements: !14)
+!12 = !{!17}
+!13 = !DIBasicType(name: "unsigned int", size: 32, encoding: DW_ATE_unsigned)
+!14 = !{!15, !16}
+!15 = !DIEnumerator(name: "false", value: 0)
+!16 = !DIEnumerator(name: "true", value: 1)
+!17 = !DICompositeType(tag: DW_TAG_enumeration_type, scope: !7, file: !1, line: 2, baseType: !13, size: 32, elements: !18)
+!18 = !{!19, !20}
+!19 = !DIEnumerator(name: "local_false", value: 0)
+!20 = !DIEnumerator(name: "local_true", value: 1)
diff --git a/llvm/test/CodeGen/X86/BTF/btf-with-dwarf.ll b/llvm/test/CodeGen/X86/BTF/btf-with-dwarf.ll
new file mode 100644
index 00000000000000..b70e62fff4172d
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/btf-with-dwarf.ll
@@ -0,0 +1,34 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck -check-prefixes=CHECK %s
+
+; Verify that BTF and DWARF coexist: both .BTF and .debug_info sections
+; are emitted when the BTF module flag is set alongside Dwarf Version,
+; while .BTF.ext is not emitted on non-BPF targets.
+;
+; Source:
+; void f1(void) {}
+; Compilation flag:
+; clang -target x86_64-linux-gnu -g -gbtf -S -emit-llvm t.c
+
+define dso_local void @f1() !dbg !7 {
+ ret void, !dbg !10
+}
+
+; Both DWARF and BTF sections must be present; .BTF.ext must not be emitted.
+; CHECK-DAG: .section .debug_info
+; CHECK-DAG: .section .BTF,"", at progbits
+; CHECK-NOT: .section .BTF.ext
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5, !6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "t.c", directory: "/tmp")
+!2 = !{}
+!3 = !{i32 2, !"Dwarf Version", i32 4}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 4}
+!6 = !{i32 7, !"BTF", i32 1}
+!7 = distinct !DISubprogram(name: "f1", scope: !1, file: !1, line: 1, type: !8, isLocal: false, isDefinition: true, scopeLine: 1, flags: DIFlagPrototyped, isOptimized: true, unit: !0, retainedNodes: !2)
+!8 = !DISubroutineType(types: !9)
+!9 = !{null}
+!10 = !DILocation(line: 1, column: 16, scope: !7)
diff --git a/llvm/test/CodeGen/X86/BTF/btf-without-dwarf.ll b/llvm/test/CodeGen/X86/BTF/btf-without-dwarf.ll
new file mode 100644
index 00000000000000..d6b2191745d6ba
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/btf-without-dwarf.ll
@@ -0,0 +1,27 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck %s
+
+; Verify that -gbtf without DWARF emits .BTF only (no .debug_info, no .BTF.ext).
+
+define dso_local void @f1() !dbg !7 {
+ ret void, !dbg !10
+}
+
+; CHECK-NOT: .section .debug_info
+; CHECK: .section .BTF,"", at progbits
+; CHECK: BTF_KIND_FUNC(id = 2)
+; CHECK-NOT: .section .debug_info
+; CHECK-NOT: .section .BTF.ext
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!4, !5, !6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "t.c", directory: "/tmp")
+!2 = !{}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 4}
+!6 = !{i32 7, !"BTF", i32 1}
+!7 = distinct !DISubprogram(name: "f1", scope: !1, file: !1, line: 1, type: !8, isLocal: false, isDefinition: true, scopeLine: 1, flags: DIFlagPrototyped, isOptimized: true, unit: !0, retainedNodes: !2)
+!8 = !DISubroutineType(types: !9)
+!9 = !{null}
+!10 = !DILocation(line: 1, column: 16, scope: !7)
diff --git a/llvm/test/CodeGen/X86/BTF/deferred-pointee-order.ll b/llvm/test/CodeGen/X86/BTF/deferred-pointee-order.ll
new file mode 100644
index 00000000000000..df8324f95dbd6a
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/deferred-pointee-order.ll
@@ -0,0 +1,30 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=obj %s -o %t
+; RUN: llvm-objcopy --dump-section .BTF=- %t | %python %p/../../BPF/BTF/print_btf.py - | FileCheck %s --check-prefix=NOPRUNE
+; RUN: sed -e 's/!{!2, !3}/!{!2, !3, !99}/' -e '$a !99 = !{i32 8, !"BTF Prune", i32 1}' %s \
+; RUN: | llc -mtriple=x86_64-linux-gnu -filetype=obj -o %t.pruned
+; RUN: llvm-objcopy --dump-section .BTF=- %t.pruned | %python %p/../../BPF/BTF/print_btf.py - | FileCheck %s --check-prefix=PRUNE
+
+; Deferred pointees are emitted in first-use order, not by metadata address:
+; as full STRUCTs by default (-gno-prune-btf) and as FWDs under -gprune-btf.
+; NOPRUNE: STRUCT 'berry' size=4 vlen=0
+; NOPRUNE-NEXT: {{.*}} STRUCT 'apple' size=4 vlen=0
+; PRUNE: FWD 'berry'
+; PRUNE-NEXT: {{.*}} FWD 'apple'
+
+define void @f(ptr %l) !dbg !4 { ret void }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3}
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !1, emissionKind: FullDebug)
+!1 = !DIFile(filename: "order.c", directory: "/")
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i32 7, !"BTF", i32 1}
+!4 = distinct !DISubprogram(name: "f", scope: !1, file: !1, type: !DISubroutineType(types: !{null, !12}), unit: !0, spFlags: DISPFlagDefinition, retainedNodes: !{!5})
+!12 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !5, size: 64)
+!5 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "local", scope: !4, size: 128, elements: !{!6, !7})
+!6 = !DIDerivedType(tag: DW_TAG_member, name: "pa", scope: !5, baseType: !8, size: 64, offset: 64)
+!7 = !DIDerivedType(tag: DW_TAG_member, name: "pb", scope: !5, baseType: !9, size: 64)
+!8 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !10, size: 64)
+!9 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !11, size: 64)
+!10 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "apple", file: !1, size: 32)
+!11 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "berry", file: !1, size: 32)
diff --git a/llvm/test/CodeGen/X86/BTF/deferred-pointee.ll b/llvm/test/CodeGen/X86/BTF/deferred-pointee.ll
new file mode 100644
index 00000000000000..14f38aea794ae5
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/deferred-pointee.ll
@@ -0,0 +1,51 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=obj %s -o %t
+; RUN: llvm-objcopy --dump-section .BTF=- %t | %python %p/../../BPF/BTF/print_btf.py - | FileCheck %s --check-prefix=NOPRUNE
+; RUN: sed -e 's/!{!2, !3}/!{!2, !3, !99}/' -e '$a !99 = !{i32 8, !"BTF Prune", i32 1}' %s \
+; RUN: | llc -mtriple=x86_64-linux-gnu -filetype=obj -o %t.pruned
+; RUN: llvm-objcopy --dump-section .BTF=- %t.pruned | %python %p/../../BPF/BTF/print_btf.py - | FileCheck %s --check-prefix=PRUNE
+
+; A pointer to a type from the first CU must never resolve to a same-named
+; definition from the second CU. With default -gno-prune-btf, CU1's own full
+; definition is emitted; with -gprune-btf, a FWD is emitted instead.
+; NOPRUNE: STRUCT 'container' size=8 vlen=1
+; NOPRUNE-NEXT: 'p' type_id=[[PTR:[0-9]+]] bits_offset=0
+; NOPRUNE: {{\[}}[[PTR]]] PTR '(anon)' type_id=[[CU1:[0-9]+]]
+; NOPRUNE: STRUCT 'payload' size=8 vlen=1
+; NOPRUNE: {{\[}}[[CU1]]] STRUCT 'payload' size=4 vlen=0
+;
+; PRUNE: STRUCT 'container' size=8 vlen=1
+; PRUNE-NEXT: 'p' type_id=[[PPTR:[0-9]+]] bits_offset=0
+; PRUNE: {{\[}}[[PPTR]]] PTR '(anon)' type_id=[[FWD:[0-9]+]]
+; PRUNE: STRUCT 'payload' size=8 vlen=1
+; PRUNE: {{\[}}[[FWD]]] FWD 'payload' fwd_kind=struct
+
+define void @first(ptr %c) !dbg !4 { ret void }
+define void @second(ptr %p) !dbg !5 { ret void }
+
+!llvm.dbg.cu = !{!0, !1}
+!llvm.module.flags = !{!2, !3}
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !6, emissionKind: FullDebug)
+!1 = distinct !DICompileUnit(language: DW_LANG_C11, file: !7, emissionKind: FullDebug)
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i32 7, !"BTF", i32 1}
+!4 = distinct !DISubprogram(name: "first", scope: !6, file: !6, type: !8, unit: !0, spFlags: DISPFlagDefinition, retainedNodes: !10)
+!5 = distinct !DISubprogram(name: "second", scope: !7, file: !7, type: !21, unit: !1, spFlags: DISPFlagDefinition, retainedNodes: !11)
+!6 = !DIFile(filename: "a.c", directory: "/")
+!7 = !DIFile(filename: "b.c", directory: "/")
+!8 = !DISubroutineType(types: !9)
+!9 = !{null, !22}
+!21 = !DISubroutineType(types: !23)
+!22 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !12, size: 64)
+!23 = !{null, !24}
+!24 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !13, size: 64)
+!10 = !{!12}
+!11 = !{!13}
+!12 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "container", scope: !4, file: !6, size: 64, elements: !14)
+!13 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "payload", scope: !5, file: !7, size: 64, elements: !18)
+!14 = !{!15}
+!15 = !DIDerivedType(tag: DW_TAG_member, name: "p", scope: !12, baseType: !16, size: 64)
+!16 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !17, size: 64)
+!17 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "payload", file: !6, size: 32)
+!18 = !{!19}
+!19 = !DIDerivedType(tag: DW_TAG_member, name: "y", scope: !13, baseType: !20, size: 64)
+!20 = !DIBasicType(name: "long", size: 64, encoding: DW_ATE_signed)
diff --git a/llvm/test/CodeGen/X86/BTF/deferred-unrepresentable.ll b/llvm/test/CodeGen/X86/BTF/deferred-unrepresentable.ll
new file mode 100644
index 00000000000000..270c4c619f62cb
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/deferred-unrepresentable.ll
@@ -0,0 +1,22 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=obj %s -o %t
+; RUN: llvm-objcopy --dump-section .BTF=- %t | %python %p/../../BPF/BTF/print_btf.py - | FileCheck %s
+; CHECK: STRUCT 'holder' size=8 vlen=1
+; CHECK-NEXT: 'p' type_id=[[PTR:[0-9]+]] bits_offset=0
+; CHECK: {{\[}}[[PTR]]] PTR '(anon)' type_id=[[FWD:[0-9]+]]
+; CHECK: {{\[}}[[FWD]]] FWD 'payload' fwd_kind=struct
+
+ at h = global ptr null, !dbg !0
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!3, !4}
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "h", scope: !2, type: !5, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C11, file: !6, emissionKind: FullDebug, globals: !{!0})
+!3 = !{i32 2, !"Debug Info Version", i32 3}
+!4 = !{i32 7, !"BTF", i32 1}
+!5 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "holder", size: 64, elements: !{!7})
+!6 = !DIFile(filename: "test.c", directory: "/")
+!7 = !DIDerivedType(tag: DW_TAG_member, name: "p", scope: !5, baseType: !8, size: 64)
+!8 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !9, size: 64)
+!9 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "payload", size: 256, elements: !{!10})
+!10 = !DIDerivedType(tag: DW_TAG_member, name: "value", scope: !9, baseType: !11, size: 256)
+!11 = !DIBasicType(name: "complex", size: 256, encoding: DW_ATE_complex_float)
diff --git a/llvm/test/CodeGen/X86/BTF/empty-prototype.ll b/llvm/test/CodeGen/X86/BTF/empty-prototype.ll
new file mode 100644
index 00000000000000..e3975b3c795a69
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/empty-prototype.ll
@@ -0,0 +1,19 @@
+; RUN: llc -mtriple=x86_64-linux-gnu %s -o - | FileCheck %s
+; An empty DISubroutineType produces no FUNC and no .BTF or .BTF.ext section.
+; CHECK-NOT: .section .BTF
+; CHECK-NOT: BTF_KIND_FUNC
+
+define void @f() !dbg !4 {
+ ret void, !dbg !7
+}
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!8, !9, !10}
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !1, emissionKind: LineTablesOnly)
+!1 = !DIFile(filename: "test.c", directory: "/")
+!2 = !{}
+!3 = !DISubroutineType(types: !2)
+!4 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !3, unit: !0, spFlags: DISPFlagDefinition)
+!7 = !DILocation(line: 1, column: 1, scope: !4)
+!8 = !{i32 7, !"Dwarf Version", i32 5}
+!9 = !{i32 2, !"Debug Info Version", i32 3}
+!10 = !{i32 7, !"BTF", i32 1}
diff --git a/llvm/test/CodeGen/X86/BTF/enum.ll b/llvm/test/CodeGen/X86/BTF/enum.ll
new file mode 100644
index 00000000000000..18faf01aa552be
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/enum.ll
@@ -0,0 +1,59 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck -check-prefixes=CHECK %s
+
+; Verify BTF_KIND_ENUM emission on x86_64.
+;
+; Source:
+; enum color { RED, GREEN, BLUE };
+; enum color a;
+; Compilation flag:
+; clang -target x86_64-linux-gnu -g -gbtf -S -emit-llvm t.c
+
+ at a = dso_local local_unnamed_addr global i32 0, align 4, !dbg !0
+
+; CHECK: .section .BTF,"", at progbits
+; CHECK-NEXT: .short 60319 # 0xeb9f
+; CHECK-NEXT: .byte 1
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .long 24
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long 76
+; CHECK-NEXT: .long 76
+; CHECK-NEXT: .long 29
+; CHECK-NEXT: .long 1 # BTF_KIND_ENUM(id = 1)
+; CHECK-NEXT: .long 100663299 # 0x6000003
+; CHECK-NEXT: .long 4
+; CHECK-NEXT: .long 7
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long 11
+; CHECK-NEXT: .long 1
+; CHECK-NEXT: .long 17
+; CHECK-NEXT: .long 2
+; CHECK: .byte 0 # string offset=0
+; CHECK-NEXT: .ascii "color" # string offset=1
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .ascii "RED" # string offset=7
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .ascii "GREEN" # string offset=11
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .ascii "BLUE" # string offset=17
+; CHECK-NEXT: .byte 0
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!12, !13, !14, !15}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "a", scope: !2, file: !3, line: 2, type: !6, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !4, globals: !5, nameTableKind: None)
+!3 = !DIFile(filename: "t.c", directory: "/tmp")
+!4 = !{!6}
+!5 = !{!0}
+!6 = !DICompositeType(tag: DW_TAG_enumeration_type, name: "color", file: !3, line: 1, baseType: !7, size: 32, elements: !8)
+!7 = !DIBasicType(name: "unsigned int", size: 32, encoding: DW_ATE_unsigned)
+!8 = !{!9, !10, !11}
+!9 = !DIEnumerator(name: "RED", value: 0)
+!10 = !DIEnumerator(name: "GREEN", value: 1)
+!11 = !DIEnumerator(name: "BLUE", value: 2)
+!12 = !{i32 2, !"Dwarf Version", i32 4}
+!13 = !{i32 2, !"Debug Info Version", i32 3}
+!14 = !{i32 1, !"wchar_size", i32 4}
+!15 = !{i32 4, !"BTF", i32 1}
diff --git a/llvm/test/CodeGen/X86/BTF/func.ll b/llvm/test/CodeGen/X86/BTF/func.ll
new file mode 100644
index 00000000000000..15acbb78cb7969
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/func.ll
@@ -0,0 +1,47 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck -check-prefixes=CHECK %s
+
+; Verify BTF function types on x86_64 without .BTF.ext emission.
+;
+; Source:
+; void f1(void) {}
+; Compilation flag:
+; clang -target x86_64-linux-gnu -gbtf -S -emit-llvm t.c
+
+define dso_local void @f1() !dbg !7 {
+ ret void, !dbg !10
+}
+
+; CHECK: .section .BTF,"", at progbits
+; CHECK-NEXT: .short 60319 # 0xeb9f
+; CHECK-NEXT: .byte 1
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .long 24
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long 24
+; CHECK-NEXT: .long 24
+; CHECK-NEXT: .long 4
+; CHECK-NEXT: .long 0 # BTF_KIND_FUNC_PROTO(id = 1)
+; CHECK-NEXT: .long 218103808 # 0xd000000
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long 1 # BTF_KIND_FUNC(id = 2)
+; CHECK-NEXT: .long 201326593 # 0xc000001
+; CHECK-NEXT: .long 1
+; CHECK-NEXT: .byte 0 # string offset=0
+; CHECK-NEXT: .ascii "f1" # string offset=1
+; CHECK-NEXT: .byte 0
+; CHECK-NOT: .section .BTF.ext
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5, !6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "t.c", directory: "/tmp")
+!2 = !{}
+!3 = !{i32 2, !"Dwarf Version", i32 4}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 4}
+!6 = !{i32 7, !"BTF", i32 1}
+!7 = distinct !DISubprogram(name: "f1", scope: !1, file: !1, line: 1, type: !8, isLocal: false, isDefinition: true, scopeLine: 1, flags: DIFlagPrototyped, isOptimized: true, unit: !0, retainedNodes: !2)
+!8 = !DISubroutineType(types: !9)
+!9 = !{null}
+!10 = !DILocation(line: 1, column: 16, scope: !7)
diff --git a/llvm/test/CodeGen/X86/BTF/global-var.ll b/llvm/test/CodeGen/X86/BTF/global-var.ll
new file mode 100644
index 00000000000000..68b3046dcd6b2b
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/global-var.ll
@@ -0,0 +1,60 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck -check-prefixes=CHECK %s
+
+; Verify BTF_KIND_VAR and BTF_KIND_DATASEC on x86_64 without .BTF.ext.
+;
+; Source:
+; int g = 5;
+; int test(void) { return g; }
+; Compilation flag:
+; clang -target x86_64-linux-gnu -gbtf -S -emit-llvm t.c
+
+ at g = dso_local global i32 5, align 4, !dbg !0
+
+define dso_local i32 @test() !dbg !11 {
+ %1 = load i32, ptr @g, align 4, !dbg !14
+ ret i32 %1, !dbg !15
+}
+
+; .BTF section with types
+; CHECK: .section .BTF,"", at progbits
+; CHECK-NEXT: .short 60319 # 0xeb9f
+; CHECK-NEXT: .byte 1
+; CHECK-NEXT: .byte 0
+; CHECK: .long 0 # BTF_KIND_FUNC_PROTO(id = 1)
+; CHECK-NEXT: .long 218103808 # 0xd000000
+; CHECK-NEXT: .long 2
+; CHECK-NEXT: .long 1 # BTF_KIND_INT(id = 2)
+; CHECK-NEXT: .long 16777216 # 0x1000000
+; CHECK-NEXT: .long 4
+; CHECK-NEXT: .long 16777248 # 0x1000020
+; CHECK: .long 5 # BTF_KIND_FUNC(id = 3)
+; CHECK: .long 10 # BTF_KIND_VAR(id = 4)
+; CHECK-NEXT: .long 234881024 # 0xe000000
+; CHECK-NEXT: .long 2
+; CHECK-NEXT: .long 1
+; CHECK: .long 12 # BTF_KIND_DATASEC(id = 5)
+; CHECK-NEXT: .long 251658241 # 0xf000001
+; CHECK: .ascii "int"
+; CHECK: .ascii "test"
+; CHECK: .ascii ".data"
+; CHECK-NOT: .section .BTF.ext
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!7, !8, !9, !10}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "g", scope: !2, file: !3, line: 1, type: !6, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !4, globals: !5, nameTableKind: None)
+!3 = !DIFile(filename: "t.c", directory: "/tmp")
+!4 = !{}
+!5 = !{!0}
+!6 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!7 = !{i32 2, !"Dwarf Version", i32 4}
+!8 = !{i32 2, !"Debug Info Version", i32 3}
+!9 = !{i32 1, !"wchar_size", i32 4}
+!10 = !{i32 7, !"BTF", i32 1}
+!11 = distinct !DISubprogram(name: "test", scope: !3, file: !3, line: 2, type: !12, isLocal: false, isDefinition: true, scopeLine: 2, flags: DIFlagPrototyped, isOptimized: true, unit: !2, retainedNodes: !4)
+!12 = !DISubroutineType(types: !13)
+!13 = !{!6}
+!14 = !DILocation(line: 2, column: 25, scope: !11)
+!15 = !DILocation(line: 2, column: 18, scope: !11)
diff --git a/llvm/test/CodeGen/X86/BTF/inheritance.ll b/llvm/test/CodeGen/X86/BTF/inheritance.ll
new file mode 100644
index 00000000000000..438afb6845df7c
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/inheritance.ll
@@ -0,0 +1,46 @@
+; RUN: llc -mtriple=x86_64-linux-gnu %s -o - | FileCheck %s
+; CHECK: BTF_KIND_STRUCT(id = 1)
+; CHECK-NEXT: .long 67108866
+; CHECK-NEXT: .long 8
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long 2
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long {{[0-9]+}}
+; CHECK-NEXT: .long 3
+; CHECK-NEXT: .long 32
+; D keeps its non-virtual base. V (virtual base) and W (base V) have no fixed
+; layout: neither they nor their variables are emitted.
+; CHECK-NOT: BTF_KIND_FWD
+; CHECK: BTF_KIND_VAR(id = 4)
+; CHECK-NOT: BTF_KIND_{{VAR|FWD}}
+
+ at d = global i64 0, !dbg !0
+ at v = global i64 0, !dbg !12
+ at w = global i64 0, !dbg !20
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!8, !9, !10}
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "d", scope: !2, file: !3, type: !4, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !3, emissionKind: FullDebug, globals: !11)
+!3 = !DIFile(filename: "test.cc", directory: "/")
+!4 = !DICompositeType(tag: DW_TAG_structure_type, name: "D", file: !3, size: 64, elements: !5)
+!5 = !{!6, !7}
+!6 = !DIDerivedType(tag: DW_TAG_inheritance, scope: !4, baseType: !14)
+!7 = !DIDerivedType(tag: DW_TAG_member, name: "b", scope: !4, baseType: !16, size: 32, offset: 32)
+!8 = !{i32 7, !"Dwarf Version", i32 5}
+!9 = !{i32 2, !"Debug Info Version", i32 3}
+!10 = !{i32 7, !"BTF", i32 1}
+!11 = !{!0, !12, !20}
+!12 = !DIGlobalVariableExpression(var: !13, expr: !DIExpression())
+!13 = distinct !DIGlobalVariable(name: "v", scope: !2, file: !3, type: !17, isLocal: false, isDefinition: true)
+!14 = !DICompositeType(tag: DW_TAG_structure_type, name: "B", file: !3, size: 32, elements: !15)
+!15 = !{}
+!16 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!17 = !DICompositeType(tag: DW_TAG_structure_type, name: "V", file: !3, size: 64, elements: !18)
+!18 = !{!19}
+!19 = !DIDerivedType(tag: DW_TAG_inheritance, scope: !17, baseType: !14, flags: DIFlagVirtual)
+!20 = !DIGlobalVariableExpression(var: !21, expr: !DIExpression())
+!21 = distinct !DIGlobalVariable(name: "w", scope: !2, file: !3, type: !22, isLocal: false, isDefinition: true)
+!22 = !DICompositeType(tag: DW_TAG_structure_type, name: "W", file: !3, size: 64, elements: !23)
+!23 = !{!24}
+!24 = !DIDerivedType(tag: DW_TAG_inheritance, scope: !22, baseType: !17)
diff --git a/llvm/test/CodeGen/X86/BTF/inlined-retained.ll b/llvm/test/CodeGen/X86/BTF/inlined-retained.ll
new file mode 100644
index 00000000000000..074abe13872e7f
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/inlined-retained.ll
@@ -0,0 +1,38 @@
+; RUN: llc -mtriple=x86_64-linux-gnu %s -o - | FileCheck %s
+
+; Retained types in both an intermediate call site and the innermost inlined
+; function survive. The innermost scope is reached only from a debug record.
+; CHECK: .section .BTF
+; CHECK: .ascii "middle_value"
+; CHECK: .ascii "inner_value"
+
+declare void @sink()
+
+define void @outer() !dbg !4 {
+ call void @sink(), !dbg !16
+ #dbg_value(i32 0, !17, !DIExpression(), !18)
+ ret void, !dbg !15
+}
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3}
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !1, emissionKind: FullDebug)
+!1 = !DIFile(filename: "inline.c", directory: "/")
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i32 7, !"BTF", i32 1}
+!4 = distinct !DISubprogram(name: "outer", scope: !1, file: !1, line: 1, type: !7, unit: !0, spFlags: DISPFlagDefinition)
+!5 = distinct !DISubprogram(name: "middle", scope: !1, file: !1, line: 2, type: !7, unit: !0, spFlags: DISPFlagDefinition, retainedNodes: !9)
+!6 = distinct !DISubprogram(name: "inner", scope: !1, file: !1, line: 3, type: !7, unit: !0, spFlags: DISPFlagDefinition, retainedNodes: !10)
+!7 = !DISubroutineType(types: !8)
+!8 = !{null}
+!9 = !{!11}
+!10 = !{!12}
+!11 = !DICompositeType(tag: DW_TAG_enumeration_type, scope: !5, size: 32, elements: !13)
+!12 = !DICompositeType(tag: DW_TAG_enumeration_type, scope: !6, size: 32, elements: !14)
+!13 = !{!DIEnumerator(name: "middle_value", value: 1)}
+!14 = !{!DIEnumerator(name: "inner_value", value: 2)}
+!15 = !DILocation(line: 1, scope: !4)
+!16 = !DILocation(line: 2, scope: !5, inlinedAt: !15)
+!17 = !DILocalVariable(name: "local", scope: !6, type: !19)
+!18 = !DILocation(line: 3, scope: !6, inlinedAt: !16)
+!19 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
diff --git a/llvm/test/CodeGen/X86/BTF/int.ll b/llvm/test/CodeGen/X86/BTF/int.ll
new file mode 100644
index 00000000000000..cf461e0c5e9382
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/int.ll
@@ -0,0 +1,42 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck -check-prefixes=CHECK %s
+
+; Verify that target-independent BTF emission works on x86_64.
+;
+; Source:
+; int a;
+; Compilation flag:
+; clang -target x86_64-linux-gnu -g -gbtf -S -emit-llvm t.c
+
+ at a = common dso_local local_unnamed_addr global i32 0, align 4, !dbg !0
+
+; CHECK: .section .BTF,"", at progbits
+; CHECK-NEXT: .short 60319 # 0xeb9f
+; CHECK-NEXT: .byte 1
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .long 24
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long 16
+; CHECK-NEXT: .long 16
+; CHECK-NEXT: .long 5
+; CHECK-NEXT: .long 1 # BTF_KIND_INT(id = 1)
+; CHECK-NEXT: .long 16777216 # 0x1000000
+; CHECK-NEXT: .long 4
+; CHECK-NEXT: .long 16777248 # 0x1000020
+; CHECK-NEXT: .byte 0 # string offset=0
+; CHECK-NEXT: .ascii "int" # string offset=1
+; CHECK-NEXT: .byte 0
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!7, !8, !9, !10}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "a", scope: !2, file: !3, line: 1, type: !6, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !4, globals: !5, nameTableKind: None)
+!3 = !DIFile(filename: "t.c", directory: "/tmp")
+!4 = !{}
+!5 = !{!0}
+!6 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!7 = !{i32 2, !"Dwarf Version", i32 4}
+!8 = !{i32 2, !"Debug Info Version", i32 3}
+!9 = !{i32 1, !"wchar_size", i32 4}
+!10 = !{i32 4, !"BTF", i32 1}
diff --git a/llvm/test/CodeGen/X86/BTF/local-enum-underlying.ll b/llvm/test/CodeGen/X86/BTF/local-enum-underlying.ll
new file mode 100644
index 00000000000000..0bfa7cd5fc6ad0
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/local-enum-underlying.ll
@@ -0,0 +1,39 @@
+; RUN: split-file %s %t
+; RUN: llc -mtriple=x86_64-linux-gnu %t/typedef.ll -o - | FileCheck %s --check-prefix=TYPEDEF
+; RUN: llc -mtriple=x86_64-linux-gnu %t/wide.ll -o - | FileCheck %s --check-prefix=WIDE --implicit-check-not=BTF_KIND_ENUM
+
+; TYPEDEF: BTF_KIND_ENUM(
+; TYPEDEF-NEXT: .long 100663297
+; TYPEDEF-NEXT: .long 2
+; TYPEDEF: .ascii "value"
+
+; WIDE: .section .BTF
+; WIDE: BTF_KIND_FUNC(
+
+;--- typedef.ll
+define void @f() !dbg !4 { ret void }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3}
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !1, emissionKind: FullDebug)
+!1 = !DIFile(filename: "enum.c", directory: "/")
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i32 7, !"BTF", i32 1}
+!4 = distinct !DISubprogram(name: "f", scope: !1, file: !1, type: !DISubroutineType(types: !{null}), unit: !0, spFlags: DISPFlagDefinition, retainedNodes: !{!5})
+!5 = !DICompositeType(tag: DW_TAG_enumeration_type, name: "E", scope: !4, baseType: !6, size: 16, elements: !{!DIEnumerator(name: "value", value: 42, isUnsigned: true)})
+!6 = !DIDerivedType(tag: DW_TAG_typedef, name: "u16", baseType: !7)
+!7 = !DIDerivedType(tag: DW_TAG_const_type, baseType: !8)
+!8 = !DIBasicType(name: "unsigned short", size: 16, encoding: DW_ATE_unsigned)
+
+;--- wide.ll
+define void @f() !dbg !4 { ret void }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3}
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !1, emissionKind: FullDebug)
+!1 = !DIFile(filename: "enum.c", directory: "/")
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i32 7, !"BTF", i32 1}
+!4 = distinct !DISubprogram(name: "f", scope: !1, file: !1, type: !DISubroutineType(types: !{null}), unit: !0, spFlags: DISPFlagDefinition, retainedNodes: !{!5})
+!5 = !DICompositeType(tag: DW_TAG_enumeration_type, name: "E", scope: !4, baseType: !6, size: 128, elements: !{!DIEnumerator(name: "value", value: 42, isUnsigned: true)})
+!6 = !DIBasicType(name: "unsigned __int128", size: 128, encoding: DW_ATE_unsigned)
diff --git a/llvm/test/CodeGen/X86/BTF/local-var-type.ll b/llvm/test/CodeGen/X86/BTF/local-var-type.ll
new file mode 100644
index 00000000000000..9154a5c7b3d8e5
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/local-var-type.ll
@@ -0,0 +1,53 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck %s
+
+; Verify dbg.declare-only local variable types are emitted on x86_64.
+;
+; Source:
+; int f1(void) {
+; struct local_ctx { int fd; } ctx = { .fd = 7 };
+; return ctx.fd;
+; }
+; Compilation flag:
+; clang -target x86_64-linux-gnu -g -gbtf -S -emit-llvm t.c
+
+%struct.local_ctx = type { i32 }
+
+define dso_local i32 @f1() !dbg !7 {
+entry:
+ %ctx = alloca %struct.local_ctx, align 4
+ call void @llvm.dbg.declare(metadata ptr %ctx, metadata !12, metadata !DIExpression()), !dbg !17
+ store i32 7, ptr %ctx, align 4, !dbg !17
+ %fd = load i32, ptr %ctx, align 4, !dbg !18
+ ret i32 %fd, !dbg !19
+}
+
+; CHECK: .section .BTF,"", at progbits
+; CHECK: # BTF_KIND_STRUCT(
+; CHECK: .ascii "local_ctx"
+; CHECK: .ascii "fd"
+
+declare void @llvm.dbg.declare(metadata, metadata, metadata)
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5, !6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "t.c", directory: "/tmp")
+!2 = !{}
+!3 = !{i32 2, !"Dwarf Version", i32 4}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 4}
+!6 = !{i32 4, !"BTF", i32 1}
+!7 = distinct !DISubprogram(name: "f1", scope: !1, file: !1, line: 1, type: !8, isLocal: false, isDefinition: true, scopeLine: 1, flags: DIFlagPrototyped, isOptimized: true, unit: !0, retainedNodes: !11)
+!8 = !DISubroutineType(types: !9)
+!9 = !{!10}
+!10 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!11 = !{}
+!12 = !DILocalVariable(name: "ctx", scope: !7, file: !1, line: 2, type: !13)
+!13 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "local_ctx", scope: !7, file: !1, line: 2, size: 32, elements: !14)
+!14 = !{!15}
+!15 = !DIDerivedType(tag: DW_TAG_member, name: "fd", scope: !13, file: !1, line: 2, baseType: !10, size: 32)
+!16 = !DILocation(line: 1, column: 1, scope: !7)
+!17 = !DILocation(line: 2, column: 30, scope: !7)
+!18 = !DILocation(line: 3, column: 3, scope: !7)
+!19 = !DILocation(line: 3, column: 10, scope: !7)
diff --git a/llvm/test/CodeGen/X86/BTF/local-virtual-member.ll b/llvm/test/CodeGen/X86/BTF/local-virtual-member.ll
new file mode 100644
index 00000000000000..ca25fdfe40bbde
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/local-virtual-member.ll
@@ -0,0 +1,30 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=obj %s -o %t
+; RUN: llvm-objcopy --dump-section .BTF=- %t | %python %p/../../BPF/BTF/print_btf.py - | FileCheck %s --implicit-check-not="STRUCT 'Wrapper'" --implicit-check-not="STRUCT 'V'" --implicit-check-not="ARRAY"
+
+; A virtual-base record cannot appear by value, even inside an array and
+; behind a typedef and qualifier. Pointers to the wrapper still work.
+; CHECK: STRUCT 'Holder' size=8 vlen=1
+; CHECK-NEXT: 'p' type_id=[[PTR:[0-9]+]] bits_offset=0
+; CHECK-NEXT: {{\[}}[[PTR]]] PTR '(anon)' type_id=[[FWD:[0-9]+]]
+; CHECK: {{\[}}[[FWD]]] FWD 'Wrapper' fwd_kind=struct
+
+define void @f() !dbg !4 { ret void }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3}
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, emissionKind: FullDebug)
+!1 = !DIFile(filename: "virtual.cc", directory: "/")
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i32 7, !"BTF", i32 1}
+!4 = distinct !DISubprogram(name: "f", scope: !1, file: !1, type: !DISubroutineType(types: !{null}), unit: !0, spFlags: DISPFlagDefinition, retainedNodes: !{!5, !8})
+!5 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Holder", scope: !4, size: 64, elements: !{!6})
+!6 = !DIDerivedType(tag: DW_TAG_member, name: "p", scope: !5, baseType: !7, size: 64)
+!7 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !8, size: 64)
+!8 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper", scope: !4, size: 256, elements: !{!9})
+!9 = !DIDerivedType(tag: DW_TAG_member, name: "items", scope: !8, baseType: !10, size: 256)
+!10 = !DIDerivedType(tag: DW_TAG_typedef, name: "Items", baseType: !11)
+!11 = !DIDerivedType(tag: DW_TAG_const_type, baseType: !12)
+!12 = !DICompositeType(tag: DW_TAG_array_type, baseType: !13, size: 256, elements: !{!DISubrange(count: 2)})
+!13 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "V", file: !1, size: 128, elements: !{!14})
+!14 = !DIDerivedType(tag: DW_TAG_inheritance, scope: !13, baseType: !15, flags: DIFlagVirtual)
+!15 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "B", file: !1, size: 32)
diff --git a/llvm/test/CodeGen/X86/BTF/local-vla.ll b/llvm/test/CodeGen/X86/BTF/local-vla.ll
new file mode 100644
index 00000000000000..5d15f36b172ef3
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/local-vla.ll
@@ -0,0 +1,28 @@
+; RUN: llc -mtriple=x86_64-linux-gnu %s -o - | FileCheck %s --implicit-check-not=BTF_KIND_ARRAY
+
+; The inner dimension is constant, but neither array entry should be emitted.
+; CHECK: .section .BTF
+; CHECK: BTF_KIND_FUNC(
+
+define void @f(i32 %n, ptr %a) !dbg !4 {
+ #dbg_value(i32 %n, !7, !DIExpression(), !8)
+ #dbg_declare(ptr %a, !9, !DIExpression(), !8)
+ ret void, !dbg !8
+}
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3}
+!0 = distinct !DICompileUnit(language: DW_LANG_C11, file: !1, emissionKind: FullDebug)
+!1 = !DIFile(filename: "vla.c", directory: "/")
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i32 7, !"BTF", i32 1}
+!4 = distinct !DISubprogram(name: "f", scope: !1, file: !1, type: !5, unit: !0, spFlags: DISPFlagDefinition)
+!5 = !DISubroutineType(types: !6)
+!6 = !{null, !12, !13}
+!7 = !DILocalVariable(name: "n", arg: 1, scope: !4, type: !12)
+!8 = !DILocation(line: 1, scope: !4)
+!9 = !DILocalVariable(name: "a", scope: !4, type: !10)
+!10 = !DICompositeType(tag: DW_TAG_array_type, baseType: !12, elements: !11)
+!11 = !{!DISubrange(count: !7), !DISubrange(count: 4)}
+!12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!13 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !12, size: 64)
diff --git a/llvm/test/CodeGen/X86/BTF/maps-global.ll b/llvm/test/CodeGen/X86/BTF/maps-global.ll
new file mode 100644
index 00000000000000..20e251d3e6ccd4
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/maps-global.ll
@@ -0,0 +1,17 @@
+; RUN: llc -mtriple=x86_64-linux-gnu %s -o - | FileCheck %s
+; CHECK: BTF_KIND_VAR
+; CHECK: BTF_KIND_DATASEC
+; CHECK: .byte 97
+; CHECK: .ascii ".maps"
+ at a = global i32 1, section ".maps", !dbg !0
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!6, !7, !8}
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "a", scope: !2, file: !3, line: 1, type: !4, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C11, file: !3, emissionKind: FullDebug, globals: !5)
+!3 = !DIFile(filename: "test.c", directory: "/")
+!4 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!5 = !{!0}
+!6 = !{i32 7, !"Dwarf Version", i32 5}
+!7 = !{i32 2, !"Debug Info Version", i32 3}
+!8 = !{i32 7, !"BTF", i32 1}
diff --git a/llvm/test/CodeGen/X86/BTF/no-btf-flag.ll b/llvm/test/CodeGen/X86/BTF/no-btf-flag.ll
new file mode 100644
index 00000000000000..8db56c6b9a2cd9
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/no-btf-flag.ll
@@ -0,0 +1,28 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck -check-prefixes=CHECK %s
+
+; Verify that without the "BTF" module flag, no .BTF sections are emitted
+; for non-BPF targets, even when debug info is present.
+;
+; Source:
+; int a;
+; Compilation flag:
+; clang -target x86_64-linux-gnu -g -S -emit-llvm t.c (no -gbtf)
+
+ at a = common dso_local local_unnamed_addr global i32 0, align 4, !dbg !0
+
+; CHECK-NOT: .section .BTF
+; CHECK-NOT: .section .BTF.ext
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!7, !8, !9}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "a", scope: !2, file: !3, line: 1, type: !6, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !4, globals: !5, nameTableKind: None)
+!3 = !DIFile(filename: "t.c", directory: "/tmp")
+!4 = !{}
+!5 = !{!0}
+!6 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!7 = !{i32 2, !"Dwarf Version", i32 4}
+!8 = !{i32 2, !"Debug Info Version", i32 3}
+!9 = !{i32 1, !"wchar_size", i32 4}
diff --git a/llvm/test/CodeGen/X86/BTF/static-member.ll b/llvm/test/CodeGen/X86/BTF/static-member.ll
new file mode 100644
index 00000000000000..65c1627219690f
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/static-member.ll
@@ -0,0 +1,19 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=obj %s -o %t
+; RUN: llvm-objcopy --dump-section .BTF=- %t | %python %p/../../BPF/BTF/print_btf.py - | FileCheck %s
+; CHECK: STRUCT 'Node' size=4 vlen=1
+; CHECK-NEXT: 'value' type_id={{[0-9]+}} bits_offset=0
+; CHECK-NOT: singleton
+
+ at n = global i32 0, !dbg !9
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3}
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, emissionKind: FullDebug, globals: !{!9})
+!1 = !DIFile(filename: "static.cc", directory: "/")
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!3 = !{i32 7, !"BTF", i32 1}
+!5 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Node", file: !1, size: 32, elements: !{!6, !7})
+!6 = !DIDerivedType(tag: DW_TAG_member, name: "singleton", scope: !5, baseType: !5, flags: DIFlagStaticMember)
+!7 = !DIDerivedType(tag: DW_TAG_member, name: "value", scope: !5, baseType: !8, size: 32)
+!8 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!9 = !DIGlobalVariableExpression(var: !10, expr: !DIExpression())
+!10 = distinct !DIGlobalVariable(name: "n", scope: !0, file: !1, type: !5, isLocal: false, isDefinition: true)
diff --git a/llvm/test/CodeGen/X86/BTF/struct-method.ll b/llvm/test/CodeGen/X86/BTF/struct-method.ll
new file mode 100644
index 00000000000000..390a3c8527c51e
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/struct-method.ll
@@ -0,0 +1,51 @@
+; RUN: llc -mtriple=x86_64-linux-gnu %s -o - | FileCheck %s
+; A struct's non-layout method is ignored while its member is retained.
+; CHECK-NOT: BTF_KIND_FUNC
+; CHECK: BTF_KIND_STRUCT
+; CHECK-NEXT: .long 67108865
+; CHECK-NEXT: .long {{[0-9]+}}
+; CHECK-NEXT: .long {{[0-9]+}}
+; CHECK-NEXT: .long 2
+; CHECK-NEXT: .long 0
+; CHECK: BTF_KIND_VAR
+; CHECK: BTF_KIND_VAR
+; CHECK: .byte 67
+; CHECK-NOT: .ascii "bad"
+; CHECK: .ascii "pointer"
+
+ at c = global i32 0, !dbg !0
+ at complex = global [2 x double] zeroinitializer, !dbg !17
+ at bad = global [2 x double] zeroinitializer, !dbg !21
+ at pointer = global ptr null, !dbg !25
+define void @f(double %x) !dbg !8 {
+ ret void, !dbg !13
+}
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!6, !7, !14}
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "c", scope: !2, file: !3, line: 1, type: !4, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !3, emissionKind: FullDebug, globals: !5)
+!3 = !DIFile(filename: "test.cc", directory: "/")
+!4 = !DICompositeType(tag: DW_TAG_structure_type, name: "C", file: !3, line: 1, size: 32, elements: !15)
+!5 = !{!0, !17, !21, !25}
+!6 = !{i32 7, !"Dwarf Version", i32 5}
+!7 = !{i32 2, !"Debug Info Version", i32 3}
+!8 = distinct !DISubprogram(name: "f", scope: !3, file: !3, line: 2, type: !9, unit: !2, spFlags: DISPFlagDefinition)
+!9 = !DISubroutineType(types: !10)
+!10 = !{null, !23, !20}
+!11 = !DIBasicType(name: "decimal float", size: 128, encoding: DW_ATE_decimal_float)
+!13 = !DILocation(line: 2, column: 1, scope: !8)
+!14 = !{i32 7, !"BTF", i32 1}
+!15 = !{!16, !19}
+!16 = !DISubprogram(name: "method", scope: !4, file: !3, type: !9, spFlags: 0)
+!17 = !DIGlobalVariableExpression(var: !18, expr: !DIExpression())
+!18 = distinct !DIGlobalVariable(name: "complex", scope: !2, file: !3, line: 1, type: !11, isLocal: false, isDefinition: true)
+!19 = !DIDerivedType(tag: DW_TAG_member, name: "n", scope: !4, baseType: !20, size: 32)
+!20 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!21 = !DIGlobalVariableExpression(var: !22, expr: !DIExpression())
+!22 = distinct !DIGlobalVariable(name: "bad", scope: !2, file: !3, type: !23, isLocal: false, isDefinition: true)
+!23 = !DIDerivedType(tag: DW_TAG_const_type, baseType: !24)
+!24 = !DIDerivedType(tag: DW_TAG_typedef, name: "bad_type", baseType: !11)
+!25 = !DIGlobalVariableExpression(var: !26, expr: !DIExpression())
+!26 = distinct !DIGlobalVariable(name: "pointer", scope: !2, file: !3, type: !27, isLocal: false, isDefinition: true)
+!27 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !24, size: 64)
diff --git a/llvm/test/CodeGen/X86/BTF/struct.ll b/llvm/test/CodeGen/X86/BTF/struct.ll
new file mode 100644
index 00000000000000..ef15469c64f9c7
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/struct.ll
@@ -0,0 +1,70 @@
+; RUN: llc -mtriple=x86_64-linux-gnu -filetype=asm -o - %s | FileCheck -check-prefixes=CHECK %s
+
+; Verify BTF_KIND_STRUCT emission on x86_64.
+;
+; Source:
+; struct t1 {char m1; int n1;} a;
+; Compilation flag:
+; clang -target x86_64-linux-gnu -g -gbtf -S -emit-llvm t.c
+
+%struct.t1 = type { i8, i32 }
+
+ at a = common dso_local local_unnamed_addr global %struct.t1 zeroinitializer, align 4, !dbg !0
+
+; CHECK: .section .BTF,"", at progbits
+; CHECK-NEXT: .short 60319 # 0xeb9f
+; CHECK-NEXT: .byte 1
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .long 24
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long 68
+; CHECK-NEXT: .long 68
+; CHECK-NEXT: .long 19
+; CHECK-NEXT: .long 1 # BTF_KIND_STRUCT(id = 1)
+; CHECK-NEXT: .long 67108866 # 0x4000002
+; CHECK-NEXT: .long 8
+; CHECK-NEXT: .long 4
+; CHECK-NEXT: .long 2
+; CHECK-NEXT: .long 0 # 0x0
+; CHECK-NEXT: .long 7
+; CHECK-NEXT: .long 3
+; CHECK-NEXT: .long 32 # 0x20
+; CHECK-NEXT: .long 10 # BTF_KIND_INT(id = 2)
+; CHECK-NEXT: .long 16777216 # 0x1000000
+; CHECK-NEXT: .long 1
+; CHECK-NEXT: .long 16777224 # 0x1000008
+; CHECK-NEXT: .long 15 # BTF_KIND_INT(id = 3)
+; CHECK-NEXT: .long 16777216 # 0x1000000
+; CHECK-NEXT: .long 4
+; CHECK-NEXT: .long 16777248 # 0x1000020
+; CHECK-NEXT: .byte 0 # string offset=0
+; CHECK-NEXT: .ascii "t1" # string offset=1
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .ascii "m1" # string offset=4
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .ascii "n1" # string offset=7
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .ascii "char" # string offset=10
+; CHECK-NEXT: .byte 0
+; CHECK-NEXT: .ascii "int" # string offset=15
+; CHECK-NEXT: .byte 0
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!12, !13, !14, !15}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "a", scope: !2, file: !3, line: 1, type: !6, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !4, globals: !5, nameTableKind: None)
+!3 = !DIFile(filename: "t.c", directory: "/tmp")
+!4 = !{}
+!5 = !{!0}
+!6 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t1", file: !3, line: 1, size: 64, elements: !7)
+!7 = !{!8, !10}
+!8 = !DIDerivedType(tag: DW_TAG_member, name: "m1", scope: !6, file: !3, line: 1, baseType: !9, size: 8)
+!9 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!10 = !DIDerivedType(tag: DW_TAG_member, name: "n1", scope: !6, file: !3, line: 1, baseType: !11, size: 32, offset: 32)
+!11 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!12 = !{i32 2, !"Dwarf Version", i32 4}
+!13 = !{i32 2, !"Debug Info Version", i32 3}
+!14 = !{i32 1, !"wchar_size", i32 4}
+!15 = !{i32 4, !"BTF", i32 1}
diff --git a/llvm/test/CodeGen/X86/BTF/unsupported-types.ll b/llvm/test/CodeGen/X86/BTF/unsupported-types.ll
new file mode 100644
index 00000000000000..aff9e9ccec7983
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/unsupported-types.ll
@@ -0,0 +1,59 @@
+; RUN: llc -mtriple=x86_64-linux-gnu %s -o - | FileCheck %s --implicit-check-not='.ascii "complex long double"'
+; A class is a struct; complex types use FLOAT only for supported sizes.
+; CHECK: BTF_KIND_FUNC_PROTO(id = 1)
+; CHECK-NEXT: .long 218103809
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long 0
+; CHECK-NEXT: .long 2
+; CHECK: BTF_KIND_FLOAT(id = 2)
+; CHECK-NEXT: .long 268435456
+; CHECK-NEXT: .long 16
+; CHECK: BTF_KIND_STRUCT(id = 4)
+; CHECK-NEXT: .long 67108865
+; CHECK-NEXT: .long 16
+; CHECK-NEXT: .long {{[0-9]+}}
+; CHECK-NEXT: .long 2
+; CHECK-NEXT: .long 0
+; CHECK: BTF_KIND_VAR
+; CHECK: BTF_KIND_VAR
+; CHECK: BTF_KIND_FLOAT
+; CHECK-NEXT: .long 268435456
+; CHECK-NEXT: .long 8
+; CHECK: .ascii "complex double"
+; CHECK: .byte 67
+; CHECK: .ascii "complex float"
+
+ at c = global [2 x double] zeroinitializer, !dbg !0
+ at complex = global [2 x double] zeroinitializer, !dbg !17
+ at cf = global [2 x float] zeroinitializer, !dbg !21
+define void @f(double %x) !dbg !8 {
+ %cl = alloca [2 x x86_fp80], align 16
+ #dbg_declare(ptr %cl, !25, !DIExpression(), !13)
+ ret void, !dbg !13
+}
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!6, !7, !14}
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "c", scope: !2, file: !3, line: 1, type: !4, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !3, emissionKind: FullDebug, globals: !5)
+!3 = !DIFile(filename: "test.cc", directory: "/")
+!4 = !DICompositeType(tag: DW_TAG_class_type, name: "C", file: !3, line: 1, size: 128, elements: !15)
+!5 = !{!0, !17, !21}
+!6 = !{i32 7, !"Dwarf Version", i32 5}
+!7 = !{i32 2, !"Debug Info Version", i32 3}
+!8 = distinct !DISubprogram(name: "f", scope: !3, file: !3, line: 2, type: !9, unit: !2, spFlags: DISPFlagDefinition)
+!9 = !DISubroutineType(types: !10)
+!10 = !{null, !11}
+!11 = !DIBasicType(name: "complex double", size: 128, encoding: DW_ATE_complex_float)
+!13 = !DILocation(line: 2, column: 1, scope: !8)
+!14 = !{i32 7, !"BTF", i32 1}
+!15 = !{!16, !19}
+!16 = !DISubprogram(name: "method", scope: !4, file: !3, type: !9, spFlags: 0)
+!17 = !DIGlobalVariableExpression(var: !18, expr: !DIExpression())
+!18 = distinct !DIGlobalVariable(name: "complex", scope: !2, file: !3, line: 1, type: !11, isLocal: false, isDefinition: true)
+!19 = !DIDerivedType(tag: DW_TAG_member, name: "member", scope: !4, baseType: !11, size: 128)
+!21 = !DIGlobalVariableExpression(var: !22, expr: !DIExpression())
+!22 = distinct !DIGlobalVariable(name: "cf", scope: !2, file: !3, type: !23, isLocal: false, isDefinition: true)
+!23 = !DIBasicType(name: "complex float", size: 64, encoding: DW_ATE_complex_float)
+!25 = !DILocalVariable(name: "cl", scope: !8, file: !3, type: !26)
+!26 = !DIBasicType(name: "complex long double", size: 256, encoding: DW_ATE_complex_float)
diff --git a/llvm/test/CodeGen/X86/BTF/wide-integer.ll b/llvm/test/CodeGen/X86/BTF/wide-integer.ll
new file mode 100644
index 00000000000000..f6a0d5baa14289
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/wide-integer.ll
@@ -0,0 +1,22 @@
+; RUN: llc -mtriple=x86_64-linux-gnu %s -o - | FileCheck %s --implicit-check-not='BTF_KIND_INT' --implicit-check-not='BTF_KIND_STRUCT'
+; CHECK: BTF_KIND_FLOAT
+
+ at w = global i256 0, !dbg !8
+ at wide = global i256 0, !dbg !0
+ at ok = global float 0.0, !dbg !11
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!3, !4}
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "wide", scope: !2, type: !5, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C11, file: !6, emissionKind: FullDebug, globals: !{!8, !0, !11})
+!3 = !{i32 2, !"Debug Info Version", i32 3}
+!4 = !{i32 7, !"BTF", i32 1}
+!5 = !DIBasicType(name: "unsigned _BitInt(256)", size: 256, encoding: DW_ATE_unsigned)
+!6 = !DIFile(filename: "test.c", directory: "/")
+!7 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper", size: 256, elements: !{!10})
+!8 = !DIGlobalVariableExpression(var: !9, expr: !DIExpression())
+!9 = distinct !DIGlobalVariable(name: "w", scope: !2, type: !7, isLocal: false, isDefinition: true)
+!10 = !DIDerivedType(tag: DW_TAG_member, name: "value", scope: !7, baseType: !5, size: 256)
+!11 = !DIGlobalVariableExpression(var: !12, expr: !DIExpression())
+!12 = distinct !DIGlobalVariable(name: "ok", scope: !2, type: !13, isLocal: false, isDefinition: true)
+!13 = !DIBasicType(name: "float", size: 32, encoding: DW_ATE_float)
diff --git a/llvm/test/CodeGen/X86/BTF/wide-opaque-enum.ll b/llvm/test/CodeGen/X86/BTF/wide-opaque-enum.ll
new file mode 100644
index 00000000000000..95d856d365c1db
--- /dev/null
+++ b/llvm/test/CodeGen/X86/BTF/wide-opaque-enum.ll
@@ -0,0 +1,22 @@
+; RUN: llc -mtriple=x86_64-linux-gnu %s -o - | FileCheck %s --implicit-check-not='BTF_KIND_ENUM' --implicit-check-not='BTF_KIND_STRUCT'
+; CHECK: BTF_KIND_FLOAT
+
+ at w = global i128 0, !dbg !8
+ at e = global i128 0, !dbg !0
+ at ok = global float 0.0, !dbg !11
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!3, !4}
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "e", scope: !2, type: !5, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !6, emissionKind: FullDebug, globals: !{!8, !0, !11})
+!3 = !{i32 2, !"Debug Info Version", i32 3}
+!4 = !{i32 7, !"BTF", i32 1}
+!5 = !DICompositeType(tag: DW_TAG_enumeration_type, name: "E", size: 128, flags: DIFlagFwdDecl)
+!6 = !DIFile(filename: "test.cc", directory: "/")
+!7 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper", size: 128, elements: !{!10})
+!8 = !DIGlobalVariableExpression(var: !9, expr: !DIExpression())
+!9 = distinct !DIGlobalVariable(name: "w", scope: !2, type: !7, isLocal: false, isDefinition: true)
+!10 = !DIDerivedType(tag: DW_TAG_member, name: "member", scope: !7, baseType: !5, size: 128)
+!11 = !DIGlobalVariableExpression(var: !12, expr: !DIExpression())
+!12 = distinct !DIGlobalVariable(name: "ok", scope: !2, type: !13, isLocal: false, isDefinition: true)
+!13 = !DIBasicType(name: "float", size: 32, encoding: DW_ATE_float)
More information about the cfe-commits
mailing list