Commit Graph
4599 Commits
Author SHA1 Message Date
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
Dana Jansens ce109708bf Add dumping for NamedConstraintId and shorten untagged id printing (#6319)
Adds support to the `dump` debugger command for named constraint ids,
which are printed as `constraint<number>`. While doing so, we print
whether the `constraint` is complete or not, and add the same to
`interface` to match.

And we noticed that the printing of name and name scope ids, which are
not tagged, are very verbose by adding 7 `0`s to them for no reason. So
make the dump output easier to read by dropping 0 prefixes.

Before:
```
name_scope00000000: {inst: inst0000000E, parent_scope: name_scope<none>, has_error: false, extended_scopes: [], names: {name00000000: inst6000000F, name00000001: inst60000011}} {kind: Namespace, arg0: name_scope00000000, arg1: inst<none>, type: type(inst(NamespaceType))} `package`
```

After:
```
name_scope0: {inst: instE, parent_scope: name_scope<none>, has_error: false, extended_scopes: [], names: {name0: inst6000000F, name1: inst60000011}} {kind: Namespace, arg0: name_scope0, arg1: inst<none>, type: type(inst(NamespaceType))} `package`
```
v0.0.0-0.nightly.2025.11.06
2025-11-05 21:36:42 +00:00
Richard Smith 99cebcf0a3 Add lowering tests for pointer parameters and return values. (#6328) 2025-11-05 21:18:53 +00:00
Richard Smith f2e98c2047 Fix initialization of a variable via an ImplicitAs conversion. (#6327)
We used to generate initialization to a temporary instead, and leave the
variable uninitialized.
2025-11-05 21:05:34 +00:00
Jon Ross-PerkinsandDana Jansens 8166f9a7cf Formalize Cpp as a PackageNameId (#6306)
This turns `Cpp` into a keyword, and makes it map to `NameId::Cpp` and
`PackageNameId::Cpp`.

Per discussion with zygoloid, the keyword versus identifier question is
deliberately kept open by #4846. This PR switches to a keyword because
mapping to a specific `PackageNameId` works best with a special `NameId`
not backed by an `IdentifierId`. We could in theory make it work using
`IdentifierId` or a runtime-tracked `PackageNameId` for `Cpp` (e.g.
stored on `SemIR::File`), but this approach is consistent with `Core`
and so seemed like a good starting point.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-11-05 17:21:41 +00:00
Boaz Brickner ae50e0f623 Propagate location to CppOverloadSetValue instructions (#6317)
Part of #5915.
2025-11-05 16:53:04 +00:00
Dana Jansens b2c3e92132 Copy the complete flag when importing a named constraint (#6316)
And don't mark the imported named constraint as an interface scope.
2025-11-05 14:19:17 +00:00
Richard Smith 5db1141f52 Allow adding / removing const with ImplicitAs. (#6323)
If `T` implicitly converts to `U`, then:

 * `const T` implicitly converts to `U`,
 * `T` implicitly converts to `const U`, and
 * `T` implicitly converts to `Optional(U)`.
2025-11-05 07:38:09 +00:00
aa69a484eb Add support for running LLVM optimizer. (#6225)
Adds a flag `--optimize=<mode>` that specifies what to optimize for:

* `--optimize=none` turns off the optimizer as much as possible, but
still respects always_inline.
* `--optimize=debug` aims to be the equivalent of `-Og` / `-O1`, and
provides optimizations that don't affect the ability to debug the
program. This is the default.
* `--optimize=size` optimizes for the size of the produced program, and
aims to be the equivalent of `-Oz`.
* `--optimize=speed` optimizes for the execution time of the produced
program, and aims to be the equivalent of `-O3`.

Following the approach taken by Clang, the optimization level feeds into
both the configuration of the LLVM pass pipeline and the attributes
added to function definitions generated by the frontend.

Optimization is performed in a new phase, `optimize`, which runs between
`lower` and `codegen`.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
v0.0.0-0.nightly.2025.11.05
2025-11-05 00:15:14 +00:00
David Blaikie db150ffc5c Remove TODO that was based on a misunderstanding on my part (#6322)
I was thinking that the incompleteness diagnostic for C++ types would've
been produced by Clang for record types, but seems they're produced by
Carbon & we already /are/ sharing that diagnostic (with #6302), and that
patch only adds an extra note rather than being a whole separate
codepath for effectively the same diagnostic.
2025-11-04 22:04:50 +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
Geoff Romer 114ecda725 Enable conversions to value-or-ref to use value_of_initializer (#6309)
As a byproduct, the only test that exercised the "address of a temporary
object" diagnostic now trigers the "address of a non-reference
expression" diagnostic. We could restore it by using a type that doesn't
support `value_of_initializer`, but it seems better to remove the
diagnostic altogether: not only does it simplify the code, I'd also
argue "non-reference expression" is more accurate as a user-facing
description of the operand.
2025-11-04 16:29:31 +00:00
Boaz Brickner 1324fad32b C++ Interop: Add basic tests for void* conversion (#6315)
Part of #6280.
2025-11-04 15:39:18 +00:00
Geoff Romer fd3b0b0bf9 Remove redundant function parameter (#6313) v0.0.0-0.nightly.2025.11.04 2025-11-03 19:42:40 +00:00
Dana Jansens 30c3a35776 Import the full NamedConstraint from its decl (#6311)
This imports the entire `NamedConstraint` structure when importing
`NamedConstraintDecl`. This will be required to identify a facet type
that contains a named constraint, as we will need to pull the `require`
decls out of the `NamedConstraint` structure to do so.

I tried making the `InterfaceDecl` code path
[templated](https://github.com/carbon-language/carbon-lang/pull/6308#discussion_r2482655927)
to reuse it, but it was a lot of template parameters including field
pointers into `InterfaceDecl`, `GenericInterfaceType`,
`SpecificInterface`, and it was very hard to read so I gave up on that
approach here.
2025-11-03 16:25:41 +00:00
Boaz Brickner 94bb6be185 C++ Interop: Make CppVoidType always-incomplete (#6302)
Part of https://github.com/carbon-language/carbon-lang/issues/6280.
2025-11-03 09:43:39 +00:00
Dana Jansens ca3f95faa6 Make named constraint eval to a FacetType with itself in it (#6308)
This requires declared FacetTypes to hold NamedConstraintIds (along with
a specific) that are named in an extend or impls requirement. We add
support to stringify and formatter to display the named constraints in
the facet type, and special case when a facet type contains a single
extend named constraint, like we did for a single extend interface.

This means that `RequireIndentifiedFacetType` can now fail, if the facet
type contains a forward-declared named constraint. Add the appropriate
diagnostics for each call to this function, and note the ones that
should change to `RequireCompleteFacetType` in the future with TODOs.

We also add tests for using facet types that can or can't be identified,
or completed, with named constraints in them.
v0.0.0-0.nightly.2025.11.03 v0.0.0-0.nightly.2025.11.02 v0.0.0-0.nightly.2025.11.01
2025-10-31 22:10:35 +00:00
Dana Jansens ed31a6dbe8 Import NamedConstraintDecl instruction names (#6305)
For now, they are imported as their constant value, so there's little to
do, we just need to support getting their NameId. In the future we will
need to import the full named constraint in order to
["identify"](https://github.com/carbon-language/carbon-lang/blob/656150593c1e3fc2b6ccd83c7256a61e4bd04030/proposals/p5168.md#proposed-rules)
them. But we need FacetTypeInfo to hold named constraints first.
2025-10-31 20:23:28 +00:00
Dana Jansens bf72c43b6b Set the completed flag in NamedConstraint after the defn is complete (#6304)
A named constraint can not be
[identified](https://github.com/carbon-language/carbon-lang/blob/656150593c1e3fc2b6ccd83c7256a61e4bd04030/proposals/p5168.md#proposed-rules)
until its definition is complete, so this flag will be used to determine
if the named constraint is ready to be identified.
2025-10-31 20:21:51 +00:00
Dana Jansens 43e09e8e81 Type-check require declarations (#6286)
They don't get stored anywhere yet, but this type checks the
declarations and diagnoses errors in their form, such as not placing a
facet type after `impls` or a type before it.
2025-10-31 20:20:31 +00:00
Jon Ross-PerkinsandDana Jansens 42e2280150 Clean up singleton TypeId use (#6300)
#6289 absentmindedly added fields in more places, and this is undoing
that plus further fixes.

This does some cleanup of types with relation to singletons. For
`TypeType` and `ErrorInst`, they're always complete due to a
`SetComplete` call in `file.cpp`. For `CppVoidType`, it's intended to be
incomplete by construction, and so a `TypeId` should be okay. The intent
though on not generally providing these had been that `GetSingletonType`
needs to be called to get a type to be marked as complete.

In the case of `AutoType`, removing `TypeId`does change a small printing
detail. I think that's old legacy that's just been carried forward.

Otherwise, for both `InstType` and `AutoType`, I've added
`GetSingletonType` calls where they were used in order to ensure
completeness is applied correctly. These calls cause small SemIR
permutations.

This causes `AutoType` to be seen by lowering, so I'm adding a
placeholder for it. Also merging two functions that look like they're
identical in intent -- not sure why they're separate.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
v0.0.0-0.nightly.2025.10.31
2025-10-30 22:50:59 +00:00
Dana Jansens f272198ce5 Don't elide Self when dumping the interface/constraint (#6297)
We give `Self` in an interface/constraint a location so it's not elided
when trying to dump the interface/constraint. We use the location of the
start of the definition, which is the scope for which the `Self` is
constructed and is available in.
2025-10-30 20:47:16 +00:00
Dana Jansens 656150593c Add the CheckIRId tag to NamedConstraintIds (#6298) 2025-10-30 20:06:47 +00:00
Jon Ross-Perkins 356ea7fd30 Fix Cpp.void stringification to be consistent with other singletons (#6301)
I missed this in #6279, just fixing it. See `IntLiteralType` in
typed_insts.h (or similar) for comparison.
2025-10-30 19:15:58 +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
Jon Ross-Perkins 9b95944020 Mask unexpected inst ids (#6295)
Just more anti-churn work.
v0.0.0-0.nightly.2025.10.30
2025-10-29 22:07:33 +00:00
Dana Jansens ec3f7dd9bd Fix diagnostic for argument count mismatch on call to generic constraint (#6292)
The error message was saying "generic interface" but should say "generic
constraint"

There is one test that demonstrates the error message for interfaces,
but it's in tests for overloads, so add a more clearly dedicated test
for interface too.
2025-10-29 20:17:54 +00:00
Dana Jansens 9085e9ee49 Syntax highlight //@include-in-dumps as a valid comment (#6299) 2025-10-29 19:46:29 +00:00
Dana JansensandJon Ross-Perkins d2fbbd3c7a Actually do fingerprinting for InstFingerprinter::GetOrCompute with a CppOverloadSet (#6296)
Currently we schedule work on the CppOverloadSet but then never `Add()`
it to add its contents to be fingerprinted, and just immediately return
an empty fingerprint.

Use CARBON_KIND_SWITCH to prevent this sort of thing from happening in
the future, now that we can use it for std::variant.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-10-29 19:10:50 +00:00
Jon Ross-PerkinsandDana Jansens a1fd86cf27 Change ImplWitnessTablePlaceholder from instruction to InstId value (#6294)
`ImplWitnessTablePlaceholder` is the only non-type singleton instruction
(`ErrorInst` is a type; while `ImplWitnessTablePlaceholder` exposes
`TypeInstId`, it's only used as an `InstId`).

In order to allow simpler handling of singleton instructions, replace
`ImplWitnessTablePlaceholder::TypeInstId` uses with
`InstId::ImplWitnessTablePlaceholder`. Since the placeholder instruction
was never evaluated, this has no significant effect on behavior.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-10-29 18:10:24 +00:00
Jon Ross-PerkinsandDana Jansens 93dc369ebd Add a base struct for singleton type insts (#6289)
This is just reducing boilerplate in `typed_insts.h` because we have a
number of singleton types, and keep adding more.

The changes to `TemplateString` allow `TemplateString IrName` to be used
as a `StringLiteral`.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
2025-10-29 16:52:46 +00:00
Geoff Romer 4821eec2f8 Add support for ref patterns (#6283)
Support for `bound`, and for the `ref` tag on arguments, is left as
future work.
2025-10-29 16:28:56 +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
David Blaikie 29d7e52a46 Add unit tagging to ImportCppId (#6288)
Another case of an id that isn't used in SemIR, but seems valuable to
tag them
just in case they evolve such a use.
2025-10-29 06:22:28 +00:00
Jon Ross-Perkins eed21f6439 Make applying const repeatedly to the same type have less additional effect. (#6287)
This is to avoid edge cases where there are multiple `ConstType`
instructions, which code may not handle appropriately. I was thinking
about this for #6279
v0.0.0-0.nightly.2025.10.29
2025-10-28 19:56:16 +00:00
Geoff Romer 0811d996e1 Finish renaming BindName and related insts. (#6281)
Resolves the TODO from #6235
2025-10-28 17:17:38 +00:00
Ivana Ivanovska 5e0201e5c8 Fix big integer literals type (#6234)
Following the C++ standard rules for assigning a type to a decimal
integer literal, when a Carbon integer literal is passed as a call
argument to a C++ function and it is too big to fit to `int`, `long` or
`long long`, it is assigned an extended integer type (`_int128`).
Discussed in the [interop
meeting](https://docs.google.com/document/d/1YlxEOJ0r-o19o19TCJbFl4Ln1U88yn_Vj23y1Hr5vTk/edit?tab=t.0#heading=h.zdrwb1soj9ms)
and documented in this [design
doc](https://docs.google.com/document/d/18u8z9UEuGH73XzXlDynTgyNK76q1Efl8YYWbpM5LX7o/edit?tab=t.0#heading=h.vxmw1gfg49f2).

Part of #5915
2025-10-28 15:01:43 +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.
v0.0.0-0.nightly.2025.10.28
2025-10-28 00:33:26 +00:00
David Blaikie 33166ffc7a Add unit tagging to CustomLayoutId (#6271) 2025-10-27 23:11:23 +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
Richard SmithandDavid Blaikie f022e91e45 Create a Call instruction directly when building a thunk call. (#6276)
Don't go through the `PerformCall` machinery a second recursive time --
this is redundant, creates additional unnecessary temporaries, and is in
theory wrong because `PerformCall` takes a syntactic argument list (one
argument per callee parameter pattern), but we have a call argument list
(one argument per callee parameter).

---------

Co-authored-by: David Blaikie <dblaikie@gmail.com>
2025-10-27 21:22:24 +00:00
David Blaikie 1aade74693 Add unit tagging to ExprRegionId (#6272)
This doesn't show up in the raw SemIR dumps (I don't think that's due to
a lack of coverage, but due to the fact that ExprRegionId isn't used as
an operand of any instructions).
2025-10-27 16:24:11 +00:00
David Blaikie 53ea894d0d Add unit tagging to ClangDeclId (#6274) v0.0.0-0.nightly.2025.10.27 v0.0.0-0.nightly.2025.10.26 v0.0.0-0.nightly.2025.10.25 2025-10-24 20:18:18 +00:00
David Blaikie 184a39ed8b Add unit tagging to ClangSourceLocId (#6273) 2025-10-24 17:09:46 +00:00
Dana Jansens 0730d5385f Clarify that the Self must be in the type structure of the type or facet type in require (#6269)
It's not enough to have `Self` _somewhere_ in the facet type (after the
`where`).
v0.0.0-0.nightly.2025.10.24
2025-10-23 21:34:03 +00:00
Dana Jansens 26381f6eaf Handle parsing of require...impls declarations (#6255)
Check is not implemented yet, but some tests are added.
2025-10-23 18:34:52 +00:00
David Blaikieandjosh11b 4f1f0fc7c2 Add unit tagging to ImportIRId (#6265)
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2025-10-23 17:34:35 +00:00
josh11bandJosh L c329bce240 PrintChar from "io" library takes a char (#6264)
As [observed in
#toolchain](https://discord.com/channels/655572317891461132/655578254970716160/1428791603786416351),
this makes demo code nicer.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-10-23 16:38:20 +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.
v0.0.0-0.nightly.2025.10.23
2025-10-23 01:46:24 +00:00