llvmbot wrote:

<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang-driver

Author: Can H. Tartanoglu (caniko)

<details>
<summary>Changes</summary>

## Summary

This makes LLVM's BTF debug info emission work for any ELF target, not just 
BPF. The Clang driver gains a new `-gbtf` flag (matching GCC) that causes the 
compiler to emit `.BTF` and `.BTF.ext` sections directly from IR debug metadata 
— no `pahole` step required.

Companion to #<!-- -->183915 which adds BTF merging/dedup in lld. Together they 
enable native BTF for Linux kernel builds with Clang, including LTO + Rust 
configurations where pahole's DWARF→BTF conversion currently breaks.

## What's here

**BTFDebug split** — the existing monolithic `BTFDebug` (1800 lines in 
`lib/Target/BPF/`) is split into:
- **Target-independent base** (`llvm/include/llvm/CodeGen/BTFDebug.h`, 
`llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp`) — all type visiting from IR debug 
metadata, string table, `.BTF` section emission, `.BTF.ext` FuncInfo + LineInfo 
subsections, global variable processing. No target dependencies.
- **BPF subclass** (`BPFBTFDebug` in `lib/Target/BPF/`) — CO-RE field 
relocations, `.maps` section handling, BPF instruction lowering 
(`InstLower()`). These are BPF-only concepts.

**Clang driver** — `-gbtf` flag that:
- Implies debug info (LimitedDebugInfo if none specified)
- Implies DWARF generation (BTF reads the same IR metadata)
- Sets a `"BTF"` module flag, read by the backend

**AsmPrinter integration** — the base `AsmPrinter::doInitialization()` 
instantiates `BTFDebug` when it sees `getBTFFlag() &amp;&amp; 
isOSBinFormatELF() &amp;&amp; !isBPF() &amp;&amp; hasDebugInfo()`. BPF keeps 
using its own `BPFBTFDebug` through `BPFAsmPrinter`. BTF and DWARF coexist — 
both consume IR metadata independently, same as CodeView + DWARF on Windows.

**Tests**:
- 7 X86 BTF lit tests (`llvm/test/CodeGen/X86/BTF/`): int, struct, enum, func, 
global-var, no-flag gating, BTF+DWARF coexistence
- Clang driver test (`clang/test/Driver/gbtf.c`): flag forwarding, debug info 
implication, negative case
- Clang codegen test (`clang/test/CodeGen/btf-module-flag.c`): module flag 
emission
- 104/104 existing BPF BTF lit tests pass unchanged

## Motivation

The kernel's Kconfig has:
```
config RUST
    depends on !DEBUG_INFO_BTF || (PAHOLE_HAS_LANG_EXCLUDE &amp;&amp; !LTO)
```

`DEBUG_INFO_BTF=y` depends on pahole for DWARF→BTF conversion, which is slow, 
fragile with LTO, and doesn't handle Rust well. With compiler-emitted BTF + lld 
merging (#<!-- -->183915), the pahole dependency goes away and this Kconfig 
restriction can be lifted.

## Design notes

The trickiest part of the split was preserving string table ordering. BPF's 
`beginInstruction()` processes CO-RE relocations (adding type name strings) 
*before* constructing line info (adding filename/line strings). The refactored 
base class calls a `processBeginInstruction()` virtual hook before line info, 
so BPF's string ordering is preserved and all 104 existing tests pass without 
modification.

For non-BPF targets, `.BTF.ext` only contains FuncInfo and LineInfo — no 
FieldReloc subsection, since CO-RE is a BPF-only concept.

I'd appreciate review from @<!-- -->yonghong-song and @<!-- -->eddyz87 on the 
BTFDebug split — the BPF subclass should be functionally identical to the 
original code.

cc @<!-- -->4ast @<!-- -->anakryiko

---

Patch is 75.17 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/183929.diff


24 Files Affected:

- (modified) clang/include/clang/Basic/DebugOptions.def (+3) 
- (modified) clang/include/clang/Options/Options.td (+4) 
- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+4) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+15) 
- (added) clang/test/CodeGen/btf-module-flag.c (+11) 
- (added) clang/test/Driver/gbtf.c (+27) 
- (renamed) llvm/include/llvm/CodeGen/BTFDebug.h (+29-29) 
- (modified) llvm/include/llvm/IR/Module.h (+3) 
- (modified) llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp (+8) 
- (renamed) llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp (+27-355) 
- (modified) llvm/lib/CodeGen/AsmPrinter/CMakeLists.txt (+2) 
- (modified) llvm/lib/IR/Module.cpp (+7) 
- (modified) llvm/lib/Target/BPF/BPFAsmPrinter.cpp (+3-3) 
- (modified) llvm/lib/Target/BPF/BPFAsmPrinter.h (+2-2) 
- (added) llvm/lib/Target/BPF/BPFBTFDebug.cpp (+313) 
- (added) llvm/lib/Target/BPF/BPFBTFDebug.h (+66) 
- (modified) llvm/lib/Target/BPF/CMakeLists.txt (+1-1) 
- (added) llvm/test/CodeGen/X86/BTF/btf-with-dwarf.ll (+33) 
- (added) llvm/test/CodeGen/X86/BTF/enum.ll (+59) 
- (added) llvm/test/CodeGen/X86/BTF/func.ll (+73) 
- (added) llvm/test/CodeGen/X86/BTF/global-var.ll (+68) 
- (added) llvm/test/CodeGen/X86/BTF/int.ll (+42) 
- (added) llvm/test/CodeGen/X86/BTF/no-btf-flag.ll (+28) 
- (added) llvm/test/CodeGen/X86/BTF/struct.ll (+70) 


``````````diff
diff --git a/clang/include/clang/Basic/DebugOptions.def 
b/clang/include/clang/Basic/DebugOptions.def
index 604e87e615a69..73e1dfb4e4c23 100644
--- a/clang/include/clang/Basic/DebugOptions.def
+++ b/clang/include/clang/Basic/DebugOptions.def
@@ -116,6 +116,9 @@ 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 coexist with DWARF.
+DEBUGOPT(EmitBTF, 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 1021d95e4005b..9a2e61d30a870 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -4978,6 +4978,10 @@ 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">, Group<g_Group>,
+  HelpText<"Generate BTF debug information">,
+  Visibility<[ClangOption, CC1Option, CC1AsOption]>,
+  MarshallingInfoFlag<CodeGenOpts<"EmitBTF">>;
 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 c31bcabe49016..614c2c31534c1 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1138,6 +1138,10 @@ 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::Warning, "BTF", 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 7e544bd1042ea..02dd263e59d7b 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4480,6 +4480,18 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, 
const llvm::Triple &T,
   if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
     EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
 
+  bool EmitBTF = false;
+  if (const Arg *A = Args.getLastArg(options::OPT_gbtf))
+    EmitBTF = checkDebugInfoOption(A, Args, D, TC);
+
+  // BTF reads IR debug metadata, which requires DWARF generation.
+  if (EmitBTF) {
+    if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo)
+      DebugInfoKind = llvm::codegenoptions::LimitedDebugInfo;
+    if (!EmitDwarf)
+      EmitDwarf = true;
+  }
+
   // If the user asked for debug info but did not explicitly specify -gcodeview
   // or -gdwarf, ask the toolchain for the default format.
   if (!EmitCodeView && !EmitDwarf &&
@@ -4624,6 +4636,9 @@ renderDebugOptions(const ToolChain &TC, const Driver &D, 
const llvm::Triple &T,
                        options::OPT_gno_codeview_command_line);
   }
 
+  if (EmitBTF)
+    CmdArgs.push_back("-gbtf");
+
   Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
                      options::OPT_gno_inline_line_tables);
 
diff --git a/clang/test/CodeGen/btf-module-flag.c 
b/clang/test/CodeGen/btf-module-flag.c
new file mode 100644
index 0000000000000..cf9fdb2c76704
--- /dev/null
+++ b/clang/test/CodeGen/btf-module-flag.c
@@ -0,0 +1,11 @@
+// Verify that -gbtf sets the "BTF" module flag in LLVM IR.
+//
+// RUN: %clang -target x86_64-linux-gnu -gbtf -g -S -emit-llvm -o - %s \
+// RUN:   | FileCheck %s --check-prefix=BTF
+// RUN: %clang -target x86_64-linux-gnu -g -S -emit-llvm -o - %s \
+// RUN:   | FileCheck %s --check-prefix=NO-BTF
+
+// BTF: !{i32 2, !"BTF", i32 1}
+// 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 0000000000000..6fd25ceb95d95
--- /dev/null
+++ b/clang/test/Driver/gbtf.c
@@ -0,0 +1,27 @@
+// Test the -gbtf flag behavior in the Clang driver.
+//
+// -gbtf forwards to cc1.
+// RUN: %clang -target x86_64-linux-gnu -gbtf -### %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=BTF %s
+//
+// -gbtf alone implies debug info (LimitedDebugInfo).
+// RUN: %clang -target x86_64-linux-gnu -gbtf -### %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=BTF-DEBUGINFO %s
+//
+// -gbtf with explicit -g also works.
+// RUN: %clang -target x86_64-linux-gnu -g -gbtf -### %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=BTF %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
+//
+// -gbtf works on aarch64 too (any ELF target).
+// RUN: %clang -target aarch64-linux-gnu -gbtf -### %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=BTF %s
+
+// BTF: "-gbtf"
+// BTF-DEBUGINFO: "-debug-info-kind=
+// NO-BTF-NOT: "-gbtf"
+
+int main(void) { return 0; }
diff --git a/llvm/lib/Target/BPF/BTFDebug.h 
b/llvm/include/llvm/CodeGen/BTFDebug.h
similarity index 90%
rename from llvm/lib/Target/BPF/BTFDebug.h
rename to llvm/include/llvm/CodeGen/BTFDebug.h
index 75858fcc8bfde..925af5d2f8eed 100644
--- a/llvm/lib/Target/BPF/BTFDebug.h
+++ b/llvm/include/llvm/CodeGen/BTFDebug.h
@@ -1,4 +1,4 @@
-//===- BTFDebug.h -----------------------------------------------*- C++ 
-*-===//
+//===- BTFDebug.h - BTF Debug Info 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.
@@ -9,10 +9,15 @@
 /// \file
 /// This file contains support for writing BTF debug info.
 ///
+/// BTF (BPF Type Format) is a compact debug info format originally designed
+/// for BPF programs but useful for any ELF target. This target-independent
+/// implementation can be used by any backend to emit .BTF and .BTF.ext
+/// sections.
+///
 
//===----------------------------------------------------------------------===//
 
-#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/StringMap.h"
 #include "llvm/CodeGen/DebugHandlerBase.h"
@@ -53,7 +58,7 @@ class BTFTypeBase {
   virtual uint32_t getSize() { return BTF::CommonTypeSize; }
   /// Complete BTF type generation after all related DebugInfo types
   /// have been visited so their BTF type id's are available
-  /// for cross referece.
+  /// for cross reference.
   virtual void completeType(BTFDebug &BDebug) {}
   /// Emit types for this BTF type entry.
   virtual void emitType(MCStreamer &OS);
@@ -286,13 +291,17 @@ struct BTFFieldReloc {
 };
 
 /// Collect and emit BTF information.
+///
+/// This is a target-independent base class that handles the core BTF
+/// generation from LLVM IR debug metadata. Target-specific backends
+/// (e.g., BPF) can subclass this to add features like CO-RE relocations.
 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;
   std::unordered_map<const DIType *, uint32_t> DIToIdMap;
@@ -303,11 +312,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::set<const Function *> ProtoFunctions;
   std::map<const DICompositeType *,
            std::vector<std::pair<const DIDerivedType *, BTFTypeDerived *>>>
       FixupDerivedTypes;
-  std::set<const Function *>ProtoFunctions;
 
   /// Add types to TypeEntries.
   /// @{
@@ -336,7 +344,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.
@@ -351,14 +358,13 @@ class BTFDebug : public DebugHandlerBase {
                          uint32_t Column);
 
   /// Generate types and variables for globals.
-  void processGlobals(bool ProcessingMapDef);
+  virtual void processGlobals();
 
-  /// Process global variable initializer in pursuit for function
-  /// pointers.
+  /// Scan a global variable initializer for function references.
   void processGlobalInitializer(const Constant *C);
 
-  /// Generate types for function prototypes.
-  void processFuncPrototypes(const Function *);
+  /// Generate BTF types for extern function prototypes.
+  void processFuncPrototypes(const Function *F);
 
   /// Generate types for decl annotations.
   void processDeclAnnotations(DINodeArray Annotations, uint32_t BaseTypeId,
@@ -368,24 +374,12 @@ class BTFDebug : public DebugHandlerBase {
   uint32_t processDISubprogram(const DISubprogram *SP, uint32_t ProtoTypeId,
                                uint8_t Scope);
 
-  /// Generate BTF type_tag's. If BaseTypeId is nonnegative, the last
-  /// BTF type_tag in the chain points to BaseTypeId. Otherwise, it points to
-  /// the base type of DTy. Return the type id of the first BTF type_tag
-  /// in the chain. If no type_tag's are generated, a negative value
-  /// is returned.
+  /// Generate BTF type_tag's.
   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();
 
@@ -393,7 +387,7 @@ class BTFDebug : public DebugHandlerBase {
   void emitBTFSection();
 
   /// Emit the .BTF.ext section.
-  void emitBTFExtSection();
+  virtual void emitBTFExtSection();
 
 protected:
   /// Gather pre-function debug information.
@@ -405,8 +399,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() {
@@ -425,6 +419,12 @@ class BTFDebug : public DebugHandlerBase {
     return DIToIdMap[Ty];
   }
 
+  /// Called at the beginning of instruction processing, before line info.
+  /// Subclasses can override to handle target-specific instruction processing
+  /// (e.g., CO-RE relocations) that must add strings to the string table
+  /// before line info strings.
+  virtual void processBeginInstruction(const MachineInstr *MI) {}
+
   /// Process beginning of an instruction.
   void beginInstruction(const MachineInstr *MI) override;
 
diff --git a/llvm/include/llvm/IR/Module.h b/llvm/include/llvm/IR/Module.h
index 7156a83c9f3cc..dfaf80c9560d4 100644
--- a/llvm/include/llvm/IR/Module.h
+++ b/llvm/include/llvm/IR/Module.h
@@ -908,6 +908,9 @@ 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;
+
 /// @}
 /// @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 083b83567e47f..e38d481473c2f 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -11,6 +11,7 @@
 
//===----------------------------------------------------------------------===//
 
 #include "llvm/CodeGen/AsmPrinter.h"
+#include "llvm/CodeGen/BTFDebug.h"
 #include "CodeViewDebug.h"
 #include "DwarfDebug.h"
 #include "DwarfException.h"
@@ -645,6 +646,13 @@ bool AsmPrinter::doInitialization(Module &M) {
         Handlers.push_back(std::unique_ptr<DwarfDebug>(DD));
       }
     }
+    // Emit BTF debug info if requested (via -gbtf). BTF can coexist with
+    // DWARF — both consume the same IR debug metadata independently.
+    // Only for ELF targets (BTF uses ELF sections). BPF target handles
+    // BTF emission through its own AsmPrinter with BPFBTFDebug.
+    if (M.getBTFFlag() && Target.isOSBinFormatELF() &&
+        !Target.isBPF() && hasDebugInfo())
+      Handlers.push_back(std::make_unique<BTFDebug>(this));
   }
 
   if (M.getNamedMetadata(PseudoProbeDescMetadataName))
diff --git a/llvm/lib/Target/BPF/BTFDebug.cpp 
b/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
similarity index 74%
rename from llvm/lib/Target/BPF/BTFDebug.cpp
rename to llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
index 46a1df28b8f1d..2a6879384e022 100644
--- a/llvm/lib/Target/BPF/BTFDebug.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/BTFDebug.cpp
@@ -6,19 +6,19 @@
 //
 
//===----------------------------------------------------------------------===//
 //
-// This file contains support for writing BTF debug info.
+// This file contains the target-independent implementation of BTF debug info
+// generation. It handles converting LLVM IR debug metadata into BTF type
+// information and emitting .BTF and .BTF.ext ELF sections.
 //
 
//===----------------------------------------------------------------------===//
 
-#include "BTFDebug.h"
-#include "BPF.h"
-#include "BPFCORE.h"
-#include "MCTargetDesc/BPFMCTargetDesc.h"
+#include "llvm/CodeGen/BTFDebug.h"
 #include "llvm/BinaryFormat/Dwarf.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/CodeGen/AsmPrinter.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/MachineOperand.h"
+#include "llvm/IR/Constants.h"
 #include "llvm/IR/Module.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCObjectFileInfo.h"
@@ -29,6 +29,7 @@
 #include "llvm/Support/LineIterator.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Target/TargetLoweringObjectFile.h"
+#include "llvm/Target/TargetMachine.h"
 #include <optional>
 
 using namespace llvm;
@@ -38,12 +39,12 @@ static const char *BTFKindStr[] = {
 #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);
-  if (DerivedTy && DerivedTy->getTag() == dwarf::DW_TAG_atomic_type)
-    return DerivedTy->getBaseType();
+  if (auto *DerivedTy = dyn_cast<DIDerivedType>(Ty))
+    if (DerivedTy->getTag() == dwarf::DW_TAG_atomic_type)
+      return DerivedTy->getBaseType();
   return Ty;
 }
 
@@ -101,13 +102,6 @@ void BTFTypeDerived::completeType(BTFDebug &BDebug) {
   case BTF::BTF_KIND_CONST:
   case BTF::BTF_KIND_VOLATILE:
   case BTF::BTF_KIND_RESTRICT:
-    // Debug info might contain names for these types, but given that we want
-    // to keep BTF minimal and naming reference types doesn't bring any value
-    // (what matters is the completeness of the base type), we don't emit them.
-    //
-    // Furthermore, the Linux kernel refuses to load BPF programs that contain
-    // BTF with these types named:
-    // https://elixir.bootlin.com/linux/v6.17.1/source/kernel/bpf/btf.c#L2586
     BTFType.NameOff = 0;
     break;
   default:
@@ -119,7 +113,7 @@ void BTFTypeDerived::completeType(BTFDebug &BDebug) {
     return;
 
   // The base type for PTR/CONST/VOLATILE could be void.
-  const DIType *ResolvedType = tryRemoveAtomicType(DTy->getBaseType());
+  const DIType *ResolvedType = 
BTFDebug::tryRemoveAtomicType(DTy->getBaseType());
   if (!ResolvedType) {
     assert((Kind == BTF::BTF_KIND_PTR || Kind == BTF::BTF_KIND_CONST ||
             Kind == BTF::BTF_KIND_VOLATILE) &&
@@ -322,14 +316,6 @@ void BTFTypeStruct::completeType(BTFDebug &BDebug) {
   BTFType.NameOff = BDebug.addString(STy->getName());
 
   if (STy->getTag() == dwarf::DW_TAG_variant_part) {
-    // Variant parts might have a discriminator, which has its own memory
-    // location, and variants, which share the memory location afterwards. LLVM
-    // DI doesn't consider discriminator as an element and instead keeps
-    // it as a separate reference.
-    // To keep BTF simple, let's represent the structure as an union with
-    // discriminator as the first element.
-    // The offsets inside variant types are already handled correctly in the
-    // DI.
     const auto *DTy = STy->getDiscriminator();
     if (DTy) {
       struct BTF::BTFMember Discriminator;
@@ -359,7 +345,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;
     }
@@ -390,11 +376,6 @@ void BTFTypeStruct::emitType(MCStreamer &OS) {
 
 std::string BTFTypeStruct::getName() { return std::string(STy->getName()); }
 
-/// The Func kind represents both subprogram and pointee of function
-/// pointers. If the FuncName is empty, it represents a pointee of function
-/// pointer. Otherwise, it represents a subprogram. The func arg names
-/// are empty for pointee of function pointer case, and are valid names
-/// for subprogram.
 BTFTypeFuncProto::BTFTypeFuncProto(
     const DISubroutineType *STy, uint32_t VLen,
     const std::unordered_map<uint32_t, StringRef> &FuncArgNames)
@@ -409,15 +390,13 @@ void BTFTypeFuncProto::completeType(BTFDebug &BDebug) {
   IsCompleted = true;
 
   DITypeArray Elements = STy->getTypeArray();
-  auto RetType = tryRemoveAtomicType(Elements[0]);
+  auto RetType = BTFDebug::tryRemoveAtomicType(Elements[0]);
   BTFType.Type = RetType ? BDebug.getTypeId(RetType) : 0;
   BTFType.NameOff = 0;
 
-  // For null parameter which is typically the last one
-  // to represent the vararg, encode the NameOff/Type to be 0.
   for (unsigned I = 1, N = Elements.size(); I < N; ++I) {
     struct BTF::BTFParam Param;
-    auto Element = tryRemoveAtomicType(Elements[I]);
+    auto Element = BTFDebug::tryRemoveAtomicType(Elements[I]);
     if (Element) {
       Param.NameOff = BDebug.addString(FuncArgNames[I]);
       Param.Type = BDebug.getTypeId(Element);
@@ -550,7 +529,7 @@ 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
@@ -574,8 +553,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");
 }
 
@@ -605,8 +583,6 @@ void BTFDebug::visitBasicType(const DIBasicType *BTy, 
uint32_t &TypeId) {
   case dwarf::DW_ATE_signed_char:
   case dwarf::DW_ATE_unsigned:
   case dwarf::DW_ATE_unsigned_char:
-    // 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;
@@ -631,10 +607,6 @@ void BTFDebug::visitSubroutineType(
   if (VLen > BTF::MAX_VLEN)
     return;
 
-  // Subprogram has a valid non-zero-length name, and t...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/183929
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to