92 Commits

Author SHA1 Message Date
Vladislav Dzhidzhoev
90691641e6
[llvm][DebugInfo] Avoid attaching retained nodes to unrelated subprograms in DIBuilder (#180294)
Fix a regression introduced by
https://github.com/llvm/llvm-project/pull/165032, where DIBuilder could
attach local metadata nodes to the wrong subprogram during finalization.

DIBuilder records freshly created local variables, labels, and types in
`DIBuilder::SubprogramTrackedNodes`, and later attaches them to their
parent subprogram's retainedNodes in `finalizeSubprogram()`.

However, a temporary local type created via
`createReplaceableCompositeType()` may later be replaced by a type with
a different scope.
DIBuilder does not currently verify that the scopes of the original and
replacement types match.

As a result, local types can be incorrectly attached to the
retainedNodes of an unrelated subprogram. This issue is observable in
clang with limited debug info mode (see
`clang/test/DebugInfo/CXX/ctor-homing-local-type.cpp`).

This patch updates `DIBuilder::finalizeSubprogram()` to verify that
tracked metadata nodes still belong to the subprogram being finalized,
and avoids adding nodes whose scopes no longer match to retainedNodes
field of an unrelated subprogram.
2026-02-09 16:23:42 +01:00
Aiden Grossman
4ec1fea922 Reapply "[Clang] Mark this pointer in destructors dead_on_return (#166276)"
This reverts commit 047db150c66e245e9df7db178b893ce6b29820f5.

The original version of the commit caused assertion failures in DSE.
Those were fixed in ec059d81aafedb253a02d6f490ad9b9747611038, so trying
to reland this again.
2026-02-08 05:00:29 +00:00
Aiden Grossman
047db150c6 Revert "[Clang] Mark this pointer in destructors dead_on_return (#166276)"
This reverts commit 278fd0553ef5834e005a048a6b480631f3fc1b38.

This was causing some buildbot failures in DSE:
1. https://lab.llvm.org/buildbot/#/builders/25/builds/15425
2. https://lab.llvm.org/buildbot/#/builders/24/builds/17304
2026-02-06 23:11:01 +00:00
Aiden Grossman
278fd0553e
[Clang] Mark this pointer in destructors dead_on_return (#166276)
This helps to clean up any dead stores that come up at the end of the
destructor. The motivating example was a refactoring in libc++'s
basic_string implementation in 8dae17be2991cd7f0d7fd9aa5aecd064520a14f6
that added a zeroing store into the destructor, causing a large
performance regression on an internal workload. We also saw a ~0.2%
performance increase on an internal server workload when enabling this.

I also tested this against all of the non-flaky tests in our large C++
codebase and found a minimal number of issues that all happened to be in
user code.
2026-02-06 14:29:29 -08:00
Vladislav Dzhidzhoev
b9cecee3fb
Reland "[DebugMetadata][DwarfDebug] Support function-local types in lexical block scopes (4/7)" (#165032)
This is an attempt to merge https://reviews.llvm.org/D144006 with LTO
fix.

The last merge attempt was
https://github.com/llvm/llvm-project/pull/75385.
The issue with it was investigated in
https://github.com/llvm/llvm-project/pull/75385#issuecomment-2386684121.
The problem happens when 
1. Several modules are being linked.
2. There are several DISubprograms that initially belong to different
modules but represent the same source code function (for example, a
function included from the same source code file).
3. Some of such DISubprograms survive IR linking. It may happen if one
of them is inlined somewhere or if the functions that have these
DISubprograms attached have internal linkage.
4. Each of these DISubprograms has a local type that corresponds to the
same source code type. These types are initially from different modules,
but have the same ODR identifier.

If the same (in the sense of ODR identifier/ODR uniquing rules) local
type is present in two modules, and these modules are linked together,
the type gets uniqued. A DIType, that happens to be loaded first,
survives linking, and the references on other types with the same ODR
identifier from the modules loaded later are replaced with the
references on the DIType loaded first. Since defintion subprograms, in
scope of which these types are located, are not deduplicated, the linker
output may contain multiple DISubprogram's having the same (uniqued)
type in their retainedNodes lists.
Further compilation of such modules causes crashes.

To tackle that,
* previous solution to handle LTO linking with local types in
retainedNodes is removed (cloneLocalTypes() function),
* for each loaded distinct (definition) DISubprogram, its retainedNodes
list is scanned after loading, and DITypes with a scope of another
subprogram are removed. If something from a Function corresponding to
the DISubprogram references uniqued type, we rely on cross-CU links.

Additionally:
* a check is added to Verifier to report about local types located in a
wrong retainedNodes list,

Original commit message follows.
---------

RFC https://discourse.llvm.org/t/rfc-dwarfdebug-fix-and-improve-handling-imported-entities-types-and-static-local-in-subprogram-and-lexical-block-scopes/68544

Similar to imported declarations, the patch tracks function-local types in
DISubprogram's 'retainedNodes' field. DwarfDebug is adjusted in accordance with
the aforementioned metadata change and provided a support of function-local
types scoped within a lexical block.

The patch assumes that DICompileUnit's 'enums field' no longer tracks local
types and DwarfDebug would assert if any locally-scoped types get placed there.

Authored-by: Kristina Bessonova <kbessonova@accesssoftek.com>
Co-authored-by: Jeremy Morse <jeremy.morse@sony.com>
2026-02-04 00:34:52 +01:00
Aiden Grossman
e2d7cd685d
[IR] Make dead_on_return attribute optionally sized
This patch makes the dead_on_return parameter attribute optionally require a number
of bytes to be passed in to specify the number of bytes known to be dead
upon function return/unwind. This is aimed at enabling annotating the
this pointer in C++ destructors with dead_on_return in clang. We need
this to handle cases like the following:

```
struct X {
  int n;
  ~X() {
    this[n].n = 0;
  }
};
void f() {
  X xs[] = {42, -1};
}
```

Where we only certain that sizeof(X) bytes are dead upon return of ~X.
Otherwise DSE would be able to eliminate the store in ~X which would not
be correct.

This patch only does the wiring within IR. Future patches will make
clang emit correct sizing information and update DSE to only delete
stores to objects marked dead_on_return that are provably in bounds of
the number of bytes specified to be dead_on_return.

Reviewers: nikic, alinas, antoniofrighetto

Pull Request: https://github.com/llvm/llvm-project/pull/171712
2026-01-21 08:22:05 -08:00
Liu Ke
be89247403
[DebugInfo] Set the DI flag for the simplified name of a template function/type (2/3). (#175708)
Set the `NameIsSimplified` flag for a template function/type that is
treated as having simplified names. Previous patch: #175130 .
Based on:
[RFC](https://discourse.llvm.org/t/rfc-debuginfo-selectively-generate-template-parameters-in-the-skeleton-cu/89395).
2026-01-14 10:53:19 +08:00
Snehasish Kumar
85b90f560d
Add a flag to preserve the old macro behaviour. (#174895)
[Clang][DebugInfo] Add a flag to use expansion loc for macro params.

This patch adds a flag to allow users to preserve the old behaviour -
use the macro expansion location for parameters. This is useful for
wider testing of sample profile driven PGO which relies on debug
information based mapping. This flag is intended to be temporary
and should be safe to remove by EOY 2026. Filed #175249 to
track the cleanup.

---------

Assisted-by: Gemini
2026-01-09 21:53:55 +00:00
Mariya Podchishchaeva
d714a6c210
Reland [MS][clang] Add support for vector deleting destructors (#170337)
This reverts commit
54a4da9df6.

MSVC supports an extension allowing to delete an array of objects via
pointer whose static type doesn't match its dynamic type. This is done
via generation of special destructors - vector deleting destructors.
MSVC's virtual tables always contain a pointer to the vector deleting
destructor for classes with virtual destructors, so not having this
extension implemented causes clang to generate code that is not
compatible with the code generated by MSVC, because clang always puts a
pointer to a scalar deleting destructor to the vtable. As a bonus the
deletion of an array of polymorphic object will work just like it does
with MSVC - no memory leaks and correct destructors are called.

This patch will cause clang to emit code that is compatible with code
produced by MSVC but not compatible with code produced with clang of
older versions, so the new behavior can be disabled via passing
-fclang-abi-compat=21 (or lower).

Fixes https://github.com/llvm/llvm-project/issues/19772
2025-12-12 09:54:32 +01:00
Bill Wendling
069d3aa923
[Clang][counted_by] Correct signed counted_by values (#171260)
If the 'counted_by' value is signed, we will incorrectly allow accesses
when the value is negative. This has obvious bad effects as it will
allow accessing a huge swath of unallocated memory.

Also clarify and rearrange the parameters to make them more
perspicuous.

Fixes: #170987.
2025-12-10 15:18:09 -08:00
Thurston Dang
75e4438b57
[ubsan] Change "Type mismatch in operation" trap reason to "Alignment, null, or object-size error" (#169752)
I originally proposed this rewording when trap reasons were introduced
in
https://github.com/llvm/llvm-project/pull/145967#discussion_r2196212344.
This was not adopted because there was a counter-proposal to split the
enum; however, that work appears to have stalled
(https://github.com/llvm/llvm-project/pull/151243). In the meantime,
there has been an additional datapoint that the current wording is
confusing to users. Thus, let's reword it now to prevent further
confusion.
2025-11-27 10:03:25 -08:00
J. Ryan Stinnett
800da10a3a
[clang][DebugInfo] Add call site debug info flag (#169574)
This adds a default enabled flag to control attachment of call site
debug info. `-gno-call-site-info` can be used to disable this feature
when needed.

This should help those concerned about debug info size in
https://github.com/llvm/llvm-project/issues/168851.
2025-11-26 12:29:54 +00:00
Zequan Wu
54a4da9df6
Revert "Reland [MS][clang] Add support for vector deleting destructors" (#169116)
This reverts 4d10c1165442cbbbc0017b48fcdd7dae1ccf3678 and its two
dependent commits: e6b9805b574bb5c90263ec7fbcb94df76d2807a4 and
c243406a695ca056a07ef4064b0f9feee7685320, see discussion in
https://github.com/llvm/llvm-project/pull/165598#issuecomment-3563825509.
2025-11-21 17:14:34 -08:00
Michael Buch
db1e73ea6d
[clang][DebugInfo] Mark _BitInt's as reconstitutable when emitting -gsimple-template-names (#168383)
Depends on:
* https://github.com/llvm/llvm-project/pull/168382

As of recent, LLVM includes the bit-size as a `DW_AT_bit_size` (and as
part of `DW_AT_name`) of `_BitInt`s in DWARF. This allows us to mark
`_BitInt`s as "reconstitutable" when compiling with
`-gsimple-template-names`. We still only omit template parameters that
are `<= 64` bit wide. So support `_BitInt`s larger than 64 bits is not
part of this patch.
2025-11-19 23:42:22 +00:00
Mariya Podchishchaeva
4d10c11654
Reland [MS][clang] Add support for vector deleting destructors (#165598)
MSVC supports an extension allowing to delete an array of objects via
pointer whose static type doesn't match its dynamic type. This is done
via generation of special destructors - vector deleting destructors.
MSVC's virtual tables always contain a pointer to the vector deleting
destructor for classes with virtual destructors, so not having this
extension implemented causes clang to generate code that is not
compatible with the code generated by MSVC, because clang always puts a
pointer to a scalar deleting destructor to the vtable. As a bonus the
deletion of an array of polymorphic object will work just like it does
with MSVC - no memory leaks and correct destructors are called.

This patch will cause clang to emit code that is compatible with code
produced by MSVC but not compatible with code produced with clang of
older versions, so the new behavior can be disabled via passing
-fclang-abi-compat=21 (or lower).

This is yet another attempt to land vector deleting destructors support
originally implemented by
https://github.com/llvm/llvm-project/pull/133451.

This PR contains fixes for issues reported in the original PR as well as
fixes for issues related to operator delete[] search reported in several
issues like

https://github.com/llvm/llvm-project/pull/133950#issuecomment-2787510484
https://github.com/llvm/llvm-project/issues/134265

Fixes https://github.com/llvm/llvm-project/issues/19772
2025-11-13 10:32:03 +01:00
J. Ryan Stinnett
342e28f8a9
[clang][DebugInfo] Attach DISubprogram to additional call variants (#166202)
`DISubprogram`s are attached to call sites to support various debug info
features, including entry values and tail calls. Clang 9.0
(0f6516856670a435461f56a9faeb4aa8a35a6679) was the first version to
include this kind of call site `DISubprogram` attachment.

This earlier work appears to visit only some call site variants,
however. The call site attachment was added to a higher-level `EmitCall`
path in Clang's code gen that is only used by some call variants. In
particular, some C++ member calls use a different code gen path, which
did not include this call site attachment step, and thus the debug info
it triggers (e.g. call site entries) was not emitted for such calls.

This moves `DISubprogram` attachment to a lower-level call emission path
that is used by all call variants.

Fixes https://github.com/llvm/llvm-project/issues/161962
2025-11-10 12:45:05 +00:00
Cyndy Ishida
d65e712e30
[clang] Make "__GCC_HAVE_DWARF2_CFI_ASM" a proper predefined macro (#165731)
Use a flag to determine whether this macro should be set when
intializing the preprocessor.

This macro was added to the driver in
9d117e7b2a399a9b2bcf53fb9b9c0946e82dc75c because it can be conditionally
disabled, but before that, the flag to gate behavior was removed under
the assumption it wasn't conditional in
b5b622a03c5136fa10d245dbe1f8f278ebd98d1b. This patch is to connect the
macro with the preexisting flag
2025-11-03 18:09:18 +00:00
SKill
beadb9eacb
[clang] Use File Location for debug info resolution. (#163982)
To improve debuggability, the macro arguments should be resolved to
their original location rather than macro expansion location.

[PR in
cation](https://github.com/user-attachments/assets/994fb89f-83be-4c21-a79c-f8e51d818f7b)

fixes #160667
2025-10-30 13:39:15 +00:00
Orlando Cazalet-Hyams
30579c0708
[DebugInfo] Add bit size to _BitInt name in debug info (#165583)
Follow on from #164372 

This changes the DW_AT_name for `_BitInt(N)` from `_BitInt` to `_BitInt(N)`
2025-10-30 09:08:43 +00:00
Orlando Cazalet-Hyams
aa5fe56db4
[DebugInfo] Add dataSize to DIBasicType to add DW_AT_bit_size to _BitInt types (#164372)
DW_TAG_base_type DIEs are permitted to have both byte_size and bit_size
attributes "If the value of an object of the given type does not fully
occupy the storage described by a byte size attribute"

* Add DataSizeInBits to DIBasicType (`DIBasicType(... dataSize: n ...)` in IR).
* Change Clang to add DataSizeInBits to _BitInt type metadata.
* Change LLVM to add DW_AT_bit_size to base_type DIEs that have non-zero
  DataSizeInBits.

TODO: Do we need to emit DW_AT_data_bit_offset for big endian targets?
See discussion on the PR.

Fixes [#61952](https://github.com/llvm/llvm-project/issues/61952)

---------

Co-authored-by: David Stenberg <david.stenberg@ericsson.com>
2025-10-29 15:23:46 +00:00
Michael Buch
d0a7411cb8 [clang][DebugInfo][test] Make Objective-C property5.m test check LLVM IR
New name makes it easer to find and checking IR is less likely to hide
bugs (and is more consistent with the other Clang debug-info tests).
2025-10-27 19:44:19 +00:00
Michael Buch
5d9df8f29a
[clang][DebugInfo][test] Convert Objective-C property2.m test to check LLVM IR (#165297)
This patch series renames these Objective-C property tests to something
more descriptive and adjusts them to check IR. Currently the tests check
raw assembly output (not even dwarfdump). Which most likely hid some
bugs around property debug-info.
2025-10-27 19:43:54 +00:00
Michael Buch
e44dce3cb6
[clang][DebugInfo][test] Remove redundant Objective-C property test (#165298)
We already have the same test (just different variable names) in
`property-basic.m`.
2025-10-27 19:40:32 +00:00
Michael Buch
769481704d [clang][DebugInfo] Make property-auto-synth.m check LLVM IR
Check for lack of `setter` and `getter` attributes on `DIObjCProperty`
2025-10-27 19:33:48 +00:00
Michael Buch
267b5b8901 [clang][DebugInfo][test] Rename Objective-C test
Changes test name to something more meaningful. In preparation to
refactoring the test to check LLVM IR instead of assembly.
2025-10-27 19:18:58 +00:00
Mark Danial
90489adf7a
[clang][DebugInfo] Disable objective-CXX tests on AIX and z/OS (#164765)
These tests not supported on AIX and z/OS, disable them to get the
clang-ppc64-aix green
2025-10-27 15:08:53 -04:00
Michael Buch
cc868f6545
[clang][DebugInfo][test] Convert Objective-C property test to check LLVM IR (#165286)
There's a couple of tests like this.

This patch series renames these to something more descriptive and
adjusts the tests to check IR. Currently the tests check raw assembly
output (not even dwarfdump). Which most likely hid some bugs around
property debug-info.
2025-10-27 19:06:43 +00:00
Michael Buch
f8b004dd7b
[clang][DebugInfo] Don't mark explicit parameter of synthesized ObjC property accessors artificial (#164998)
In the past we used to only mark variables artificial that were
`isImplicit`. We would also omit the location information if the
variable's parent was implicit. Since
https://github.com/llvm/llvm-project/pull/100355 we made the logic to
mark variables as artificial the same as determining whether to omit its
location or not. This was to support binding variable declarations,
which we would like to have line information for (and don't want to mark
artificial as they are explicitly named in source).

However, this doesn't quite do the expected for parameters of
Objective-C synthesised property accessors. An Objective-C setter will
have an explicit parameter, which is the ivar to write to. However,
because the parent (i.e., the synthesised method) is artificial, we now
mark that parameter artificial. This is example debug-info for such an
accessor:
```
0x00000118:   DW_TAG_subprogram                                                                           
                DW_AT_low_pc    (0x0000000000000044)
                DW_AT_high_pc   (0x0000000000000078)
                DW_AT_frame_base        (DW_OP_reg29 W29)   
                DW_AT_object_pointer    (0x00000128)
                DW_AT_specification     (0x00000068 "-[Foo setFooProp:]")
                                                     
0x00000128:     DW_TAG_formal_parameter
                  DW_AT_location        (DW_OP_fbreg -8)
                  DW_AT_name    ("self")                                                                  
                  DW_AT_type    (0x00000186 "Foo *")
                  DW_AT_artificial      (true)    
                                                     
0x00000131:     DW_TAG_formal_parameter
                  DW_AT_location        (DW_OP_breg31 WSP+16)
                  DW_AT_name    ("_cmd")
                  DW_AT_type    (0x0000018b "SEL")
                  DW_AT_artificial      (true)      
                                                     
0x0000013a:     DW_TAG_formal_parameter                                                                   
                  DW_AT_location        (DW_OP_breg31 WSP+8)
                  DW_AT_name    ("fooProp")                                                               
                  DW_AT_type    (0x000000aa "id")
                  DW_AT_artificial      (true)    
```

Note how the `fooProp` parameter is marked artificial, although it
technically is an explicitly passed parameter. We want to treat the
synthesised method like any other, where explicitly passed parameters
aren't artificial. But we do want to omit the file/line info because it
doesn't exist in the source.

This patch prevents such parameters from being marked artificial. We
could probably generalise this to any kind of synthesised method, not
just Objective-C. But I'm currently not aware of such synthesised
functions, so made it Objective-C specific for now for testability.

*Motivator*
Marking such parameters artificial makes LLDB fail to parse the ObjC
method and emit an error such as:
```
error: Foo.o [0x00000000000009d7]: invalid Objective-C method DW_TAG_subprogram (DW_TAG_subprogram), please file a bug and attach the file at the start of this error message
```

rdar://163063569
2025-10-27 07:49:06 +00:00
Antonio Frighetto
efcda54794
[clang][CodeGen] Emit llvm.tbaa.errno metadata during module creation
Let Clang emit `llvm.tbaa.errno` metadata in order to let LLVM
carry out optimizations around errno-writing libcalls to, as
long as it is proved the involved memory location does not alias
`errno`.

Previous discussion: https://discourse.llvm.org/t/rfc-modelling-errno-memory-effects/82972.
2025-10-21 11:38:45 +02:00
Michael Buch
0ede5637ff
[clang][DebugInfo] Emit DW_AT_language_{name, version} for DWARFv6 (#163208)
Depends on:
* https://github.com/llvm/llvm-project/pull/163348
* https://github.com/llvm/llvm-project/pull/162632

With this patch Clang will start emitting `DW_AT_language_{name,
version}` for C++/C/Objective-C/Objective-C++ when using `-gdwarf-6`. We
adjust the `DISourceLanguageName` (which we pass to `DICompileUnit`) to
hold a `DW_AT_language_name_` and version code when in DWARFv6.
Otherwise we continue using the `DW_LANG_` version of
`DISourceLanguageName`.

We didn't back-port emitting
`DW_AT_language_name`/`DW_AT_language_version` to DWARFv5 (unlike GCC,
which emits both the new and old language attributes in DWARFv5) because
there wasn't a compelling reason to do so (yet).
2025-10-16 07:37:10 +01:00
Reid Kleckner
56e3e30ceb
[clang] Remove -g[no-]-* bool flags from g_Group (#162750)
There are four uses of BoolGOption, and all of them are essentially debug
info feature flags, which I believe should not the enablement or
disablement of all debug info emission. `OPT_g_group` is used to control
the debug info level here:

https://github.com/llvm/llvm-project/blob/main/clang/lib/Driver/ToolChains/Clang.cpp#L4387

This doesn't cause any test failures, and seems like the right behavior
for all four flags:
* -g[no-]flag-base
* -g[no-]inline-line-tables
* -g[no-]key-instructions
* -g[no-]structor-decl-linkage-names

None of these, even in the positive form, should enable debug info
emission.

Fixes #162747
2025-10-10 22:49:18 +00:00
Mary Kassayova
79f102f339
[clang][DWARF] Add DW_AT_bit_stride for SVE predicate types (#161409)
Fixes #159285
2025-10-09 10:12:59 +01:00
Jan Svoboda
839b91c229
[clang] Move -fprofile-instrument-use-path= check to driver (#159667)
The frontend currently opens the path provided via
`-fprofile-instrument-use-path=` to learn the kind of the
instrumentation data and set the `CodeGenOptions::ProfileUse` value.
This happens during command-line parsing, where we don't have a
correctly configured VFS yet, so the behavior is quite different from
all other frontend inputs. We need to move this logic out of the
frontend command line parsing logic somewhere where we do have the
configured VFS.

The complication is that the `ProfileUse` flag is being used to set
preprocessor macros, and there isn't a great place between command line
parsing and preprocessor initialization to perform this logic.

This PR solves the issue by deducing the kind of instrumentation data
right in the driver and then passing it via a new flag to the frontend.
This shouldn't change observable behavior of Clang on the driver level,
and only affects the frontend command line interface, which is an
implementation detail anyway.
2025-10-06 10:41:46 -07:00
Sirui Mu
d2239fbf43
[clang][CodeGen] Fix sub-optimal clang CodeGen for __atomic_test_and_set (#160098)
Clang CodeGen for `__atomic_test_and_set` would emit a `store`
instruction that stores an `i1` value:

```cpp
bool f(void *ptr) {
  return __atomic_test_and_set(ptr, __ATOMIC_RELAXED);
}
```

```llvm
%1 = atomicrmw xchg ptr %0, i8 1 monotonic, align 1
%tobool = icmp ne i8 %1, 0
store i1 %tobool, ptr %atomic-temp, align 1
```

which could lead to suboptimal binary code, for example on x86_64:

```asm
f:
    mov     al, 1
    xchg    byte ptr [rdi], al
    test    al, al
    setne   al
    setne   byte ptr [rsp - 1]
    ret
```

The last `setne` instruction is obviously redundant. This patch fixes
this issue by first zero-extending `%tobool` to an `i8` before the
store. This effectively eliminates the last `setne` instruction in the
binary code sequence. The `test` and `setne` on `al` is kept still,
though.

-----

I'm quite conservative about the codegen in this patch. Vanilla gcc
actually emits simpler code for `__atomic_test_and_set`:

```cpp
bool f(void *ptr) {
  return __atomic_test_and_set(ptr, __ATOMIC_RELAXED);
}
```

```asm
f:
    mov     eax, 1
    xchg    al, BYTE PTR [rdi]
    ret
```

It seems like gcc assumes `ptr` would always point to a valid `bool`
value as required by the ABI. I'm not sure if we should also make this
assumption.

Related to #121943 .
2025-09-26 23:58:45 +08:00
Michael Buch
77a3d431ff
[clang][DebugInfo][test] Add tests for lambda capture packs (#160705)
We didn't have coverage for this yet. And I'm planning on making some
chnges in this area. These tests will be useful for that.
2025-09-26 07:11:36 +00:00
Michael Buch
8f905c3e6f
[clang][DebugInfo][test] Adjust structured-binding.cpp expected IR names (#160300)
This was failing on a Gentoo amd64 bot:
```
FAIL: Clang :: DebugInfo/CXX/structured-binding.cpp (11221 of 22437)
******************** TEST 'Clang :: DebugInfo/CXX/structured-binding.cpp' FAILED ********************
Exit Code: 1

Command Output (stderr):
--
/var/tmp/portage/llvm-core/clang-22.0.0.9999/work/x/y/clang-abi_x86_32.x86/bin/clang -cc1 -internal-isystem /var/tmp/portage/llvm-core/clang-22.0.0.9999/work/x/y/clang-abi_x86_32.x86/bin/../../../../lib/clang/22/include -nostdsysteminc -std=c++23 -emit-llvm -debug-info-kind=standalone -triple i686-pc-linux-gnu /var/tmp/portage/llvm-core/clang-22.0.0.9999/work/clang/test/DebugInfo/CXX/structured-binding.cpp -o - | /usr/lib/llvm/22/bin/FileCheck /var/tmp/portage/llvm-core/clang-22.0.0.9999/work/clang/test/DebugInfo/CXX/structured-binding.cpp --implicit-check-not="call void @llvm.dbg.declare" # RUN: at line 1
+ /var/tmp/portage/llvm-core/clang-22.0.0.9999/work/x/y/clang-abi_x86_32.x86/bin/clang -cc1 -internal-isystem /var/tmp/portage/llvm-core/clang-22.0.0.9999/work/x/y/clang-abi_x86_32.x86/bin/../../../../lib/clang/22/include -nostdsysteminc -std=c++23 -emit-llvm -debug-info-kind=standalone -triple i686-pc-linux-gnu /var/tmp/portage/llvm-core/clang-22.0.0.9999/work/clang/test/DebugInfo/CXX/structured-binding.cpp -o -
+ /usr/lib/llvm/22/bin/FileCheck /var/tmp/portage/llvm-core/clang-22.0.0.9999/work/clang/test/DebugInfo/CXX/structured-binding.cpp '--implicit-check-not=call void @llvm.dbg.declare'
/var/tmp/portage/llvm-core/clang-22.0.0.9999/work/clang/test/DebugInfo/CXX/structured-binding.cpp:12:11: error: CHECK: expected string not found in input
// CHECK: #dbg_declare(ptr %v, ![[VAR_8:[0-9]+]], !DIExpression()
          ^
<stdin>:152:44: note: scanning from here
 #dbg_declare(ptr %k, !133, !DIExpression(), !139)
                                           ^
<stdin>:163:2: note: possible intended match here
 #dbg_declare(ptr %v6, !140, !DIExpression(), !145)
 ^

Input file: <stdin>
Check file: /var/tmp/portage/llvm-core/clang-22.0.0.9999/work/clang/test/DebugInfo/CXX/structured-binding.cpp

-dump-input=help explains the following input dump.

Input was:
<<<<<<
            .
            .
            .
          147:  store <2 x i32> <i32 1, i32 2>, ptr %vctr, align 8, !dbg !126
          148:  #dbg_declare(ptr %5, !127, !DIExpression(DW_OP_deref), !128)
          149:  #dbg_declare(ptr %5, !129, !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 4), !130)
          150:  store ptr %vctr, ptr %5, align 4, !dbg !131
          151:  call void @llvm.memcpy.p0.p0.i32(ptr align 4 %6, ptr align 4 @__const._Z1fv..1, i32 12, i1 false), !dbg !132
          152:  #dbg_declare(ptr %k, !133, !DIExpression(), !139)
check:12'0                                                X~~~~~~~ error: no match found
          153:  call void @llvm.memcpy.p0.p0.i32(ptr align 4 %agg.tmp, ptr align 4 %6, i32 12, i1 false), !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          154:  %k4 = getelementptr inbounds nuw %"struct.std::triple", ptr %agg.tmp, i32 0, i32 0, !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          155:  %9 = load i32, ptr %k4, align 4, !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          156:  %v = getelementptr inbounds nuw %"struct.std::triple", ptr %agg.tmp, i32 0, i32 1, !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          157:  %10 = load i32, ptr %v, align 4, !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          158:  %w = getelementptr inbounds nuw %"struct.std::triple", ptr %agg.tmp, i32 0, i32 2, !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          159:  %11 = load i32, ptr %w, align 4, !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          160:  %call5 = call noundef i32 @_ZSt3getILj0EEiSt6triple(i32 %9, i32 %10, i32 %11), !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          161:  store i32 %call5, ptr %ref.tmp3, align 4, !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          162:  store ptr %ref.tmp3, ptr %k, align 4, !dbg !139
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          163:  #dbg_declare(ptr %v6, !140, !DIExpression(), !145)
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
check:12'1      ?                                                   possible intended match
          164:  call void @llvm.memcpy.p0.p0.i32(ptr align 4 %agg.tmp8, ptr align 4 %6, i32 12, i1 false), !dbg !145
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          165:  %k9 = getelementptr inbounds nuw %"struct.std::triple", ptr %agg.tmp8, i32 0, i32 0, !dbg !145
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          166:  %12 = load i32, ptr %k9, align 4, !dbg !145
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          167:  %v10 = getelementptr inbounds nuw %"struct.std::triple", ptr %agg.tmp8, i32 0, i32 1, !dbg !145
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          168:  %13 = load i32, ptr %v10, align 4, !dbg !145
check:12'0     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            .
            .
            .
>>>>>>

--

********************
```
2025-09-23 14:10:46 +00:00
Tomohiro Kashiwada
2b90eb8abb
[clang][DebugInfo] Re-enable VTable debug info on COFF platforms (#158450)
The debug info for VTables introduced in #130255 was temporarily
disabled on COFF platforms by #151684, due to the risk of emitting
dangling relocations (see also:
https://github.com/llvm/llvm-project/issues/149639#issuecomment-3114257062
).

This patch re-enables that debug info and adds a guard to prevent
emitting dangling relocations by checking whether the VTable definition
is actually emitted.

Resolves #149639
2025-09-23 11:10:20 +03:00
Michael Buch
012680faf4
[clang][Expr] Teach IgnoreUnlessSpelledInSource about implicit calls to std::get free function (#122265)
When we generate the debug-info for a `VarDecl` we try to determine
whether it was introduced as part of a structure binding (aka a "holding
var"). If it was then we don't mark it as `artificial`.

The heuristic to determine a holding var uses
`IgnoreUnlessSpelledInSource` to unwrap the `VarDecl` initializer until
we hit a `DeclRefExpr` that refers to a `Decomposition`. For "tuple-like
decompositions", Clang will generate a call to a `template<size_t I> Foo
get(Bar)` function that retrieves the `Ith` element from the tuple-like
structure. If that function is a member function, we get an AST that
looks as follows:
```
VarDecl implicit used z1 'std::tuple_element<0, B>::type &&' cinit
`-ExprWithCleanups <col:10> 'int' xvalue
  `-MaterializeTemporaryExpr <col:10> 'int' xvalue extended by Var 0x11d110cf8 'z1' 'std::tuple_element<0, B>::type &&'
    `-CXXMemberCallExpr <col:10> 'int'
      `-MemberExpr <col:10> '<bound member function type>' .get 0x11d104390
        `-ImplicitCastExpr <col:10> 'B' xvalue <NoOp>
          `-DeclRefExpr <col:10> 'B' lvalue Decomposition 0x11d1100a8 '' 'B'
```
`IgnoreUnlessSpelledInSource` happily unwraps this down to the
`DeclRefExpr`. However, when the `get` helper is a free function (which
it is for `std::pair` in libc++ for example), then the AST is:
```
VarDecl col:16 implicit used k 'std::tuple_element<0, const std::tuple<int, int>>::type &' cinit
`-CallExpr <col:16> 'const typename tuple_element<0UL, tuple<int, int>>::type':'const int' lvalue adl
  |-ImplicitCastExpr <col:16> 'const typename tuple_element<0UL, tuple<int, int>>::type &(*)(const tuple<int, int> &) noexcept' <FunctionToPointerDecay>
  | `-DeclRefExpr <col:16> 'const typename tuple_element<0UL, tuple<int, int>>::type &(const tuple<int, int> &) noexcept' lvalue Function 0x1210262d8 'get' 'const typename tuple_element<0UL, tuple<int, int>>::type &(const tuple<int, int> &) noexcept' (FunctionTemplate 0x11d068088 'get')
  `-DeclRefExpr <col:16> 'const std::tuple<int, int>' lvalue Decomposition 0x121021518 '' 'const std::tuple<int, int> &'
```
`IgnoreUnlessSpelledInSource` doesn't unwrap this `CallExpr`, so we
incorrectly mark the binding as `artificial` in debug-info.

This patch adjusts `IgnoreUnlessSpelledInSource` so it unwraps implicit
`CallExpr`s. It's almost identical to how we treat implicit constructor
calls (unfortunately the code can't quite be re-used because a
`CXXConstructExpr` is-not a `CallExpr`, and we check `isElidable`, which
doesn't exist for regular function calls. So I added a new
`IgnoreImplicitCallSingleStep`).

Fixes https://github.com/llvm/llvm-project/issues/122028
2025-09-20 18:30:18 +01:00
Tomohiro Kashiwada
b01cddee0e
[Clang][Cygwin] Cygwin x86_64 should accept __stdcall (#158385)
Cygwin should support calling convention attributes `__cdecl`,
`__stdcall`, `__thiscall`, and `__fastcall`, even though they have no
effect in x86_64, as done in MinGW.

Originally reported in
https://cygwin.com/pipermail/cygwin/2025-September/258782.html

---------

Co-authored-by: Jeremy Drake <github@jdrake.com>
2025-09-14 10:09:46 -07:00
Tomohiro Kashiwada
bf156a2087
[Clang](NFC) Add coverage for VTable debug info (#151818)
Add test for:
- shows effect of inlining member functions
- shows effect of template instantiation methods

Make cleaner a bit:
- drops unnecessary `REQUIRES` clause
- uses `%clang_cc1` instead of `%clang -Xclang`
- uses `-O0 -disable-llvm-passes` and `-O1 -disable-llvm-passes` because
the optimization level affects the linkage of VTables.
2025-09-14 00:39:33 +03:00
Antonio Frighetto
04d38bed70
[clang] Regenerate test checks including TBAA semantics (NFC)
Tests exercizing TBAA metadata (both purposefully and not), and
previously generated via UTC, have been regenerated and updated
to version 6.
2025-09-12 18:37:59 +02:00
Michael Buch
06d202b6cb
[clang][DebugInfo] Emit unified (Itanium) mangled name to structor declarations (#154142)
Depends on https://github.com/llvm/llvm-project/pull/154137

This patch is motivated by
https://github.com/llvm/llvm-project/pull/149827, where we plan on using
mangled names on structor declarations to find the exact structor
definition that LLDB's expression evaluator should call.

Given a `DW_TAG_subprogram` for a function declaration, the most
convenient way for a debugger to find the corresponding definition is to
use the `DW_AT_linkage_name` (i.e., the mangled name). However, we
currently can't do that for constructors/destructors because Clang
doesn't attach linkage names to them. This is because, depending on ABI,
there can be multiple definitions for a single constructor/destructor
declaration. The way GCC works around this is by producing a `C4`/`D4`
"unified" mangling for structor declarations (see
[godbolt](https://godbolt.org/z/Wds6cja9K)). GDB uses this to locate the
relevant definitions.

This patch aligns Clang with GCC's DWARF output and allows us to
implement the same lookup scheme in LLDB.
2025-09-09 09:50:11 +01:00
David Blaikie
5b4819e337 Generalize test over 32 and 64bit targets 2025-09-02 21:53:10 +00:00
David Blaikie
665e875f1a
[DebugInfo] When referencing structured bindings use the reference's location, not the binding's declaration's location (#153637)
For structured bindings that use custom `get` specializations, the
resulting LLVM IR ascribes the load of the result of `get` to the
binding's declaration, rather than the place where the binding is
referenced - this caused awkward sequencing in the debug info where,
when stepping through the code you'd step back to the binding
declaration every time there was a reference to the binding.

To fix that - when we cross into IRGening a binding - suppress the debug
info location of that subexpression.

I don't represent this as a great bit of API design - certainly open to
ideas, but putting it out here as a place to start.

It's /possible/ this is an incomplete fix, even - if the binding decl
had other subexpressions, those would still get their location applied &
it'd likely be wrong.

So maybe that's a direction to go with to productionize this - add a new
location scoped device that suppresses any overriding - this might be
more robust. How do people feel about that?
2025-09-02 21:03:58 +00:00
Dan Liew
f1ee047320
[UBSan][BoundsSafety] Implement support for more expressive "trap reasons" (#154618)
In 29992cfd628ed5b968ccb73b17ed0521382ba317 (#145967) support was added
for "trap reasons" on traps emitted in UBSan in trapping mode (e.g.
`-fsanitize-trap=undefined`). This improved the debugging experience by
attaching the reason for trapping as a string on the debug info on trap
instructions. Consumers such as LLDB can display this trap reason string
when the trap is reached.

A limitation of that patch is that the trap reason string is hard-coded
for each `SanitizerKind` even though the compiler actually has much more
information about the trap available at compile time that could be shown
to the user.

This patch is an incremental step in fixing that. It consists of two
main steps.

**1. Introduce infrastructure for building trap reason strings**

To make it convenient to construct trap reason strings this patch
re-uses Clang's powerful diagnostic infrastructure to provide a
convenient API for constructing trap reason strings. This is achieved
by:

* Introducing a new `Trap` diagnostic kind to represent trap diagnostics
in TableGen files.
* Adding a new `Trap` diagnostic component. While this part probably
isn't technically necessary it seemed like I should follow the existing
convention used by the diagnostic system.
* Adding `DiagnosticTrapKinds.td` to describe the different trap
reasons.
* Add the `TrapReasonBuilder` and `TrapReason` classes to provide an
interface for constructing trap reason strings and the trap category.
Note this API while similar to `DiagnosticBuilder` has different
semantics which are described in the code comments. In particular the
behavior when the destructor is called is very different.
* Adding `CodeGenModule::BuildTrapReason()` as a convenient constructor
for the `TrapReasonBuilder`.

This use of the diagnostic system is a little unusual in that the
emitted trap diagnostics aren't actually consumed by normal diagnostic
consumers (e.g. the console). Instead the `TrapReasonBuilder` is just
used to format a string, so in effect the builder is somewhat analagous
to "printf". However, re-using the diagnostics system in this way brings
a several benefits:

* The powerful diagnostic templating languge (e.g. `%select`) can be
used.
* Formatting Clang data types (e.g. `Type`, `Expr`, etc.) just work
out-of-the-box.
* Describing trap reasons in tablegen files opens the door for
translation to different languages in the future.
* The `TrapReasonBuilder` API is very similar to `DiagnosticBuilder`
which makes it easy to use by anyone already familiar with Clang's
diagnostic system.

While UBSan is the first consumer of this new infrastructure the intent
is to use this to overhaul how trap reasons are implemented in the
`-fbounds-safety` implementation (currently exists downstream).

**2. Apply the new infrastructure to UBSan checks for arithmetic
overflow**

To demonstrate using `TrapReasonBuilder` this patch applies it to UBSan
traps for arithmetic overflow. The intention is that we would
iteratively switch to using the `TrapReasonBuilder` for all UBSan traps
where it makes sense in future patches.

Previously for code like

```
int test(int a, int b) { return a + b; }
```

The trap reason string looked like

```
Undefined Behavior Sanitizer: Integer addition overflowed
```

now the trap message looks like:

```
Undefined Behavior Sanitizer: signed integer addition overflow in 'a + b'
```

This string is much more specific because

* It explains if signed or unsigned overflow occurred
* It actually shows the expression that overflowed

One possible downside of this approach is it may blow up Debug info size
because now there can be many more distinct trap reason strings. To
allow users to avoid this a new driver/cc1 flag
`-fsanitize-debug-trap-reasons=` has been added which can either be
`none` (disable trap reasons entirely), `basic` (use the per
`SanitizerKind` hard coded strings), and `detailed` (use the new
expressive trap reasons implemented in this patch). The default is
`detailed` to give the best out-of-the-box debugging experience. The
existing `-fsanitize-debug-trap-reasons` and
`-fno-sanitize-debug-trap-reasons` have been kept for compatibility and
are aliases of the new flag with `detailed` and `none` arguments passed
respectively.


rdar://158612755
2025-08-27 13:07:15 -07:00
Orlando Cazalet-Hyams
9d65f77159
[KeyInstr] Enable -gkey-instructions by default if optimisations are enabled (#149509)
That's enabling Clang's -gkey-instructions, cc1's -gkey-instructions
remains off by default.

Key Instructions improves the optimized-code debug-stepping experience
in debuggers that use DWARF's `is_stmt` line table register to determine
stepping behaviour.

The feature can be disabled with -gno-key-instructions (note that the
positive and negative flag both imply -g).

RFC:
https://discourse.llvm.org/t/rfc-improving-is-stmt-placement-for-better-interactive-debugging/82668
2025-08-27 09:49:40 +01:00
Michael Buch
bac8c8784c
[clang][DebugInfo][test] Move debug-info tests from CodeGenObjCXX to DebugInfo directory (#154912)
This patch works towards consolidating all Clang debug-info into the
`clang/test/DebugInfo` directory

(https://discourse.llvm.org/t/clang-test-location-of-clang-debug-info-tests/87958).

Here we move only the `clang/test/CodeGenObjCXX` tests.

The list of files i came up with is:
1. searched for anything with `*debug-info*` in the filename
2. searched for occurrences of `debug-info-kind` in the tests
2025-08-26 10:35:29 +02:00
David Tenty
f9bd1876c9
[clang][DebugInfo] Disable objective-C tests on AIX and z/OS (#154951)
These tests don't work due to limitations in backend support, so it's
better to mark them uniformly unsupported on AIX and z/OS.
2025-08-22 11:53:05 -04:00
Michael Buch
8fa55a023b
[clang][DebugInfo][test] Move debug-info tests from CodeGenObjC to DebugInfo directory (#154781)
This patch works towards consolidating all Clang debug-info into the
`clang/test/DebugInfo` directory
(https://discourse.llvm.org/t/clang-test-location-of-clang-debug-info-tests/87958).

Here we move only the `clang/test/CodeGenObjC` tests.

The list of files i came up with is:
1. searched for anything with `*debug-info*` in the filename
2. searched for occurrences of `debug-info-kind` in the tests
2025-08-21 22:09:34 +01:00
ykhatav
38f0b9e6d9
Fix scope of typedefs present inside a template class (#146729)
When a typedef is declared within a templated class, clang incorrectly
assigns the typedef to the compilation unit (CU) scope rather than the
intended scope of the templated class. This issue arises because, during
the creation of the typedef, the context lookup in the RegionMap fails
to locate the templated class, despite its prior creation.
The problem stems from the way the context is stored in the RegionMap.
When handling templated types, the current implementation stores the
class specialization rather than the templated declaration itself. This
leads to a mismatch when attempting to retrieve the context for the
typedef.
To address this issue, the solution involves modifying the
CreatedLimitedType() function. Specifically, when a struct or class is a
templated type, we should store the actual templated declaration in the
RegionMap instead of the class specialization. This ensures that
subsequent lookups for context, such as those needed for typedef
declarations, correctly identify the templated class scope.
Fixes https://github.com/llvm/llvm-project/issues/91451
2025-08-21 16:58:25 -04:00