Commit Graph
59 Commits
Author SHA1 Message Date
Jon Ross-Perkins c0b335b87f Add well-known identifier caching (#6486)
I'm doing this because I figured it'd be an incremental improvement for
all the operator lookups that we do. Even to the extent that we've
discussed witness caching, I think it'll still apply. It does add one
more step to adding new interfaces (before, you'd just write the string,
now you add it to the def file and reference it).

I'll claim it makes GetClangOperatorKind a lot friendlier to read/edit,
nevermind removing the string comparisons. :)
2025-12-11 21:41:47 +00:00
Richard Smith 6114df59ee Factor out a Check::CppContext holding C++-specific check state (#6482)
* Move `Sema` access from `CppFile` into `CppContext`.
* Move the mangle context from `SemIR::File` into `CppContext`.
* Move source location mapping state from `Context` into `CppContext`.

Also factor out the `GenerateAst` function that builds the `CppContext`
and `CppFile` into its own file.
2025-12-10 18:55:22 +00:00
Geoff Romer bf45b1cbf5 Refactor function return type representation (#6463)
This separates the return type from the return pattern, and replaces the
return pattern with a block of return patterns. This is a step toward
support for `ref` returns (where there's no corresponding return
pattern) and compund-form returns (where there may be multiple return
patterns).
2025-12-10 18:34:23 +00:00
Richard Smith c7cd24e1b2 Support for calling C++ destructors. (#6453)
Synthesize an impl of `Destroy` for C++ classes in response to impl
lookup.
2025-12-09 21:03:27 +00:00
Richard SmithandJon Ross-Perkins d208e950c7 Encapsulate clang::ASTUnit in SemIR::CppFile. (#6459)
This intends to avoid proliferation of dependencies on the exact API of
`clang::ASTUnit`, and would enable us to more easily switch to a
different approach that gives us more control over the construction of
the Clang AST.

Also remove some unnecessary tracking of the `CppFile` and instead
always retrieve it from the `SemIR::File`.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-12-04 21:05:40 +00:00
372f632d9d Implement support for copying C++ classes. (#6434)
When performing impl lookup for `Core.Copy` for a C++ class type, look
for a copy constructor. If we find one, synthesize an impl witness that
calls the constructor.

This adds initial support for impl lookup to delegate to the C++ interop
logic for queries involving C++ types. For now, we don't implement the
rules from #6166 that compare a synthesized type structure for the C++
impl against the best Carbon type structure, but the framework for
building that support is established here.

Currently there is no caching of the lookup here, and we build unique
`ImplWitnessTable`s for each lookup, which leads to each impl lookup
producing a distinct facet value. This results in some errors in generic
contexts; this will be addressed in follow-up changes. This PR aims only
to support the non-generic case.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2025-12-02 02:52:23 +00:00
Ivana Ivanovska 108e39e095 Fix SemIR printout for string literals in macros (#6440)
Added SemIR printout for string literals in macros in the tests. Removed
adding the inst in the imports to make the printout succeed.

Part of #6303
2025-11-28 16:34:25 +00:00
Boaz Brickner bef92cf881 Add CppCompat.ULong32, CppCompat.LongLong64 and CppCompat.ULongLong64 (#6386)
This extends #6364 to allow having:
* `Cpp.unsigned_long` as a distinct type when `unsigned long` is 32
bits.
* `Cpp.long_long` and `Cpp.unsigned_long_long` as distinct types when
`long` and `unsigned long` are 64 bits.

Similarly to #6364, we only support implicit conversions from the
matching literal type (`u32`, `i64` and `u64`).

See #6275 for rationale.

Part of #5263.
2025-11-26 16:51:22 +00:00
Ivana Ivanovska 109e39c75c Add support for nullptr literals in macros (#6426)
Adding support for macros that evaluate to nullptr literal.

Demo:

```c++
// macros.h
void foo(int a[2]);
#define MyNullPtr nullptr
```
```c++
// macros.cpp
void foo(int a[2]) {
  if (!a) {
    printf("array a is nullptr\n");
    return;
  }
  printf("a[0] = %d \n", a[0]);
}
```

```c++
// main.carbon

library "Main";

import Cpp library "macros.h";

fn Run() -> i32 {
  Cpp.foo(Cpp.MyNullPtr);
  return 0;
}
```

```
$ clang -c macros.cpp;
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link macros.o main.o \--output=demo_carbon
$ ./demo_carbon
array a is nullptr
```

Part of #6303
2025-11-24 21:03:35 +00:00
Ivana Ivanovska 7be6538aec Add support for character literals in macros (#6419)
Adding support for macros with character literals.

Part of #6303
2025-11-24 13:54:17 +00:00
Ivana Ivanovska 093700b274 Add support for boolean literals in macros (#6418)
Adding support for macros with boolean literals.

Demo:

```c++
// main.carbon

library "Main";

import Core library "io";

import Cpp inline '''
  #define M_TRUE true
''';

fn Run() -> i32 {
  let a: bool = Cpp.M_TRUE;
  if (a) {
    Core.Print(1);
  } else {
    Core.Print(0);
  }
  return 0;
}
```

```
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o \--output=demo_carbon
$ ./demo_carbon
1
```

Part of #6303
2025-11-24 10:40:57 +00:00
Richard Smith 13fbe3c1f3 Allow interop with classes with virtual base classes. (#6413)
For now, treat such classes as being final, since we can't correctly
derive from them.

This removes the last category of C++ class that we are entirely unable
to interop with, and is a prerequisite for interop with C++ iostreams
(which have a virtual base class).
2025-11-21 16:45:38 +00:00
Ivana Ivanovska 8866e39085 Add support for string literals in macros (#6408)
Adding support for macros with string literals.

Part of #6303
2025-11-21 12:33:18 +00:00
Ivana Ivanovska 994e6c904d Add support for macros with floating-point literals (#6391)
Adding support for floating-point literals in macros.

Part of #6303
2025-11-20 12:49:43 +00:00
Richard Smith 0678501038 Replace builtin CppVoidType with a prelude type. (#6403)
Following #6357, map C++ `void` to a prelude class type
`Core.CppCompat.VoidBase`, not to a builtin type. This is mostly just
moving logic around, but does notably change `Cpp.void` from being an
incomplete type to being a complete-but-abstract type.

Also change `NullptrT` to be an adapter for `void*` instead of `()*`, to
follow the approved design.

Implicit conversions to `void` and to `void*` are still absent.

Part of #6280.
2025-11-19 20:40:17 +00:00
Ivana Ivanovska 315b0ac241 Refactor identifier lookup in cpp/import.cpp (#6383)
Following up on the
[comment](https://github.com/carbon-language/carbon-lang/pull/6326#discussion_r2512160370)
from PR #6326, refactoring the identifier lookup to be only once,
instead of both in `LookupMacro` and `ClangLookupName`.

Part of #6303
2025-11-19 13:38:07 +00:00
Chandler Carruth 13bb660f7f Update LLVM and update APIs (#6147)
This also updates the patch file for compiler-rt as upstream has changed
a bit. No functional change.
2025-11-15 03:37:13 +00:00
Boaz Brickner bc734bb768 C++ Interop: Add Core.CppCompat.Long32 as a distinct type for Cpp.long when long is 32 bits (#6364)
For now, only support implicit conversions from and to `i32`.

See #6275 for rationale.

Part of #5263.
2025-11-14 23:26:43 +00:00
Boaz Brickner 2ad26487b6 C++ Interop: Don't crash when trying to call a C++ function with undeduced return type (#6363)
This crashed on trying to build a C++ thunk because the error wasn't
propagated.

Part of #5436.
2025-11-13 20:53:03 +00:00
Jon Ross-Perkins 877179d6d9 Refactor addition of imported locations and placeholders (#6354)
- Makes a little more use of `MakeImportedLocIdAndInst` instead of
`UncheckedLoc`
- Requires use of `MakeImportedLocIdAndInst` with `ImportIRInstId`;
previously optional
- Relevant `if constexpr` moves to `AddPlaceholderImportedInst`, but is
more narrowly scoped there.
- Refactors out `AddPlaceholderImportedInstInNoBlock` to reduce how many
spots do an explicit `imports().push_back(...)`

I'd also considered removing `MakeImportedLocIdAndInst` where possible,
but went this route so that changes to the expected parse node wouldn't
affect callers. When it's required, `MakeImportedLocIdAndInst` is always
there; when it's conditionally present, changing `Parse::NodeId` between
enforceable and not-enforceable would require refactoring any callsites
that assumed one or the other.
2025-11-13 18:34:13 +00:00
Geoff Romer 0873777237 Import C++ ref parameters as ref parameters (#6360) 2025-11-13 17:04:58 +00:00
Richard Smith 86b02ee8af Interop support for nullptr and nullptr_t. (#6353)
Add a `Core.CppCompat.NullptrT` type that C++'s `nullptr_t` maps into.
Map `nullptr` to an uninitialized constant of that type -- `nullptr`
doesn't actually have any defined bits within it, despite having the
same representation as `void*`.
2025-11-12 23:23:48 +00:00
Ivana Ivanovska 3b0dad9dd5 Add support for simple object-like macros (#6326)
Adds support for object-like macros with a single replacement
numeric-literal kind token. Only macros that evaluate to an integer
constant are supported for now. When detected at name lookup, they are
imported as a constant integer value in Carbon.

Demo:

```c++
// --- macros.h

#define CONFIG_VALUE 2
```

``` c++
// main.carbon
library "Main";

import Cpp library "macros.h";
import Core library "io";

fn Run() {
    let a: i32 = Cpp.CONFIG_VALUE;
    Core.Print(a);
}
```

```c++
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o \--output=demo_carbon
$ ./demo_carbon
2
```

Part of #6303
2025-11-11 11:24:20 +00:00
Boaz Brickner b54f2dd592 Support import Cpp; to import Cpp namespace for using C++ builtins (#6320)
This allows writing
```
import Cpp;
```

Instead of writing
```
import Cpp inline "";
```

Part of #6330.
2025-11-06 08:45:28 +00:00
Boaz Brickner ae50e0f623 Propagate location to CppOverloadSetValue instructions (#6317)
Part of #5915.
2025-11-05 16:53:04 +00:00
Boaz Brickner 805600de43 C++ Interop: Preserve non-nullability when mapping const non-nullable pointers (#6293)
For non-nullable const pointers, we need to keep the non-nullability.

This is done by preserving non-nullability when mapping qualifiers.
2025-11-04 18:25:22 +00:00
Boaz Brickner d3762f9723 Remove unused ImportCppId and list of Cpp imports in File (#6290)
See discussion:
https://discord.com/channels/655572317891461132/655578254970716160/1432518191350808659

Part of #5245.
2025-10-30 18:03:34 +00:00
Boaz Brickner fc8db6ac5c C++ Interop: Add a test that demonstrates that const non nullable pointers are wrongly mapped to nullable (optional) pointers (#6284)
Part of #5772.
2025-10-29 09:12:25 +00:00
Boaz Brickner 4d4d720ff0 C++ Interop: Support getting void* from C++ functions and passing void* it to C++ function (#6279)
This defines `Cpp.void` as a custom type.
`Cpp.void*` is mapped to C++ `void*`.

Not supported yet: Conversions from and to other pointer types.

C++ Interop Demo:

```carbon
// main.carbon

library "Main";

import Core library "io";

import Cpp inline '''
#include <cstdio>

auto GetPointer() -> void* _Nonnull {
  static int x = 8;
  return &x;
}

auto GetValue(void* _Nonnull ptr) -> int {
  return *static_cast<int*>(ptr);
}
''';

fn Run() -> i32 {
  let ptr: Cpp.void* = Cpp.GetPointer();
  Core.Print(Cpp.GetValue(ptr));
  return 0;
}
```

```shell
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o --output=demo
$ ./demo
8
```

Part of #6280.
2025-10-29 09:03:53 +00:00
Richard Smith 6011040481 Rework handling of C++ references. (#6268)
For now, map C++ reference types to const-qualified Carbon pointer types
rather than picking between a (non-const) pointer or a value type. This
fixes misbehavior in lowering for reference members in classes and
reference return types.

Update the special-case handling for references as function parameters
so that it continues to map const reference parameters to Carbon
pass-by-value, and unify the code paths for `self` parameters and other
parameters, which were mostly doing the same thing but had some subtle
differences.

Add references to the list of types that we can pass to and from C++
directly, without needing an additional layer of thunks.
2025-10-28 00:33:26 +00:00
Richard Smith a1a35c207e Unify "needs thunk" logic. (#6277)
Remove duplication between determining whether a parameter needs custom
thunk mapping and whether a function needs a thunk. Now a function needs
a thunk if any parameter or the return type does.

This fixes some inconsistencies; previously:
- We would not require a thunk when passing an `unsigned int`, but if we
  had a thunk we'd pass `unsigned int` indirectly.
- We would always require a thunk for an enum parameter, even though
  we'd actually pass it directly if its underlying type is a 32- or
  64-bit integer.
- We would require a thunk for a nullable pointer, even though
  we arrange for all pointer types to have the same ABI in Carbon and
  C++, including nullable pointers / Optional(T*).

This also causes us to use a thunk for rvalue reference return types,
which we used to miscompile.

Depends on #6276.
2025-10-27 22:49:29 +00:00
Geoff Romer 09710d102f Separate binding insts for refs and values (#6235)
This resolves a TODO in `expr_info.cpp` by using the inst kind rather
than the bound value to track the binding's category.

Since we're churning all the `bind_name` insts in testdata anyway, I'm
also taking this opportunity to align the inst naming with the design's
terminology, by calling these insts "bindings" (this aspect of the PR is
dependent on #6231 resolving an ambiguity in that terminology). For
consistency we'll need to rename several other insts as well (see the
TODO on `RefBinding`); I'm deferring that to a separate PR to minimize
the review load, but I think those name changes are in-scope for this
review.
2025-10-23 01:46:24 +00:00
Boaz Brickner 840562feb3 C++ Interop: Fix access calculation to handle private member of base classes correctly (#6238)
Always take into account both the lookup access specifier and the
declaration. When set, lookup access specifier takes precedence. When
not set, we have two use cases:
1. This is not a record member, so no access is specified at all. Treat
this as public.
2. This is a record member of a base class. Treat this as private.
[Reference](https://github.com/llvm/llvm-project/blob/4b1d7827c07381610ad4fa7bd9d1a9659008b963/clang/include/clang/AST/DeclCXX.h#L1724).

Also, deduplicate access mapping between import and overload resolution.

Background:
https://github.com/carbon-language/carbon-lang/pull/6221#issuecomment-3407981790

Part of #5859.
2025-10-21 08:12:57 +00:00
Richard Smith 304d2056cc Map nullable C++ pointer types to Core.Optional(T*). (#6230) 2025-10-16 20:52:32 +00:00
Boaz Brickner c2d21429f2 Avoid changing visiblity when inheriting in CodeContextRenderer (#6219)
This fixes clang-tidy `override-with-different-visibility`.
2025-10-15 15:50:47 +00:00
Boaz Brickner ffefa7711c Move the mapping from entity name to an imported C++ global variable declaration outside of EntityName (#6211)
This would save space for every `EntityName` that is not an imported C++
global variable.
C++ global variables include static data members.
Created `CppGlobalVarId`, `CppGlobalVarKey` and `CppGlobalVar` to allow
having `CanonicalValueStore` that maps `EntityNameId` (which is in
`CppGlobalVarKey` and `CppGlobalVar`) to `ClangDeclId` (which is also in
`CppGlobalVar`).
This is similar to `ClangDeclId`, `ClangDeclKey` and `ClangDecl` .
2025-10-15 13:33:32 +00:00
Boaz Brickner 1ac1d11063 C++ Interop: Support reference types in fields and globals (#6187)
Implemented by generalizing the reference type support for parameters
and return values to other use cases.
The changes to the `method.carbon` test are due to to supporting the
reference types but not supporting the necessary conversions.

C++ Interop Demo:

```c++
// global.h

struct C {
  int member = 0;
  int& member_ref = member;
};

extern C& global;
```

```c++
// global.cpp

#include "global.h"

static C static_c;

C& global= static_c;
```

```carbon
// main.carbon

library "Main";

import Core library "io";

import Cpp library "global.h";

fn Run() -> i32 {
  Core.Print(Cpp.global->member);
  ++(*Cpp.global->member_ref);
  Core.Print(Cpp.global->member);
  ++(*Cpp.global->member_ref);
  Core.Print(Cpp.global->member);
  return 0;
}
```

```shell
$ clang++ -stdlib=libc++ -c global.cpp
$ bazel build toolchain:carbon && bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link global.o main.o --output=demo
$ ./demo
0
1
2
```

**Without this change**:
```shell
main.carbon:10:14: error: semantics TODO: `Unsupported: var type: C &`
  Core.Print(Cpp.global->member);
             ^~~~~~~~~~
main.carbon:10:14: note: in `Cpp` name lookup for `global`
  Core.Print(Cpp.global->member);
             ^~~~~~~~~~
```

Part of #6006 and #6186.
2025-10-10 23:15:31 +00:00
Boaz Brickner 46c5209f2f C++ Interop: Set location when creating a return pattern (#6185)
This requires changing `ReturnSlotPattern` and `OutParamPattern`
definitions to use untyped node id, so they can have any associated
node.

Follow up of #5197.
Part of #5064.
2025-10-10 15:32:14 +00:00
Boaz Brickner f713964db4 C++ Interop: Set location when creating param patterns (#6184)
Follow up of #5197.
Part of #5064.
2025-10-10 09:00:00 +00:00
Ivana Ivanovska 1fe3316f8e Remove unnecessary TODO (#6188)
When importing the overload set the dependencies are not imported
anymore, so this TODO is unnecessary.

Part of #5915
2025-10-09 11:46:08 +00:00
Boaz Brickner c254e9fd75 C++ interop: Correctly report the unsupported param type when using explicit object param (#6179)
This fixes a bug, which seems to have been introduced in #6108.

In the new test, without this change, we will diagnose with
```
error: semantics TODO: `Unsupported: parameter type: ExplicitObjectParam` [SemanticsTodo]
```
2025-10-08 17:01:11 +00:00
Boaz Brickner bfc4d2b127 C++ interop: Add return reference types support (#6178)
This is a follow up of #6082, which added support for reference types,
but not for return types.

C++ Interop Demo:

```carbon
// main.carbon

library "Main";

import Core library "io";

import Cpp inline '''
struct C {
  auto Inc() -> void { ++x; }
  int x = 0;
};
auto GetC() -> C& {
  static C c;
  return c;
}
''';

fn Run() -> i32 {
  Core.Print(Cpp.GetC()->x);
  Cpp.GetC()->Inc();
  Core.Print(Cpp.GetC()->x);
  Cpp.GetC()->Inc();
  Core.Print(Cpp.GetC()->x);
  return 0;
}
```

```shell
$ bazel build toolchain:carbon && bazel-bin/toolchain/carbon compile main.carbon && bazel-bin/toolchain/carbon link main.o --output=demo && ./demo
0
1
2
```

**Without this change**:
```shell
main.carbon:19:14: error: semantics TODO: `Unsupported: return type: C &`
  Core.Print(Cpp.GetC()->x);
             ^~~~~~~~~~
```

Part of #6148.
2025-10-08 16:33:09 +00:00
Boaz Brickner 7c13bddc92 C++ interop: Support C++20 operator and overload resolution for expression rewriting (#6171)
This allows to find the spaceship `operator<=>` when a comparison
operator is not available, and `operator==` when `operator!=` is not
available.
Support added to both lookup and overload resolution, by adding
`OperatorRewriteInfo` and propagating it in `CppOverloadSet`.
In case overload resolution chooses to use an operator which requires
rewriting, we emit a `TODO` since rewriting is not yet supported.

Part of #6170.
2025-10-08 06:28:50 +00:00
Richard SmithandDana Jansens 3b6d202730 Implement support for mixed-access overload sets. (#6137)
This turns out to be quite important, as several important standard
library types (such as `std::string`) have mixed-access overload sets
for their constructors as an implementation detail. The overall approach
here is:

- Use the most permissive access to determine the access of the overload
set itself. This affects whether name lookup finds the member name at
all.
- After overload resolution, re-check the access of the selected member,
if it's protected or private.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-09-26 23:18:16 +00:00
Richard SmithandJon Ross-Perkins 949ec17da2 Improve interop for classes with multiple inheritance. (#6130)
If there's a unique "preferred" base class, then treat that as "the"
base class for Carbon's purposes. In particular:

* If there's exactly one polymorphic base class, that's our preferred
base class.
* If there's exactly one non-empty base class, that's our perferred base
class.
* (Degenerate case) If there's exactly one base class, that's our
preferred base class.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-09-25 20:25:48 +00:00
David Blaikie f194acbf96 Implement system header lookup for interop import (#6128)
Using the toolchain-tasks suggested syntax of:
```
import Cpp header "<system_header.h>";
```
2025-09-25 15:49:06 +00:00
Richard Smith d85781acbf Fix handling of deleted and templated constructors. (#6129)
Don't ignore deleted constructors in overload resolution. If one is the
best match, we want an error rather than picking something else. Don't
crash if we find a constructor template or other weird thing; use
`getConstructorInfo` to map it into a constructor and skip it if it
isn't one, like Clang does.
2025-09-25 04:19:18 +00:00
Richard SmithandJon Ross-Perkins 1e7b7e53ae C++ interop: support for default arguments. (#6108)
The general strategy here is to force use of a thunk when we want to use
default arguments, and have Clang generate uses of the default arguments
on its side of the thunk.

To support this, change the key type used in `clang_decls` from being
just a `Decl*` to being a pair of `Decl*` and number of parameters in
the case of function decls. Import distinct `SemIR::Function`s for each
number of parameters that's used, and corresponding distinct thunks.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-09-24 01:07:59 +00:00
Ivana Ivanovska 6ca443afc7 Refactor ImportNameFromCpp in cpp/import.cpp (#6100)
Cleaned up `ImportNameFromCpp`, extracting smaller functions out of it.
Also added a documentation for `ClangLookup`. No changes in
functionality.

Part of #5915
2025-09-23 12:09:28 +00:00
Boaz Brickner a73e259620 Add Check::Context::clang_sema() method and use it (#6110)
This replaces `sem_ir().clang_ast_unit()->getSema()`.
2025-09-22 19:11:06 +00:00