[llvm] [MC][DWARF] Compare effective paths for root file reuse (PR #231067)

via llvm-commits llvm-commits at lists.llvm.org
Sun Oct 11 21:49:24 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-debuginfo

@llvm/pr-subscribers-llvm-mc

Author: Ben Silver (silver-ben)

<details>
<summary>Changes</summary>

DWARF5 file zero can name the compilation unit source with an absolute filename while a source location names the same file using a directory and relative filename. `MCDwarfLineTableHeader::tryGetFile` currently compares only the filename and checksum. This can create a duplicate line-table entry for the same file and can incorrectly reuse file zero for a different file with the same basename.

Compare lexical effective paths using the compilation directory, file directory, and filename while retaining checksum equality. Preserve file zero's spelling and embedded source. Reuse file zero only during automatic file-number allocation. Explicit assembler `.file` numbers remain allocated so `.loc` directives can refer to them.

The comparison does not perform filesystem lookup, symlink resolution, dot-dot simplification, or home-directory expansion. Windows separators are compared consistently when the path has Windows absolute syntax.

The MC unit tests cover equivalent and distinct paths, checksums, foreign path styles, explicit file-number aliases, and DWARF4 behavior. The assembler test references an explicit root-file alias and checks that its number remains in the emitted line table.

Validation on a macOS Release build with assertions and the X86 backend:

- 44 MC unit tests passed. One WebAssembly disassembler test was skipped because that backend was not built.
- Four DWARF4 and DWARF5 object and assembly checks for `dwarf-file0.s` passed.
- `dbg-file-name.ll` and `file-index-across-cu.ll` passed their focused checks.
- A fresh object from the minimal IR reproducer passed `llvm-dwarfdump --verify` with no warnings or errors. The unmodified backend had emitted a duplicate file warning for this input.

Windows-host execution was not performed.

Related: #<!-- -->72027.

OpenAI Codex assisted with investigation, implementation, tests and preparation of this description.


---
Full diff: https://github.com/llvm/llvm-project/pull/231067.diff


3 Files Affected:

- (modified) llvm/lib/MC/MCDwarf.cpp (+41-6) 
- (modified) llvm/test/MC/ELF/dwarf-file0.s (+8-1) 
- (modified) llvm/unittests/MC/DwarfLineTables.cpp (+88) 


``````````diff
diff --git a/llvm/lib/MC/MCDwarf.cpp b/llvm/lib/MC/MCDwarf.cpp
index da8e057f0f9ee..040530d13004c 100644
--- a/llvm/lib/MC/MCDwarf.cpp
+++ b/llvm/lib/MC/MCDwarf.cpp
@@ -635,12 +635,45 @@ MCDwarfLineTable::tryGetFile(StringRef &Directory, StringRef &FileName,
                            FileNumber);
 }
 
-static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
-                       StringRef &FileName,
+static SmallString<256> getDwarfFilePath(StringRef CompilationDir,
+                                         StringRef Directory,
+                                         StringRef FileName) {
+  // Debug paths need not originate on the host running this producer.
+  auto IsAbsolute = [](StringRef Path) {
+    return sys::path::is_absolute(Path, sys::path::Style::posix) ||
+           sys::path::is_absolute(Path, sys::path::Style::windows);
+  };
+  StringRef Base = IsAbsolute(FileName)    ? FileName
+                  : IsAbsolute(Directory) ? Directory
+                                          : CompilationDir;
+  auto Style = sys::path::Style::native;
+  if (sys::path::is_absolute(Base, sys::path::Style::posix))
+    Style = sys::path::Style::posix;
+  else if (sys::path::is_absolute(Base, sys::path::Style::windows))
+    Style = sys::path::Style::windows_slash;
+
+  SmallString<256> Path;
+  if (IsAbsolute(FileName)) {
+    Path = FileName;
+  } else {
+    if (!IsAbsolute(Directory))
+      Path = CompilationDir;
+    sys::path::append(Path, Style, Directory, FileName);
+  }
+  // Normalize Windows separators only; backslashes are valid POSIX filenames.
+  if (sys::path::is_style_windows(Style))
+    llvm::replace(Path, '\\', '/');
+  return Path;
+}
+
+static bool isRootFile(const MCDwarfFile &RootFile, StringRef CompilationDir,
+                       StringRef Directory, StringRef FileName,
                        std::optional<MD5::MD5Result> Checksum) {
-  if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName)
+  if (RootFile.Name.empty() || RootFile.Checksum != Checksum)
     return false;
-  return RootFile.Checksum == Checksum;
+  // Keep the root spelling required by DWARF, but compare the effective paths.
+  return getDwarfFilePath(CompilationDir, "", RootFile.Name) ==
+         getDwarfFilePath(CompilationDir, Directory, FileName);
 }
 
 Expected<unsigned>
@@ -661,9 +694,11 @@ MCDwarfLineTableHeader::tryGetFile(StringRef &Directory, StringRef &FileName,
     trackMD5Usage(Checksum.has_value());
     HasAnySource |= Source.has_value();
   }
-  if (DwarfVersion >= 5 && isRootFile(RootFile, Directory, FileName, Checksum))
-    return 0;
   if (FileNumber == 0) {
+    // Explicit assembler file numbers may be referenced by .loc directives.
+    if (DwarfVersion >= 5 &&
+        isRootFile(RootFile, CompilationDir, Directory, FileName, Checksum))
+      return 0;
     // File numbers start with 1 and/or after any file numbers
     // allocated by inline-assembler .file directives.
     FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
diff --git a/llvm/test/MC/ELF/dwarf-file0.s b/llvm/test/MC/ELF/dwarf-file0.s
index d7d796b7ba775..d412019609539 100644
--- a/llvm/test/MC/ELF/dwarf-file0.s
+++ b/llvm/test/MC/ELF/dwarf-file0.s
@@ -10,6 +10,8 @@
         .file 0 "/test" "root.cpp"
         .file 1 "/include" "header.h"
         .file 2 "/test" "root.cpp"
+        .text
+        .loc 2 1 0
 # CHECK:       include_directories[  0] = "/test"
 # CHECK-NEXT:  include_directories[  1] = "/include"
 # CHECK:       file_names[  0]:
@@ -19,6 +21,11 @@
 # CHECK-NEXT:             name: "header.h"
 # CHECK-NEXT:        dir_index: 1
 
+# CHECK:       file_names[  2]:
+# CHECK-NEXT:             name: "root.cpp"
+# CHECK-NEXT:        dir_index: 0
+
 # ASM:     .file 0 "/test" "root.cpp"
 # ASM:     .file 1 "/include" "header.h"
-# ASM-NOT: .file
+# ASM:     .file 2 "root.cpp"
+# ASM:     .loc 2 1 0
diff --git a/llvm/unittests/MC/DwarfLineTables.cpp b/llvm/unittests/MC/DwarfLineTables.cpp
index f687d48a989b4..fefedfcf8a71b 100644
--- a/llvm/unittests/MC/DwarfLineTables.cpp
+++ b/llvm/unittests/MC/DwarfLineTables.cpp
@@ -184,3 +184,91 @@ TEST(DwarfLineTables, TestCustomParams2) {
                                dwarf::DW_LNS_copy};
   verifyEncoding(Params, 248, 0, Encoding0);
 }
+
+
+TEST(DwarfLineTables, RootFilePathIdentity) {
+  struct Case {
+    const char *Root;
+    const char *Directory;
+    const char *Name;
+    unsigned Expected;
+  };
+  const Case Cases[] = {
+      {"/build/src/a.c", "/build/src", "a.c", 0},
+      {"/build/src/a.c", "src", "a.c", 0},
+      {"/build/src/a.c", "", "src/a.c", 0},
+      {"src/a.c", "", "/build/src/a.c", 0},
+      {"a.c", "", "a.c", 0},
+      {"a.c", "/build", "a.c", 0},
+      {"a.c", "/other", "a.c", 1},
+      {"a.c", "other", "a.c", 1},
+      {"/build/a.c", "/ignored", "/build/a.c", 0},
+      {"C:\\build\\a.c", "/ignored", "C:\\build\\a.c", 0},
+  };
+  for (const auto &C : Cases) {
+    SCOPED_TRACE(C.Root);
+    SCOPED_TRACE(C.Directory);
+    SCOPED_TRACE(C.Name);
+    MCDwarfLineTableHeader Header;
+    Header.setRootFile("/build", C.Root, std::nullopt, "source text");
+    StringRef Directory = C.Directory, Name = C.Name;
+    EXPECT_EQ(C.Expected, cantFail(Header.tryGetFile(
+                              Directory, Name, std::nullopt, "source text", 5)));
+    // Root spelling and embedded source must survive deduplication.
+    EXPECT_EQ(C.Root, Header.RootFile.Name);
+    EXPECT_EQ("source text", *Header.RootFile.Source);
+  }
+}
+
+TEST(DwarfLineTables, RootFileForeignPathStyles) {
+  MCDwarfLineTableHeader Header;
+  Header.setRootFile("C:\\build", "C:/build/src/a.c", std::nullopt, std::nullopt);
+  StringRef Directory = "src", Name = "a.c";
+  EXPECT_EQ(0u, cantFail(Header.tryGetFile(Directory, Name, std::nullopt,
+                                         std::nullopt, 5)));
+  Directory = "C:\\other\\src";
+  Name = "a.c";
+  EXPECT_EQ(1u, cantFail(Header.tryGetFile(Directory, Name, std::nullopt,
+                                         std::nullopt, 5)));
+
+  // A backslash in a POSIX path is a character, not a separator.
+  MCDwarfLineTableHeader Posix;
+  Posix.setRootFile("/build", "/build/a\\b.c", std::nullopt, std::nullopt);
+  Directory = "/build/a";
+  Name = "b.c";
+  EXPECT_EQ(1u, cantFail(Posix.tryGetFile(Directory, Name, std::nullopt,
+                                        std::nullopt, 5)));
+}
+
+TEST(DwarfLineTables, RootFileChecksumIdentity) {
+  MD5::MD5Result First{}, Second{};
+  Second[0] = 1;
+  for (std::optional<MD5::MD5Result> Checksum :
+       {std::optional<MD5::MD5Result>(First),
+        std::optional<MD5::MD5Result>(Second), std::optional<MD5::MD5Result>()}) {
+    MCDwarfLineTableHeader Header;
+    Header.setRootFile("/build", "/build/a.c", First, std::nullopt);
+    StringRef Directory = "/build", Name = "a.c";
+    EXPECT_EQ(Checksum == First ? 0u : 1u,
+              cantFail(Header.tryGetFile(Directory, Name, Checksum,
+                                         std::nullopt, 5)));
+  }
+}
+
+TEST(DwarfLineTables, ExplicitRootFileAliasKeepsItsNumber) {
+  MCDwarfLineTableHeader Header;
+  Header.setRootFile("/build", "a.c", std::nullopt, std::nullopt);
+  StringRef Directory = "/build", Name = "a.c";
+  EXPECT_EQ(1u, cantFail(Header.tryGetFile(Directory, Name, std::nullopt,
+                                          std::nullopt, 5, 1)));
+  ASSERT_EQ(2u, Header.MCDwarfFiles.size());
+  EXPECT_EQ("a.c", Header.MCDwarfFiles[1].Name);
+}
+
+TEST(DwarfLineTables, DWARF4DoesNotReuseFileZero) {
+  MCDwarfLineTableHeader Header;
+  Header.setRootFile("/build", "/build/a.c", std::nullopt, std::nullopt);
+  StringRef Directory = "/build", Name = "a.c";
+  EXPECT_EQ(1u, cantFail(Header.tryGetFile(Directory, Name, std::nullopt,
+                                          std::nullopt, 4)));
+}

``````````

</details>


https://github.com/llvm/llvm-project/pull/231067


More information about the llvm-commits mailing list