Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[clang-repl] Extend the C support. #89804

Merged
merged 1 commit into from
May 21, 2024
Merged

Conversation

vgvassilev
Copy link
Contributor

The IdResolver chain is the main way for C to implement lookup rules. Every new partial translation unit caused clang to exit the top-most scope which in turn cleaned up the IdResolver chain. That was not an issue for C++ because its lookup is implemented on the level of declaration contexts.

This patch keeps the IdResolver chain across partial translation units maintaining proper C-style lookup infrastructure.

@llvmbot llvmbot added clang Clang issues not falling into any other category clang:frontend Language frontend issues, e.g. anything involving "Sema" labels Apr 23, 2024
@llvmbot
Copy link
Member

llvmbot commented Apr 23, 2024

@llvm/pr-subscribers-clang

Author: Vassil Vassilev (vgvassilev)

Changes

The IdResolver chain is the main way for C to implement lookup rules. Every new partial translation unit caused clang to exit the top-most scope which in turn cleaned up the IdResolver chain. That was not an issue for C++ because its lookup is implemented on the level of declaration contexts.

This patch keeps the IdResolver chain across partial translation units maintaining proper C-style lookup infrastructure.


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

3 Files Affected:

  • (modified) clang/lib/Interpreter/IncrementalParser.cpp (+11-2)
  • (modified) clang/lib/Sema/SemaDecl.cpp (+2-1)
  • (added) clang/test/Interpreter/execute.c (+21)
diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp
index ef90fe9e6f5451..f1cb5fc870eb94 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -387,8 +387,7 @@ std::unique_ptr<llvm::Module> IncrementalParser::GenModule() {
 
 void IncrementalParser::CleanUpPTU(PartialTranslationUnit &PTU) {
   TranslationUnitDecl *MostRecentTU = PTU.TUPart;
-  TranslationUnitDecl *FirstTU = MostRecentTU->getFirstDecl();
-  if (StoredDeclsMap *Map = FirstTU->getPrimaryContext()->getLookupPtr()) {
+  if (StoredDeclsMap *Map = MostRecentTU->getPrimaryContext()->getLookupPtr()) {
     for (auto &&[Key, List] : *Map) {
       DeclContextLookupResult R = List.getLookupResult();
       std::vector<NamedDecl *> NamedDeclsToRemove;
@@ -407,6 +406,16 @@ void IncrementalParser::CleanUpPTU(PartialTranslationUnit &PTU) {
       }
     }
   }
+
+  // FIXME: We should de-allocate MostRecentTU
+  for (Decl *D : MostRecentTU->decls()) {
+    if (!isa<NamedDecl>(D))
+      continue;
+    // Check if we need to clean up the IdResolver chain.
+    NamedDecl *ND = cast<NamedDecl>(D);
+    if (ND->getDeclName().getFETokenInfo())
+      getCI()->getSema().IdResolver.RemoveDecl(ND);
+  }
 }
 
 llvm::StringRef IncrementalParser::GetMangledName(GlobalDecl GD) const {
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 452e00fa32b102..2a0f73b42d3088 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2282,7 +2282,8 @@ void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
 
     // Remove this name from our lexical scope, and warn on it if we haven't
     // already.
-    IdResolver.RemoveDecl(D);
+    if (!PP.isIncrementalProcessingEnabled())
+      IdResolver.RemoveDecl(D);
     auto ShadowI = ShadowingDecls.find(D);
     if (ShadowI != ShadowingDecls.end()) {
       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
diff --git a/clang/test/Interpreter/execute.c b/clang/test/Interpreter/execute.c
new file mode 100644
index 00000000000000..44a3a32c930112
--- /dev/null
+++ b/clang/test/Interpreter/execute.c
@@ -0,0 +1,21 @@
+// REQUIRES: host-supports-jit
+// UNSUPPORTED: system-aix
+
+// RUN: cat %s | clang-repl -Xcc -xc -Xcc -Xclang -Xcc -verify | FileCheck %s
+// RUN: cat %s | clang-repl -Xcc -xc -Xcc -O2 -Xcc -Xclang -Xcc -verify| FileCheck %s
+int printf(const char *, ...);
+int i = 42; err // expected-error{{use of undeclared identifier}}
+int i = 42;
+struct S { float f; struct S *m;} s = {1.0, 0};
+// FIXME: Making foo inline fails to emit the function.
+int foo() { return 42; }
+void run() {                                                    \
+  printf("i = %d\n", i);                                        \
+  printf("S[f=%f, m=0x%llx]\n", s.f, (unsigned long long)s.m);  \
+  int r3 = foo();                                               \
+}
+run();
+// CHECK: i = 42
+// CHECK-NEXT: S[f=1.000000, m=0x0]
+
+%quit

Copy link
Contributor

@weliveindetail weliveindetail left a comment

Choose a reason for hiding this comment

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

I am not an expert on the behavior of IdResolver, but this patch works for me.

clang/test/Interpreter/execute.c Show resolved Hide resolved
clang/lib/Interpreter/IncrementalParser.cpp Show resolved Hide resolved
vgvassilev added a commit that referenced this pull request Apr 25, 2024
…9879)

Should fix the failure seen in the pre-merge infrastructure of #89804.
@vgvassilev
Copy link
Contributor Author

The pre-merge windows test failure in Clang :: Driver/amdgpu-toolchain.c seems unrelated to this PR.

@vgvassilev vgvassilev requested a review from AaronBallman May 10, 2024 19:43
@vgvassilev
Copy link
Contributor Author

@AaronBallman, can you take a look at that patch, hopefully to move forward as seems the other reviewers are busy.

@vgvassilev vgvassilev force-pushed the clang-repl-c branch 2 times, most recently from 72d655c to 7acf367 Compare May 20, 2024 15:49
@vgvassilev
Copy link
Contributor Author

The bots fail on windows due to TEST 'Clang :: CoverageMapping/mcdc-system-headers.cpp' FAILED which does not seem related to this PR.

The IdResolver chain is the main way for C to implement lookup rules. Every new
partial translation unit caused clang to exit the top-most scope which in turn
cleaned up the IdResolver chain. That was not an issue for C++ because its
lookup is implemented on the level of declaration contexts.

This patch keeps the IdResolver chain across partial translation units
maintaining proper C-style lookup infrastructure.
Copy link
Collaborator

@AaronBallman AaronBallman left a comment

Choose a reason for hiding this comment

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

LGTM with a possible improvement in the code (take it or leave it, your call).

Comment on lines +412 to +416
auto *ND = dyn_cast<NamedDecl>(D);
if (!ND)
continue;
// Check if we need to clean up the IdResolver chain.
if (ND->getDeclName().getFETokenInfo())
Copy link
Collaborator

Choose a reason for hiding this comment

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

As a one-liner rather than a four-liner.

if (auto *ND = dyn_cast<NamedDecl>(D);
    ND && ND->getDeclName().getFETokenInfo())

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It always good to take rather than leave ;) I haven't got used to this syntax and I'd leave it :(

@vgvassilev
Copy link
Contributor Author

The failures on windows are due to "out of heap" error. Let's land this to test on the "real" bots.

@vgvassilev vgvassilev merged commit 253c28f into llvm:main May 21, 2024
3 of 4 checks passed
@vgvassilev vgvassilev deleted the clang-repl-c branch May 21, 2024 17:21
@mysterymath
Copy link
Contributor

mysterymath commented May 21, 2024

We've started seeing crashes in Fuchsia's Mac tooclhain's LLDB test suite:
https://luci-milo.appspot.com/ui/p/fuchsia/builders/toolchain.ci/clang-mac-x64/b8747305520511321169/overview

This is the only PR in the blamelist that looks plausible, but there isn't a clear connection to me (or a clear reason why it would be Mac-only). Does anything jump out, or am I barking up the wrong tree?

EDIT: Blamelist: https://luci-milo.appspot.com/ui/p/fuchsia/builders/toolchain.ci/clang-mac-x64/b8747305520511321169/blamelist

Stack trace follows:

Assertion failed: (D->getLexicalDeclContext() == this && "Decl inserted into wrong lexical context"), function addHiddenDecl, file DeclBase.cpp, line 1692.
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace.
Stack dump:
0.	/Volumes/Work/s/w/ir/cache/macos_sdk/XCode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSZone.h:32:1 <Spelling=/Volumes/Work/s/w/ir/cache/macos_sdk/XCode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObjCRuntime.h:382:22>: at annotation token
 #0 0x0000000111461238 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x8ab238)
 #1 0x000000011145f179 llvm::sys::RunSignalHandlers() (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x8a9179)
 #2 0x0000000111461900 SignalHandler(int) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x8ab900)
 #3 0x00007ff807c915ed (/usr/lib/system/libsystem_platform.dylib+0x7ff8004255ed)
 #4 0x0000700014de4c40 
 #5 0x00007ff807b8ab45 (/usr/lib/system/libsystem_c.dylib+0x7ff80031eb45)
 #6 0x00007ff807b89e5e (/usr/lib/system/libsystem_c.dylib+0x7ff80031de5e)
 #7 0x0000000114a4ae54 clang::DeclContext::addHiddenDecl(clang::Decl*) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x3e94e54)
 #8 0x0000000114a4aeae clang::DeclContext::addDecl(clang::Decl*) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x3e94eae)
 #9 0x0000000113edeb81 clang::Sema::ActOnStartTopLevelStmtDecl(clang::Scope*) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x3328b81)
#10 0x0000000113a31ccf clang::Parser::ParseTopLevelStmtDecl() (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2e7bccf)
#11 0x0000000113a6d231 clang::Parser::ParseExternalDeclaration(clang::ParsedAttributes&, clang::ParsedAttributes&, clang::ParsingDeclSpec*) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2eb7231)
#12 0x0000000113a45202 clang::Parser::ParseLinkage(clang::ParsingDeclSpec&, clang::DeclaratorContext) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2e8f202)
#13 0x0000000113a6f037 clang::Parser::ParseDeclOrFunctionDefInternal(clang::ParsedAttributes&, clang::ParsedAttributes&, clang::ParsingDeclSpec&, clang::AccessSpecifier) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2eb9037)
#14 0x0000000113a6e8a5 clang::Parser::ParseDeclarationOrFunctionDefinition(clang::ParsedAttributes&, clang::ParsedAttributes&, clang::ParsingDeclSpec*, clang::AccessSpecifier) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2eb88a5)
#15 0x0000000113a6cfd4 clang::Parser::ParseExternalDeclaration(clang::ParsedAttributes&, clang::ParsedAttributes&, clang::ParsingDeclSpec*) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2eb6fd4)
#16 0x0000000113a6ad37 clang::Parser::ParseTopLevelDecl(clang::OpaquePtr<clang::DeclGroupRef>&, clang::Sema::ModuleImportState&) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2eb4d37)
#17 0x0000000113a6a501 clang::Parser::ParseFirstTopLevelDecl(clang::OpaquePtr<clang::DeclGroupRef>&, clang::Sema::ModuleImportState&) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2eb4501)
#18 0x0000000113956acb clang::ParseAST(clang::Sema&, bool, bool) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2da0acb)
#19 0x0000000113721a53 clang::FrontendAction::Execute() (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2b6ba53)
#20 0x000000011369068d clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2ada68d)
#21 0x000000011369cd24 void llvm::function_ref<void ()>::callback_fn<compileModuleImpl(clang::CompilerInstance&, clang::SourceLocation, llvm::StringRef, clang::FrontendInputFile, llvm::StringRef, llvm::StringRef, llvm::function_ref<void (clang::CompilerInstance&)>, llvm::function_ref<void (clang::CompilerInstance&)>)::$_1>(long) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x2ae6d24)
#22 0x000000011145c0fe llvm::CrashRecoveryContext::RunSafely(llvm::function_ref<void ()>) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x8a60fe)
#23 0x000000011145c220 RunSafelyOnThread_Dispatch(void*) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x8a6220)
#24 0x000000011145c23f void* llvm::thread::ThreadProxy<std::__2::tuple<void (*)(void*), (anonymous namespace)::RunSafelyOnThreadInfo*>>(void*) (/Volumes/Work/s/w/ir/x/w/llvm_build/lib/liblldb.19.0.0git.dylib+0x8a623f)
#25 0x00007ff807c641d3 (/usr/lib/system/libsystem_pthread.dylib+0x7ff8003f81d3)
#26 0x00007ff807c5fbd3 (/usr/lib/system/libsystem_pthread.dylib+0x7ff8003f3bd3)

jasonmolenda added a commit that referenced this pull request May 22, 2024
This reverts commit 253c28f.

This commit is causing failures on the lldb CI bots, e.g.
https://ci.swift.org/view/all/job/llvm.org/view/LLDB/job/as-lldb-cmake/4307/

On my local macOS desktop build,
```
bin/lldb-dotest -p TestImportBuiltinFileID.py
Assertion failed: (D->getLexicalDeclContext() == this && "Decl inserted into wrong lexical context"), function addHiddenDecl, file DeclBase.cpp, line 1692.

6  libsystem_c.dylib        0x0000000185f0b8d0 abort + 128
7  libsystem_c.dylib        0x0000000185f0abc8 err + 0
8  liblldb.19.0.0git.dylib  0x00000001311e5800 clang::DeclContext::addHiddenDecl(clang::Decl*) + 120
9  liblldb.19.0.0git.dylib  0x00000001311e5978 clang::DeclContext::addDecl(clang::Decl*) + 32
10 liblldb.19.0.0git.dylib  0x000000012f617b48 clang::Sema::ActOnStartTopLevelStmtDecl(clang::Scope*) + 64
11 liblldb.19.0.0git.dylib  0x000000012eaf76c8 clang::Parser::ParseTopLevelStmtDecl() + 208
12 liblldb.19.0.0git.dylib  0x000000012ec051fc clang::Parser::ParseExternalDeclaration(clang::ParsedAttributes&, clang::ParsedAttributes&, clang::ParsingDeclSpec*) + 3412
13 liblldb.19.0.0git.dylib  0x000000012ec03274 clang::Parser::ParseTopLevelDecl(clang::OpaquePtr<clang::DeclGroupRef>&, clang::Sema::ModuleImportState&) + 2020
14 liblldb.19.0.0git.dylib  0x000000012eaca860 clang::ParseAST(clang::Sema&, bool, bool) + 604
15 liblldb.19.0.0git.dylib  0x000000012e8554c0 clang::ASTFrontendAction::ExecuteAction() + 308
16 liblldb.19.0.0git.dylib  0x000000012e854c78 clang::FrontendAction::Execute() + 124
17 liblldb.19.0.0git.dylib  0x000000012e76dcfc clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) + 984
18 liblldb.19.0.0git.dylib  0x000000012e784500 compileModuleImpl(clang::CompilerInstance&, clang::SourceLocation, llvm::StringRef, clang::FrontendInputFile, llvm::StringRef, llvm::StringRef, llvm::function_ref<void (clang::CompilerInstance&)>, llvm::function_ref<void (clang::CompilerInstance&)>)::$_1::operator()() const + 52
```
Reverting until Vassil has a chance to look int oit.
@jasonmolenda
Copy link
Collaborator

I reverted in

commit dfdf1c5fe45a82b9c578306f3d7627fd251d63f8
Author: Jason Molenda <jmolenda@apple.com>
Date:   Tue May 21 18:00:11 2024 -0700

    Revert "[clang-repl] Extend the C support. (#89804)"
    
    This reverts commit 253c28fa829cee0104c2fc59ed1a958980b5138c.

to unblock the CI bots until Vassil has a chance to look at it.

@vgvassilev
Copy link
Contributor Author

I reverted in

commit dfdf1c5fe45a82b9c578306f3d7627fd251d63f8
Author: Jason Molenda <jmolenda@apple.com>
Date:   Tue May 21 18:00:11 2024 -0700

    Revert "[clang-repl] Extend the C support. (#89804)"
    
    This reverts commit 253c28fa829cee0104c2fc59ed1a958980b5138c.

to unblock the CI bots until Vassil has a chance to look at it.

Thank you! I suspect that this is due to the changes in SemaDecl.cpp (https://github.com/llvm/llvm-project/pull/89804/files#diff-edac6256ac508912a16d0165b2f8cf37123dc2f40a147dca49a34c33f1db13ddR2288)

I am trying to build lldb but if you have a hint how to reproduce it outside lldb would be great!

@vgvassilev
Copy link
Contributor Author

@jasonmolenda, I am stuck. I could not find how the bot configures llvm and lldb. I built lldb and ran make check-lldb but did not fail in the same way. Can you provide a recipe to reproduce the failure?

@mysterymath
Copy link
Contributor

I was able to verify that the revert fixed the tests at least.

@vgvassilev
Copy link
Contributor Author

@jasonmolenda, I am stuck. I could not find how the bot configures llvm and lldb. I built lldb and ran make check-lldb but did not fail in the same way. Can you provide a recipe to reproduce the failure?

For some reason it only fails on our Mac LLDB builders, and not our Linux ones. Our LLDB configuration is also quite tortured I'm afraid; it's difficult to reproduce locally. I'm not sure whether this issue would be seen on a clean Mac build; it seems like it might be some kind of pointer Heisenbug or something. I can definitely test a candidate fix, but that's about it.

I tried on a mac machine. Can I get access to that bot then?

@vgvassilev
Copy link
Contributor Author

I was able to verify that the revert fixed the tests at least.

I am pretty sure that the failure ha to do with the incremental processing if-stmt in SemaDecl. I can provide a fix that does not trigger this for lldb but that would be a workaround. I suspect that change uncovers some inconsistency in either clang or lldb which I think we should fix.

@mysterymath
Copy link
Contributor

mysterymath commented May 22, 2024

I did have a means to reproduce this locally, but it's been a long time since I've used it. I should be able to recreate the setup. I'll get back to you with the details when I can; this whole afternoon is booked through pretty solid with meetings for me I'm afraid.

EDIT: It would be a ~10 step process involving installing a bunch of Chrome tools like cipd, cas, etc. I think everything should be open source and accessible, but it's still not very straightforward. The intent is to build a version of LLVM that is kept as hermetic as possible from the host system, so there's a lot that goes into that.

@vgvassilev
Copy link
Contributor Author

Ok, maybe I can you test this patch for a temporary fix until we figure out what's going wrong.

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 7f6921ea22be..d771a060f305 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2285,7 +2285,7 @@ void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
     // Partial translation units that are created in incremental processing must
     // not clean up the IdResolver because PTUs should take into account the
     // declarations that came from previous PTUs.
-    if (!PP.isIncrementalProcessingEnabled())
+    if (!PP.isIncrementalProcessingEnabled() && !getLangOpts().IncrementalExtensions)
       IdResolver.RemoveDecl(D);
 
     // Warn on it if we are shadowing a declaration.

mysterymath added a commit to mysterymath/llvm-project that referenced this pull request May 22, 2024
@mysterymath
Copy link
Contributor

mysterymath commented May 22, 2024

This still exhibits the same issue:

https://luci-milo.appspot.com/raw/build/logs.chromium.org/fuchsia/led/dthorn_google.com/0d77d2b0963e18ad11cb83db0680c2382ed7f8df95cf733f42fcdbd1dda8a7ec/+/build.proto

https://logs.chromium.org/logs/fuchsia/led/dthorn_google.com/0d77d2b0963e18ad11cb83db0680c2382ed7f8df95cf733f42fcdbd1dda8a7ec/+/u/lldb/test/stdout

I do think it should be possible to download a "source tarball" that allows easily reproducing the output of our bots on similar host configurations, but I don't think we're quite there yet. It's an AI on our end, for sure, especially since we often catch real issues upstream that other bots don't, owing to our unusual build. I asked around what people were doing, and it involved basically replicating the bot build by hand using a ton of undocumented knowledge and manual editing; it's not something that I could export any easier than it would be to create a better way to do this.

@jasonmolenda
Copy link
Collaborator

fwiw if you have access to a mac, I don't think it's hard to build lldb+clang? I have swig, cmake, and ninja installed on my mac via homebrew.

lldb/scripts/macos-setup-codesign.sh

mkdir build
cd build
 cmake ../llvm -G Ninja -DLLDB_ENABLE_SWIFT_SUPPORT=0 -DPython3_EXECUTABLE=/usr/bin/python3 -DCMAKE_BUILD_TYPE=Debug -DLLVM_ENABLE_ASSERTIONS=1 -DLLVM_ENABLE_PROJECTS='llvm;lldb;clang' '-DLLVM_ENABLE_RUNTIMES=libcxx;libcxxabi;libunwind' -DLLDB_ENABLE_PYTHON=1 -DLLDB_ENABLE_LUA=0

ninja lldb
bin/lldb-dotest -p TestImportBuiltinFileID.py

@junaire
Copy link
Member

junaire commented May 23, 2024

Just found out this keeps popping up from my notification, and I would like give my 2 cents, maybe can provide some insights:

Looking at the backtrace of the failing tests, I noticed we ran into clang::Parser::ParseTopLevelStmtDecl() which makes me very confused. Do we actually enable the incremental extension in lldb? I grep it in lldb codebase and the only occurrence is here

The other thing I noticed is that the failure looks like have something to do with the objc, can we also check the current language we're compiling when skipping removing the name for the lexical scope?

@vgvassilev
Copy link
Contributor Author

fwiw if you have access to a mac, I don't think it's hard to build lldb+clang? I have swig, cmake, and ninja installed on my mac via homebrew.

lldb/scripts/macos-setup-codesign.sh

mkdir build
cd build
 cmake ../llvm -G Ninja -DLLDB_ENABLE_SWIFT_SUPPORT=0 -DPython3_EXECUTABLE=/usr/bin/python3 -DCMAKE_BUILD_TYPE=Debug -DLLVM_ENABLE_ASSERTIONS=1 -DLLVM_ENABLE_PROJECTS='llvm;lldb;clang' '-DLLVM_ENABLE_RUNTIMES=libcxx;libcxxabi;libunwind' -DLLDB_ENABLE_PYTHON=1 -DLLDB_ENABLE_LUA=0

ninja lldb
bin/lldb-dotest -p TestImportBuiltinFileID.py

Does not seem to be reproducing it for me:

builds/llvm-project$ bin/lldb-dotest -p TestImportBuiltinFileID.py
/Applications/Xcode.app/Contents/Developer/usr/bin/python3 /Users/vvassilev/workspace/sources/llvm-project/lldb/test/API/dotest.py --arch x86_64 --build-dir /Users/vvassilev/workspace/builds/llvm-project/lldb-test-build.noindex --executable /Users/vvassilev/workspace/builds/llvm-project/./bin/lldb --compiler /Users/vvassilev/workspace/builds/llvm-project/./bin/clang --dsymutil /Users/vvassilev/workspace/builds/llvm-project/./bin/dsymutil --lldb-libs-dir /Users/vvassilev/workspace/builds/llvm-project/./lib --llvm-tools-dir /Users/vvassilev/workspace/builds/llvm-project/./bin --libcxx-include-dir /Users/vvassilev/workspace/builds/llvm-project/include/c++/v1 --libcxx-library-dir /Users/vvassilev/workspace/builds/llvm-project/lib --lldb-obj-root /Users/vvassilev/workspace/builds/llvm-project/tools/lldb -p TestImportBuiltinFileID.py
lldb version 19.0.0git (git@github.com:llvm/llvm-project.git revision 253c28fa829cee0104c2fc59ed1a958980b5138c)
  clang revision 253c28fa829cee0104c2fc59ed1a958980b5138c
  llvm revision 253c28fa829cee0104c2fc59ed1a958980b5138c
Skipping the following test categories: ['libstdcxx', 'dwo', 'llgs', 'fork']
PASS: LLDB (/Users/vvassilev/workspace/builds/llvm-project/bin/clang-x86_64) :: test_import_builtin_fileid_gmodules (TestImportBuiltinFileID.TestImportBuiltinFileID)
----------------------------------------------------------------------
Ran 1 test in 52.311s

OK

@vgvassilev
Copy link
Contributor Author

Just found out this keeps popping up from my notification, and I would like give my 2 cents, maybe can provide some insights:

Looking at the backtrace of the failing tests, I noticed we ran into clang::Parser::ParseTopLevelStmtDecl() which makes me very confused. Do we actually enable the incremental extension in lldb? I grep it in lldb codebase and the only occurrence is here

Hm, ok. I remember some discussions revolving around this but got the impression lldb turns that off. I think having it on is the right thing to do but that explains why my workaround did not work.

The other thing I noticed is that the failure looks like have something to do with the objc, can we also check the current language we're compiling when skipping removing the name for the lexical scope?

I am hoping to cover objc, too. That's why I am really interested in figuring out what is going on. Otherwise if we limit the feature to c/c++ maybe we will get away with the bot. I still want to see why it crashes though...

@vgvassilev
Copy link
Contributor Author

@mysterymath, @jasonmolenda, ping -- I am still stuck in reproducing this issue.

@jasonmolenda
Copy link
Collaborator

I set aside my current work, updated to current main sources, cherry-picked 253c28f, built it on my macOS system, did bin/lldb-dotest -p TestImportBuiltinFileID.py and it crashes like before.

I'm not sure what you're asking help with, I don't know much of anything about how the clang setup in lldb is done - I happened to be watching the CI bots and saw they all started failing and reverted the change.

You couldn't reproduce this behavior on a macOS system? it is an arm64 macOS system, I didn't try repo'ing on an Intel box.

Earlier on this PR you mused about making this change in SemaDecl.cpp

-    if (!PP.isIncrementalProcessingEnabled())
+    if (!PP.isIncrementalProcessingEnabled() && !getLangOpts().IncrementalExtensions)

the test case still crashes for me with that change.

vgvassilev added a commit to vgvassilev/llvm-project that referenced this pull request Jun 2, 2024
vgvassilev added a commit that referenced this pull request Jun 4, 2024
Original commit message:"

[clang-repl] Extend the C support. (#89804)

The IdResolver chain is the main way for C to implement lookup rules.  Every new
partial translation unit caused clang to exit the top-most scope which in turn
cleaned up the IdResolver chain. That was not an issue for C++ because its
lookup is implemented on the level of declaration contexts.

This patch keeps the IdResolver chain across partial translation units
maintaining proper C-style lookup infrastructure.
"

It was reverted in dfdf1c5 because it broke the
bots of lldb. This failure was subtle to debug but the current model does not
work well with ObjectiveC support in lldb. This patch does cleans up the
partial translation units in ObjectiveC. In future if we want to support
ObjectiveC we need to understand what exactly lldb is doing when recovering from
errors...
@vgvassilev
Copy link
Contributor Author

@jasonmolenda, I struggled quite a bit in reproducing the test failures and everything but I have a fix. Thanks a lot for your time and I hope the fix works!

@hokein
Copy link
Collaborator

hokein commented Jun 5, 2024

@vgvassilev

The reland d999ce0 makes the clang reject the valid code now:

$ cat /tmp/t33.cpp
#include <pthread.h>
#include <algorithm>

int main() {

}
                                                                                                                                      
$  ./bin/clang -Xclang -fsyntax-only -Xclang=-fincremental-extensions -stdlib=libc++ /tmp/t33.cpp                                      <<<
In file included from /tmp/t33.cpp:2:
In file included from /usr/include/c++/v1/algorithm:1712:
In file included from /usr/include/c++/v1/memory:877:
In file included from /usr/include/c++/v1/iterator:684:
In file included from /usr/include/c++/v1/__iterator/common_iterator.h:22:
/usr/include/c++/v1/variant:1024:43: error: use of undeclared identifier '__arg'; did you mean '_pthread_cleanup_buffer::__arg'?
 1024 |       } __impl{this, _VSTD::forward<_Arg>(__arg)};
      |                                           ^
/usr/include/pthread.h:162:9: note: '_pthread_cleanup_buffer::__arg' declared here
  162 |   void *__arg;                            /* Its argument.  */
      |         ^
In file included from /tmp/t33.cpp:2:
In file included from /usr/include/c++/v1/algorithm:1861:
In file included from /usr/include/c++/v1/__algorithm/ranges_stable_partition.h:15:
/usr/include/c++/v1/__algorithm/stable_partition.h:246:18: error: use of undeclared label '__second_half_done'
  246 |             goto __second_half_done;
      |                  ^
2 errors generated.

Can you take a look?

@vgvassilev
Copy link
Contributor Author

@hokein, ah, that's annoying. Can you provide the entire proprocessed file that does not work? I'd like to bisect and debug.

@vgvassilev
Copy link
Contributor Author

vgvassilev commented Jun 5, 2024

I realize I do not entirely understand the role of the IdResolver chain in c++. Perhaps we are better of changing this line to:

    if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC)
      IdResolver.RemoveDecl(D);

to

   if (!PP.isIncrementalProcessingEnabled() || !getLangOpts().C)
     IdResolver.RemoveDecl(D);

This way will limit the scope to the actual intent without assuming the IdResolver changes are irrelevant for languages such as C++. Can you test if that works?

@hokein
Copy link
Collaborator

hokein commented Jun 5, 2024

Thanks for the prompt response. I think limiting it to C-only will fix the issue (note that there is no C in LangOpts, you may want to use !getLangOpts().CPlusPlus to exclude C++).

@vgvassilev
Copy link
Contributor Author

Thanks for the prompt response. I think limiting it to C-only will fix the issue (note that there is no C in LangOpts, you may want to use !getLangOpts().CPlusPlus to exclude C++).

Makes sense. If that works for you, we can check this in. I want to somehow record this breakage in the form of a test for our future selves when decide to revisit this workaround-looking code.

Out of curiosity, in what context you use -fincremental-extensions?

@hokein
Copy link
Collaborator

hokein commented Jun 5, 2024

Out of curiosity, in what context you use -fincremental-extensions?

The code snippet I provided is extracted from our internal test. We have an internal clang-tool (with the incremental-extensions on) to generate headers

@vgvassilev
Copy link
Contributor Author

Out of curiosity, in what context you use -fincremental-extensions?

The code snippet I provided is extracted from our internal test. We have an internal clang-tool (with the incremental-extensions on) to generate headers

I am a bit overwhelmed right now, are you willing to open a PR with that change so we can merge it -- otherwise I could look later this week :(

@hokein
Copy link
Collaborator

hokein commented Jun 5, 2024

I want to somehow record this breakage in the form of a test for our future selves when decide to revisit this workaround-looking code.

This is the processed file https://gist.github.com/hokein/e4a5881329c3956494afa2de7d350476.

I am a bit overwhelmed right now, are you willing to open a PR with that change so we can merge it -- otherwise I could look later this week :(

Sure, I will prepare one.

rupprecht added a commit to rupprecht/llvm-project that referenced this pull request Jun 5, 2024
The incremental processing mode doesn't seem to work well for C++, see the llvm#89804 (comment) for details.

This patches in llvm#94471 as well as applies some followup comments.
hokein added a commit that referenced this pull request Jun 5, 2024
The incremental processing mode doesn't seem to work well for C++, see
the
#89804 (comment)
for details.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang:frontend Language frontend issues, e.g. anything involving "Sema" clang Clang issues not falling into any other category
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants