Skip to content

[clangd] Introduce --skip-preamble-build command line option - #189284

Merged
ArcsinX merged 4 commits into
llvm:mainfrom
ArcsinX:skip-preamble-build
Apr 16, 2026
Merged

ArcsinX merged 4 commits into
llvm:mainfrom
ArcsinX:skip-preamble-build

Conversation

@ArcsinX

@ArcsinX ArcsinX commented Mar 29, 2026 •

Copy link
Copy Markdown
Member

This option allows to disable preamble optimization in clangd. By default it's false, but became true for TUs which import modules (and experimental modules support is enabled).

This PR is a try to address C++20 modules problems described here #187432
Fixes #181770

This option allows to disable preamble optimization in clangd.
By default it's false, but became true if experimental modules support is enabled.
@llvmbot

llvmbot commented Mar 29, 2026 •

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-clang-tools-extra

@llvm/pr-subscribers-clangd

Author: Aleksandr Platonov (ArcsinX)

Changes

This option allows to disable preamble optimization in clangd. By default it's false, but became true if experimental modules support is enabled.

This PR is a try to address C++20 modules problems described here #187432

Set to WIP because no tests were added yet.
@ChuanqiXu9 can you please take a look, is this solutions is acceptable to you? For me this fixes all crashes related to including headers with import inside


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

8 Files Affected:

  • (modified) clang-tools-extra/clangd/ClangdServer.cpp (+3)
  • (modified) clang-tools-extra/clangd/ClangdServer.h (+5)
  • (modified) clang-tools-extra/clangd/CodeComplete.cpp (+6-2)
  • (modified) clang-tools-extra/clangd/Compiler.h (+2)
  • (modified) clang-tools-extra/clangd/ParsedAST.cpp (+1-1)
  • (modified) clang-tools-extra/clangd/Preamble.cpp (+20-7)
  • (modified) clang-tools-extra/clangd/Preamble.h (+4)
  • (modified) clang-tools-extra/clangd/tool/ClangdMain.cpp (+18)
diff --git a/clang-tools-extra/clangd/ClangdServer.cpp b/clang-tools-extra/clangd/ClangdServer.cpp
index f1a87dd12d905..af80cc9c3e453 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -223,6 +223,7 @@ ClangdServer::ClangdServer(const GlobalCompilationDatabase &CDB,
       UseDirtyHeaders(Opts.UseDirtyHeaders),
       LineFoldingOnly(Opts.LineFoldingOnly),
       PreambleParseForwardingFunctions(Opts.PreambleParseForwardingFunctions),
+      SkipPreambleBuild(Opts.SkipPreambleBuild),
       ImportInsertions(Opts.ImportInsertions),
       PublishInactiveRegions(Opts.PublishInactiveRegions),
       WorkspaceRoot(Opts.WorkspaceRoot),
@@ -300,6 +301,7 @@ void ClangdServer::addDocument(PathRef File, llvm::StringRef Contents,
   std::string ActualVersion = DraftMgr.addDraft(File, Version, Contents);
   ParseOptions Opts;
   Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions;
+  Opts.SkipPreambleBuild = SkipPreambleBuild;
   Opts.ImportInsertions = ImportInsertions;
 
   // Compile command is set asynchronously during update, as it can be slow.
@@ -459,6 +461,7 @@ void ClangdServer::codeComplete(PathRef File, Position Pos,
         Config::current().Completion.HeaderInsertion;
     CodeCompleteOpts.CodePatterns = Config::current().Completion.CodePatterns;
     CodeCompleteOpts.MacroFilter = Config::current().Completion.MacroFilter;
+    ParseInput.Opts.SkipPreambleBuild = SkipPreambleBuild;
     // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
     // both the old and the new version in case only one of them matches.
     CodeCompleteResult Result = clangd::codeComplete(
diff --git a/clang-tools-extra/clangd/ClangdServer.h b/clang-tools-extra/clangd/ClangdServer.h
index 3ffaf67553dce..6ee1dfd863e3c 100644
--- a/clang-tools-extra/clangd/ClangdServer.h
+++ b/clang-tools-extra/clangd/ClangdServer.h
@@ -191,6 +191,9 @@ class ClangdServer {
     // If true, parse emplace-like functions in the preamble.
     bool PreambleParseForwardingFunctions = true;
 
+    // If true, skip preamble build.
+    bool SkipPreambleBuild = false;
+
     /// Whether include fixer insertions for Objective-C code should use #import
     /// instead of #include.
     bool ImportInsertions = false;
@@ -508,6 +511,8 @@ class ClangdServer {
 
   bool PreambleParseForwardingFunctions = true;
 
+  bool SkipPreambleBuild = false;
+
   bool ImportInsertions = false;
 
   bool PublishInactiveRegions = false;
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp
index 28f81cd5267d5..8414ffe20526a 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -1420,7 +1420,8 @@ bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
   // overriding the preamble will break sema completion. Fortunately we can just
   // skip all includes in this case; these completions are really simple.
   PreambleBounds PreambleRegion =
-      ComputePreambleBounds(CI->getLangOpts(), *ContentsBuffer, 0);
+      computePreambleBounds(CI->getLangOpts(), *ContentsBuffer,
+                            Input.ParseInput.Opts.SkipPreambleBuild);
   bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
                               (!PreambleRegion.PreambleEndsAtStartOfLine &&
                                Input.Offset == PreambleRegion.Size);
@@ -1433,7 +1434,10 @@ bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
   if (Input.Preamble.StatCache)
     VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
   auto Clang = prepareCompilerInstance(
-      std::move(CI), !CompletingInPreamble ? &Input.Preamble.Preamble : nullptr,
+      std::move(CI),
+      (!CompletingInPreamble && !Input.ParseInput.Opts.SkipPreambleBuild)
+          ? &Input.Preamble.Preamble
+          : nullptr,
       std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
   Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
   Clang->setCodeCompletionConsumer(Consumer.release());
diff --git a/clang-tools-extra/clangd/Compiler.h b/clang-tools-extra/clangd/Compiler.h
index e513e4c40794a..5e5e23d5b9682 100644
--- a/clang-tools-extra/clangd/Compiler.h
+++ b/clang-tools-extra/clangd/Compiler.h
@@ -43,6 +43,8 @@ struct ParseOptions {
   bool PreambleParseForwardingFunctions = true;
 
   bool ImportInsertions = false;
+
+  bool SkipPreambleBuild = false;
 };
 
 /// Information required to run clang, e.g. to parse AST or do code completion.
diff --git a/clang-tools-extra/clangd/ParsedAST.cpp b/clang-tools-extra/clangd/ParsedAST.cpp
index 4e873f1257a17..e2a49f384a3e9 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -464,7 +464,7 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
     Patch->apply(*CI);
   }
   auto Clang = prepareCompilerInstance(
-      std::move(CI), PreamblePCH,
+      std::move(CI), Inputs.Opts.SkipPreambleBuild ? nullptr : PreamblePCH,
       llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, Filename), VFS,
       *DiagConsumer);
 
diff --git a/clang-tools-extra/clangd/Preamble.cpp b/clang-tools-extra/clangd/Preamble.cpp
index f5e512793e98e..58da7edcf3b93 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -320,8 +320,9 @@ struct ScannedPreamble {
 /// running preprocessor over \p Contents. Returned includes do not contain
 /// resolved paths. \p Cmd is used to build the compiler invocation, which might
 /// stat/read files.
-llvm::Expected<ScannedPreamble>
-scanPreamble(llvm::StringRef Contents, const tooling::CompileCommand &Cmd) {
+llvm::Expected<ScannedPreamble> scanPreamble(llvm::StringRef Contents,
+                                             const tooling::CompileCommand &Cmd,
+                                             bool SkipPreambleBuild) {
   class EmptyFS : public ThreadsafeFS {
   private:
     llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> viewImpl() const override {
@@ -345,7 +346,8 @@ scanPreamble(llvm::StringRef Contents, const tooling::CompileCommand &Cmd) {
   // This means we're scanning (though not preprocessing) the preamble section
   // twice. However, it's important to precisely follow the preamble bounds used
   // elsewhere.
-  auto Bounds = ComputePreambleBounds(CI->getLangOpts(), *ContentsBuffer, 0);
+  auto Bounds = computePreambleBounds(CI->getLangOpts(), *ContentsBuffer,
+                                      SkipPreambleBuild);
   auto PreambleContents = llvm::MemoryBuffer::getMemBufferCopy(
       llvm::StringRef(PI.Contents).take_front(Bounds.Size));
   auto Clang = prepareCompilerInstance(
@@ -576,7 +578,8 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
   // without those.
   auto ContentsBuffer =
       llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
-  auto Bounds = ComputePreambleBounds(CI.getLangOpts(), *ContentsBuffer, 0);
+  auto Bounds = computePreambleBounds(CI.getLangOpts(), *ContentsBuffer,
+                                      Inputs.Opts.SkipPreambleBuild);
 
   trace::Span Tracer("BuildPreamble");
   SPAN_ATTACH(Tracer, "File", FileName);
@@ -722,7 +725,8 @@ bool isPreambleCompatible(const PreambleData &Preamble,
                           const CompilerInvocation &CI) {
   auto ContentsBuffer =
       llvm::MemoryBuffer::getMemBuffer(Inputs.Contents, FileName);
-  auto Bounds = ComputePreambleBounds(CI.getLangOpts(), *ContentsBuffer, 0);
+  auto Bounds = computePreambleBounds(CI.getLangOpts(), *ContentsBuffer,
+                                      Inputs.Opts.SkipPreambleBuild);
   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
   return compileCommandsAreEqual(Inputs.CompileCommand,
                                  Preamble.CompileCommand) &&
@@ -785,13 +789,15 @@ PreamblePatch PreamblePatch::create(llvm::StringRef FileName,
   // - If scanning for Modified fails, cannot figure out newly added ones so
   //   there's nothing to do but generate an empty patch.
   auto BaselineScan =
-      scanPreamble(Baseline.Preamble.getContents(), Modified.CompileCommand);
+      scanPreamble(Baseline.Preamble.getContents(), Modified.CompileCommand,
+                   Modified.Opts.SkipPreambleBuild);
   if (!BaselineScan) {
     elog("Failed to scan baseline of {0}: {1}", FileName,
          BaselineScan.takeError());
     return PreamblePatch::unmodified(Baseline);
   }
-  auto ModifiedScan = scanPreamble(Modified.Contents, Modified.CompileCommand);
+  auto ModifiedScan = scanPreamble(Modified.Contents, Modified.CompileCommand,
+                                   Modified.Opts.SkipPreambleBuild);
   if (!ModifiedScan) {
     elog("Failed to scan modified contents of {0}: {1}", FileName,
          ModifiedScan.takeError());
@@ -957,5 +963,12 @@ OptionalFileEntryRef PreamblePatch::getPatchEntry(llvm::StringRef MainFilePath,
   auto PatchFilePath = getPatchName(MainFilePath);
   return SM.getFileManager().getOptionalFileRef(PatchFilePath);
 }
+
+PreambleBounds computePreambleBounds(const LangOptions &LangOpts,
+                                     const llvm::MemoryBufferRef &Buffer,
+                                     bool SkipPreambleBuild) {
+  return SkipPreambleBuild ? PreambleBounds(0, false)
+                           : ComputePreambleBounds(LangOpts, Buffer, 0);
+}
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/Preamble.h b/clang-tools-extra/clangd/Preamble.h
index 7f2eb233ee1aa..2051930dae05d 100644
--- a/clang-tools-extra/clangd/Preamble.h
+++ b/clang-tools-extra/clangd/Preamble.h
@@ -239,6 +239,10 @@ class PreamblePatch {
   MainFileMacros PatchedMacros;
 };
 
+PreambleBounds computePreambleBounds(const LangOptions &LangOpts,
+                                     const llvm::MemoryBufferRef &Buffer,
+                                     bool SkipPreambleBuild);
+
 } // namespace clangd
 } // namespace clang
 
diff --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index 54af3662470db..7bedf83be14ac 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -525,6 +525,14 @@ opt<bool> PreambleParseForwardingFunctions{
     init(ParseOptions().PreambleParseForwardingFunctions),
 };
 
+opt<bool> SkipPreambleBuild{
+    "skip-preamble-build",
+    cat(Misc),
+    desc("If ture, skip preamble build"),
+    Hidden,
+    init(ParseOptions().SkipPreambleBuild),
+};
+
 #if defined(__GLIBC__) && CLANGD_MALLOC_TRIM
 opt<bool> EnableMallocTrim{
     "malloc-trim",
@@ -1005,6 +1013,16 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var
   }
   Opts.UseDirtyHeaders = UseDirtyHeaders;
   Opts.PreambleParseForwardingFunctions = PreambleParseForwardingFunctions;
+  if (ExperimentalModulesSupport &&
+      SkipPreambleBuild.getNumOccurrences() == 0) {
+    Opts.SkipPreambleBuild = true;
+    log("Experimental C++20 modules support is enabled. This leads to "
+        "disabling preamble build due to instability of mixed precompiled "
+        "headers and C++20 modules. To enable C++20 modules together with "
+        "preamble builds, pass --skip-preamble-build=false command line "
+        "option");
+  } else
+    Opts.SkipPreambleBuild = SkipPreambleBuild;
   Opts.ImportInsertions = ImportInsertions;
   Opts.QueryDriverGlobs = std::move(QueryDriverGlobs);
   Opts.TweakFilter = [&](const Tweak &T) {

@ArcsinX ArcsinX changed the title [wip][clangd] Introduce --skip-preamble-build command line options [wip][clangd] Introduce --skip-preamble-build command line option Mar 29, 2026
@ArcsinX
ArcsinX marked this pull request as draft March 29, 2026 20:48

@ChuanqiXu9 ChuanqiXu9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But in the current impl, for module units containing headers, how can clangd detect the change in the included header for the module units?

@ArcsinX

ArcsinX commented Mar 30, 2026 •

Copy link
Copy Markdown
Member Author

But in the current impl, for module units containing headers, how can clangd detect the change in the included header for the module units?

I checked, for me this scenario works correctly. I used example provided here #181770:

  • modifications of exported structure (added field)
  • add an include at the end of M.cppm

Behavior should be the same as for includes, which are outside the preamble section (e.g. include directive in the middle of the file), so I believe everything should be ok.

@ChuanqiXu9

Copy link
Copy Markdown
Member

But in the current impl, for module units containing headers, how can clangd detect the change in the included header for the module units?

I checked, for me this scenario works correctly. I used example provided here #181770:

  • modifications of exported structure (added field)
  • add an include at the end of M.cppm

No, the example in my mind is,

// header.h
#pragma once
constexpr int vvv = 43;
module;
#include "header.h"
export module m;
export constexpr int mm = vvv;

We should be able to see the mm's value as 43. And after we change the value to 44 or 45 in header.h, we should be able to see mm's value be the corresponding value.

Behavior should be the same as for includes, which are outside the preamble section (e.g. include directive in the middle of the file), so I believe everything should be ok.

No, modules have different mechanism. We can't assume header will have similar affect. But after all, the mechanism comes from the canReuse interface from the preamble. And now you just simply not building the preamble, I believe the canReuse interface will stop working and clangd won't detect the changes.

@ArcsinX

ArcsinX commented Mar 30, 2026

Copy link
Copy Markdown
Member Author

But in the current impl, for module units containing headers, how can clangd detect the change in the included header for the module units?

I checked, for me this scenario works correctly. I used example provided here #181770:

  • modifications of exported structure (added field)
  • add an include at the end of M.cppm

No, the example in my mind is,

// header.h
#pragma once
constexpr int vvv = 43;
module;
#include "header.h"
export module m;
export constexpr int mm = vvv;

We should be able to see the mm's value as 43. And after we change the value to 44 or 45 in header.h, we should be able to see mm's value be the corresponding value.

Tried this example, and it works ok for me.

Maybe you can just check this patch to make sure?

No, modules have different mechanism. We can't assume header will have similar affect. But after all, the mechanism comes from the canReuse interface from the preamble. And now you just simply not building the preamble, I believe the canReuse interface will stop working and clangd won't detect the changes.

I mean that without this patch we can add #include header.h in the middle of the file and I believe this should be ok, If not, we need to investigate this (but for me it works)

@ChuanqiXu9

Copy link
Copy Markdown
Member

But in the current impl, for module units containing headers, how can clangd detect the change in the included header for the module units?

I checked, for me this scenario works correctly. I used example provided here #181770:

  • modifications of exported structure (added field)
  • add an include at the end of M.cppm

No, the example in my mind is,

// header.h
#pragma once
constexpr int vvv = 43;
module;
#include "header.h"
export module m;
export constexpr int mm = vvv;

We should be able to see the mm's value as 43. And after we change the value to 44 or 45 in header.h, we should be able to see mm's value be the corresponding value.

Tried this example, and it works ok for me.

Maybe you can just check this patch to make sure?

I just tried and it doesn't work. And also it is weird that it works as it literally violates the abstraction of canReuse() feature. If clangd is able to detect change, why do we have canReuse() ?

No, modules have different mechanism. We can't assume header will have similar affect. But after all, the mechanism comes from the canReuse interface from the preamble. And now you just simply not building the preamble, I believe the canReuse interface will stop working and clangd won't detect the changes.

I mean that without this patch we can add #include header.h in the middle of the file and I believe this should be ok, If not, we need to investigate this (but for me it works)

I failed to understand what you want to say. If we change the file by adding a new #include, of course, it should change. But I guess you're talking about something different?

@ArcsinX

ArcsinX commented Mar 30, 2026 •

Copy link
Copy Markdown
Member Author

I failed to understand what you want to say. If we change the file by adding a new #include, of course, it should change. But I guess you're talking about something different?

If we have headers from your example

And one more extra

Test.h

import m;

main.cpp is

#include "Dummy.h"

int dummy; // we cut preamble here

#include "Test.h"

int a = mm; 

If this works correctly without this patch, then

#include "Test.h"

int a = mm; 

also should be ok with --skip-preamble-build=true

For me at vvv modifications, hover at mm shows correct modified value.

@ChuanqiXu9

Copy link
Copy Markdown
Member

I failed to understand what you want to say. If we change the file by adding a new #include, of course, it should change. But I guess you're talking about something different?

If we have headers from your example

And one more extra

Test.h

import m;

main.cpp is

#include "Dummy.h"

int dummy; // we cut preamble here

#include "Test.h"

int a = mm; 

If this works correctly without this patch, then

#include "Test.h"

int a = mm; 

also should be ok with --skip-preamble-build=true

I failed to understand your intention with the example. Why do you think this is a problem? I didn't think about this

For me at vvv modifications, hover at mm shows correct modified value.

I just tried it:

image

The source code is here: https://github.com/alibaba/async_simple/tree/CXX20Modules

And the reason why I think the current approach is problematic is, the current approach simply breaks the design of the CanReuse interface. I can't believe it can work properly with the CanReuse interface otherwise we should remove CanReuse.

@ArcsinX

ArcsinX commented Mar 30, 2026 •

Copy link
Copy Markdown
Member Author

I failed to understand your intention with the example. Why do you think this is a problem? I didn't think about this

I am just trying to say, that If we support includes in the middle of the file (I believe we must), then this patch should works correctly, because roughly speaking it acts like we have an empty preamble and all headers are in the middle of the file.

So, if scenarios with includes in the middle of the file doesn't work for you, we need to investigate this first.

For me at vvv modifications, hover at mm shows correct modified value.

I just tried it:

The source code is here: https://github.com/alibaba/async_simple/tree/CXX20Modules

And the reason why I think the current approach is problematic is, the current approach simply breaks the design of the CanReuse interface. I can't believe it can work properly with the CanReuse interface otherwise we should remove CanReuse.

With this patch preamble is empty, in general it doesn't matter can it be reused it or not, because all includes are in the file body and not a part of preamble.
Can you please provide a minimal example to reproduce the problem? Currently I have no plans to download repos to check this. You provided examples above an with this I don't see any problems and can't see the reason why this can't work

@ChuanqiXu9

Copy link
Copy Markdown
Member

The simplest example can't work

image
[
  {
    "directory": "/disk2/workspace.xuchuanqi/llvm-project-for-work/llvm-project-for-work/build/clangd_example",
    "file": "m.cppm",
    "command": "clang++ -std=c++20 -c m.cppm"
  }
]

With this patch preamble is empty, in general it doesn't matter can it be reused it or not, because all includes are in the file body and not a part of preamble.

The question is, when the included header changes, how can clangd detect that?

@ArcsinX

ArcsinX commented Mar 30, 2026

Copy link
Copy Markdown
Member Author

The simplest example can't work

image ``` [ { "directory": "/disk2/workspace.xuchuanqi/llvm-project-for-work/llvm-project-for-work/build/clangd_example", "file": "m.cppm", "command": "clang++ -std=c++20 -c m.cppm" } ] ```

With this patch preamble is empty, in general it doesn't matter can it be reused it or not, because all includes are in the file body and not a part of preamble.

The question is, when the included header changes, how can clangd detect that?

Oh, now I see the problem.

  • mm doesn't show correct value if we are using hove in m.cppm,
  • but mm shows correct value if we are in a source file which imports m.

But, as I can say, if I make
m.cppm to be

module;
export module M;
#include "header.h"
export constexpr int mm = vvv;

This also doesn't work as you expect. So, I think this is is not a problem of this patch.

@ChuanqiXu9

ChuanqiXu9 commented Mar 30, 2026 •

Copy link
Copy Markdown
Member

The simplest example can't work
image

[
  {
    "directory": "/disk2/workspace.xuchuanqi/llvm-project-for-work/llvm-project-for-work/build/clangd_example",
    "file": "m.cppm",
    "command": "clang++ -std=c++20 -c m.cppm"
  }
]

With this patch preamble is empty, in general it doesn't matter can it be reused it or not, because all includes are in the file body and not a part of preamble.

The question is, when the included header changes, how can clangd detect that?

Oh, now I see the problem.

  • mm doesn't show correct value if we are using hove in m.cppm,
  • but mm shows correct value if we are in a source file which imports m.

But, as I can say, if I make m.cppm to be

module;
export module M;
#include "header.h"
export constexpr int mm = vvv;

This also doesn't work as you expect. So, I think this is is not a problem of this patch.

No, this is definitely the problem of this patch. The original example works well before the patch and not working after the patch. You can't really say an invariant of the problem exists too so it is not your problem.

And also the variant you made is actually not by design of C++20 modules. Headers should belong to the global module fragments. This is by design. Attaching headers to module purview may be warned: https://godbolt.org/z/3rTM19r9P

And even besides modules, again, this patch breaks the CanReuse functionality of preamble. This is why I said we can't do so.

@ArcsinX

ArcsinX commented Mar 30, 2026 •

Copy link
Copy Markdown
Member Author

No, this is definitely the problem of this patch. The original example works well before the patch and not working after the patch. You can't really say an invariant of the problem exists too so it is not your problem.

I think clangd should reparse opened files, when dependent file changes (independent of is this include happens in preamble section or not). In this case clangd doesn't do this if include is not in the preamble section, so this looks like another problem.

This patch introduces ability to avoid preamble build and I think this works as expected. But yes, we found some problem cases but these problems have different origin. Anyway, this is just an option, which can be disabled/enabled.

And also the variant you made is actually not by design of C++20 modules. Inclusion in module purview will be warned.

I don't see any compilation warnings. Anyway, I think there can be other legal ways to make includes to be in the middle of the file.

And even besides modules, again, this patch breaks the CanReuse functionality of preamble. This is why I said we can't do so.

As I said previously, it doesn't not, because we actually don't build the preamble, so we can say that we don't have the preamble and CanReuse functionality is out of scope here.

This solution provides ability to fix crashes (at least for me, because #187432 is not enough and still I faced crashes at preamble index update with that patch) and just a try to help you to improve stability of c++20 modules support in clangd. If this is not acceptable for you because of the reasons above (which I believe have different origin), maybe it's better to fix the problem in clang itself, as far as all we try to do here is to find a workaround for clang bugs.

@ArcsinX

ArcsinX commented Mar 30, 2026

Copy link
Copy Markdown
Member Author

Headers should belong to the global module fragments. This is by design. Attaching headers to module purview may be warned: https://godbolt.org/z/3rTM19r9P

But here we have no warnings https://godbolt.org/z/xPeohsMEf

@ChuanqiXu9

Copy link
Copy Markdown
Member

Headers should belong to the global module fragments. This is by design. Attaching headers to module purview may be warned: https://godbolt.org/z/3rTM19r9P

But here we have no warnings https://godbolt.org/z/xPeohsMEf

This is just some implementation choices. By design, the original legacy headers should be in GMF for sure.

@ChuanqiXu9

Copy link
Copy Markdown
Member

I think clangd should reparse opened files, when dependent file changes (independent of is this include happens in preamble section or not). In this case clangd doesn't do this if include is not in the preamble section, so this looks like another problem.

This patch introduces ability to avoid preamble build and I think this works as expected. But yes, we found some problem cases but these problems have different origin. Anyway, this is just an option, which can be disabled/enabled.

If you think this is a missing feature, and the current patch introduces some problems but acceptable as modules support are experimental and we will add the feature back in the feature. Let's add them in document. And I think we can land this.

@ArcsinX

ArcsinX commented Mar 30, 2026

Copy link
Copy Markdown
Member Author

I think clangd should reparse opened files, when dependent file changes (independent of is this include happens in preamble section or not). In this case clangd doesn't do this if include is not in the preamble section, so this looks like another problem.
This patch introduces ability to avoid preamble build and I think this works as expected. But yes, we found some problem cases but these problems have different origin. Anyway, this is just an option, which can be disabled/enabled.

If you think this is a missing feature, and the current patch introduces some problems but acceptable as modules support are experimental and we will add the feature back in the feature. Let's add them in document. And I think we can land this.

Returning to your concern. I found that reparsing of opened files is based on preamble and this was on purpose because it was more simple to implement (just check if preamble is compatible with previous one or not). That's why this doesn't work for include directives in the middle of the file (and for our case when we don't build preamble) 596b63a (related issue clangd/clangd#107 )

So, if we decide to go with this patch, I think we have the following options:

  • we can always report that preamble is incompatible if we skip preamble build (just add a check into isPreambleCompatible() and return false). This will lead to all opened files reparsing at any file save.
  • keep this as is

In any case I think we need to file an issue about this problem (with a header inclusion which is outside of the preamble bounds). And this can be fixed with a check at a file save: if this file is in include structure of an opened file or not (needs additional investigation, but I think this should not be very hard)

@ChuanqiXu9

Copy link
Copy Markdown
Member

I think clangd should reparse opened files, when dependent file changes (independent of is this include happens in preamble section or not). In this case clangd doesn't do this if include is not in the preamble section, so this looks like another problem.
This patch introduces ability to avoid preamble build and I think this works as expected. But yes, we found some problem cases but these problems have different origin. Anyway, this is just an option, which can be disabled/enabled.

If you think this is a missing feature, and the current patch introduces some problems but acceptable as modules support are experimental and we will add the feature back in the feature. Let's add them in document. And I think we can land this.

Returning to your concern. I found that reparsing of opened files is based on preamble and this was on purpose because it was more simple to implement (just check if preamble is compatible with previous one or not). That's why this doesn't work for include directives in the middle of the file (and for our case when we don't build preamble) 596b63a (related issue clangd/clangd#107 )

So, if we decide to go with this patch, I think we have the following options:

  • we can always report that preamble is incompatible if we skip preamble build (just add a check into isPreambleCompatible() and return false). This will lead to all opened files reparsing at any file save.

This seems unacceptable.

  • keep this as is

At least for modules, it is not so bad. At least support for modules in clangd is still experimental.

In any case I think we need to file an issue about this problem (with a header inclusion which is outside of the preamble bounds). And this can be fixed with a check at a file save: if this file is in include structure of an opened file or not (needs additional investigation, but I think this should not be very hard)

Yes, it is an existing issue that the files not belong to the preamble are not watched. And we need another fix for it.

@ArcsinX

ArcsinX commented Apr 1, 2026

Copy link
Copy Markdown
Member Author
  • keep this as is

At least for modules, it is not so bad. At least support for modules in clangd is still experimental.

I am going to polish this PR (at least add some tests) in the nearest future, after that we review and/or merge it.

In any case I think we need to file an issue about this problem (with a header inclusion which is outside of the preamble bounds). And this can be fixed with a check at a file save: if this file is in include structure of an opened file or not (needs additional investigation, but I think this should not be very hard)

Yes, it is an existing issue that the files not belong to the preamble are not watched. And we need another fix for it.

Created issue for this #189804

@ArcsinX ArcsinX changed the title [wip][clangd] Introduce --skip-preamble-build command line option [clangd] Introduce --skip-preamble-build command line option Apr 5, 2026
@ArcsinX
ArcsinX marked this pull request as ready for review April 5, 2026 14:22
@ArcsinX
ArcsinX requested a review from HighCommander4 April 5, 2026 14:22
@ArcsinX

ArcsinX commented Apr 5, 2026

Copy link
Copy Markdown
Member Author

I've added test (based on tests from #187432 ) and now this is ready for review.
In this test we check that when we skip preamble build:

@ChuanqiXu9 ChuanqiXu9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to record our conclusion somewhere in clangd's release notes: "We introduced a regression that clangd can't detect the changes in headers for TU containing import in some cases. The original change detection mechanism (it can't detect changes not in preamble) already has some problems. We plan to fix it in the future. We did this to modules now as the PCH and C++20 named module don't work well and may introduce bad crashes randomly.". You can change the wording if you like.

@ArcsinX

ArcsinX commented Apr 12, 2026

Copy link
Copy Markdown
Member Author

We need to record our conclusion somewhere in clangd's release notes: "We introduced a regression that clangd can't detect the changes in headers for TU containing import in some cases. The original change detection mechanism (it can't detect changes not in preamble) already has some problems. We plan to fix it in the future. We did this to modules now as the PCH and C++20 named module don't work well and may introduce bad crashes randomly.". You can change the wording if you like.

Maybe we can do this before the release? But if you're sure we won't fix this clang problem before the next release, I'd be happy to add this information into release notes now.

@ChuanqiXu9 ChuanqiXu9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Let's land it. Thank you very much.

@ArcsinX

ArcsinX commented Apr 14, 2026

Copy link
Copy Markdown
Member Author

LGTM. Let's land it. Thank you very much.

Thanks for review, I'll land this in two days to make sure nobody has any concerns

@ArcsinX
ArcsinX merged commit 982f736 into llvm:main Apr 16, 2026
8 checks passed
alexfh pushed a commit to alexfh/llvm-project that referenced this pull request Apr 18, 2026
…9284)

This option allows to disable preamble optimization in clangd. By
default it's false, but became true for TUs which import modules (and
experimental modules support is enabled).

This PR is a try to address C++20 modules problems described here
llvm#187432
Fixes llvm#181770
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[clangd] import from #include not working

3 participants