Files
carbon-lang/toolchain/sem_ir/file.cpp
T
Dana JansensandJon Ross-Perkins 53c98a8619 Support specialization in impl lookup with a symbolic query/impl. (#5169)
Add a new instruction called ImplSymbolicWitness which represents a
search for an impl declaration given a self type and an interface to
find implemented for the self type. The self type is stored as a
constant instruction id, rather than as a ConstantId, as instructions
don't currently support holding ConstantId. The interface is stored as a
SpecificInterface but we can't fit all of it directly into the
instruction. So we add a new id to refer to the SpecificInterface as
follows.

Add a new SpecificInterfaceId which indexes into a canonical value store
on SemIR::File. This tracks all `SpecificInterface`s stored in an
instruction - specifically the ImplSymbolicWitness instruction.

The SpecificInterface on Impl is still stored there as a value, not as
an id, and no id is eagerly constructed for it. We wait until an id is
needed to make one. Since they are canonical, a new id is only create
when a new SpecificInterface value is seen.

When doing impl lookup, and the query is not concrete, and the impl is
not effectively final, the query needs to consider future impls that may
specialize either the self type or the constaint to make a more precise
match and replace the found impl declaration. Instead of returning the
ImplWitness instruction from the found impl, we generate a
ImplSymbolicWitness instruction, storing the query so that it can be
replayed later. This instruction is added to the generic eval block and
thus will be re-evaluated later with a SpecificId that may make the
query more concrete. When evaluating the instruction and replaying the
query, the lookup has the same conditions and if it does not decide to
use the found impl concretely, then the same instruction is returned
from eval, leaving it as symbolic.

--- Impl lookup changes ---

Impl lookup gets a little more interesting now. It continues to look in
the facet value for a witness if the self type is a facet value. Then
falls back to looking for an impl declaration. This step is no longer
done directly. Instead, we construct a ImplSymbolicWitness instruction
and evaluate it immediately for each interface that are in the query
facet type.

The ImplSymbolicWitness instruction, when evaluated, calls back to the
impl lookup code, with a query specific interface. There we resume back
into the same code path as from before, finding a witness in an impl
declaration. But we may return "found a non-final impl" instead of a
concrete witness. If eval receives this back, it evaluates to the
current ImplSymbolicWitness instruction as the resulting constant value.

To pass lookup failures back through eval, a result of InstId::None from
the second step of impl lookup will result in a non-constant value,
which is used as a signal back up the stack to the original impl lookup
function that the lookup failed. Using a non-constant value here would
break evaluation of the generic eval block if impl lookup could fail
there, however we know it will not since we only leave behind an
ImplSymbolicWitness instruction in the eval block if we found at least
one matching impl already, and we just want to look for a better match
with a more specific query.

We must take care to not store a reference into any value store across
computation in impl lookup, since impl lookup can recurse into itself
invalidate those stores. That includes the SpecificInterface obtained
from a SpecificInterfaceId, which impl lookup also inserts into the
store.

--- The long tail ---

Adding a new instruction and a new id type requires a myriad of changes
to support them:

We add Dump() support for SpecificInterfaceId. And fix a crash in Dump
for SpecificId::None. We also add MakeSpecificInterfaceId() for dumping
arbitrary ids.

The type of ImplSymbolicWitness is a new singleton builtin type
instruction called WitnessSymbolicType (like WitnessType is the type for
an ImplWitness).

Both ImplSymbolicWitness and WitnessSymbolicType are given `Value` as
their expression category as they are builtin constant values. And
BuildInfo() in TypeCompleter is taught about them both, returning a
`ValueRepr::Copy`.

WitnessSymbolicType is added to the set of SingletonInstKinds, so that
it can have a singleton instrution id as a static member.

Lower's BuildTypeForInst() is taught to make an empty struct for
WitnessSymbolicType, similar to WitnessType.

Instruction formatter (FormatterImpl) grows support for printing a
SpecificInterfaceId so that it can print both arguments of
ImplSymbolicWitness on the RHS when printing the SemIR instruction. To
print a SpecificInterfaceId, it prints both the interface id and the
specific id (if there is one). For example, for a query on a generic
interface `Z` with one parameter, the RHS includes the query, interface,
and specific:
```
%Z.impl_symbolic_witness: <symbolic witness> = impl_symbolic_witness %U, @Z, @Z(%U.as_type) [symbolic]
```

IdKind is extended to include SpecificInterfaceId.

InstFingerprinter is taught to look through SpecificInterfaceId and use
the interface and specific ids in the fingerprint.

InstNamer is taught about SpecificInterfaceId, counting the interfaces
when building an index. It is also tought about ImplSymbolicWitness,
using the name of the interface within and the `.impl_symbolic_witness`
suffix. For example, here the LHS is named after the interface in the
query:
```
%Z.impl_symbolic_witness: <symbolic witness> = impl_symbolic_witness %U, @Z, @Z(%U.as_type) [symbolic]
```

StringifyTypeExpr is taught about WitnessSymbolicType, which uses its IR
name since it's a singleton. And about ImplSymbolicWitness which uses
its constant value. The handling of ImplWitnessAccess also needed to be
adjusted, since it assumed that ImplWitnessAccess::witness_id would
always be a FacetAccessWitness, but it can now also be an
ImplSymbolicWitness. (It seems that the witness_id is also assigned
ImplWitness instructions, but those ImplWitnessAccess instructions don't
ever seem to get stringified in a diagnostic at this time.) At the
moment the ImplWitnessAccess with a symbolic witness is just stringified
as "<symbolic>", such as in:
```
x.carbon:1:2: error: cannot implicitly convert value of type `()` to `<symbolic>` [ConversionFailure]
  let a: C(D).(Z.X) = ();
                      ^~
```

There is a TODO left behind to include more information there.

The TypeStructure builder is made to handle WitnessSymbolicType and
WitnessType. These come up now in deduce where a generic impl will have
a ImplSymbolicWitness in a FacetValue for a generic self type. The query
may have a concrete ImplWitness in the same position. Since deduce tries
to deduce through the FacetValue, it tries to convert ImplWitness to
ImplSymbolicWitness, tries to do an impl lookup for `impl ImplWitness as
ImplicitAs(ImplSymbolicWitness)` and causes us to build type structures
with each of these.

Subst is updated to handle pushing and popping SpecificInterfaceId.
Without this, when finishing a generic's eval block, we would walk into
the ImplSymbolicWitness instruction, and its arguments, and fail to
recurse down into the SpecificInterfaceId. Then any specifics inside
would be left as "orphaned" without any generic id attached to them, and
we would never update the instructions in the SpecificInterface's
instructions (inside its own SpecificId) with new constant values when
evaluating the generic eval block against a specific. To do this we push
the specific_id inside the SpecificInterface, and when popping we pop
the specific_id then construct a new canonical SpecificInterface with it
and return that id.

We add support for importing ImplSymbolicWitness by importing its self
constant instruction and specific interface id. However we also had to
add import support for SpecificImplFunction, which can now appear in the
generic eval block for a generic impl declaration, and thus must be
imported with the declaration. This is done very similarly to
SpecificFunction, except the `type_id` is a singleton value.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-03-26 15:10:23 +00:00

393 lines
14 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "toolchain/sem_ir/file.h"
#include "common/check.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "toolchain/base/kind_switch.h"
#include "toolchain/base/shared_value_stores.h"
#include "toolchain/base/yaml.h"
#include "toolchain/parse/node_ids.h"
#include "toolchain/sem_ir/ids.h"
#include "toolchain/sem_ir/inst.h"
#include "toolchain/sem_ir/inst_kind.h"
#include "toolchain/sem_ir/typed_insts.h"
namespace Carbon::SemIR {
File::File(const Parse::Tree* parse_tree, CheckIRId check_ir_id,
const std::optional<Parse::Tree::PackagingDecl>& packaging_decl,
SharedValueStores& value_stores, std::string filename)
: parse_tree_(parse_tree),
check_ir_id_(check_ir_id),
package_id_(packaging_decl ? packaging_decl->names.package_id
: PackageNameId::None),
library_id_(packaging_decl ? LibraryNameId::ForStringLiteralValueId(
packaging_decl->names.library_id)
: LibraryNameId::Default),
value_stores_(&value_stores),
filename_(std::move(filename)),
impls_(*this),
type_blocks_(allocator_),
constant_values_(ConstantId::NotConstant),
inst_blocks_(allocator_),
constants_(this) {
// `type` and the error type are both complete & concrete types.
types_.SetComplete(TypeType::SingletonTypeId,
{.value_repr = {.kind = ValueRepr::Copy,
.type_id = TypeType::SingletonTypeId}});
types_.SetComplete(ErrorInst::SingletonTypeId,
{.value_repr = {.kind = ValueRepr::Copy,
.type_id = ErrorInst::SingletonTypeId}});
insts_.Reserve(SingletonInstKinds.size());
for (auto kind : SingletonInstKinds) {
auto inst_id =
insts_.AddInNoBlock(LocIdAndInst::NoLoc(Inst::MakeSingleton(kind)));
constant_values_.Set(inst_id,
SemIR::ConstantId::ForConcreteConstant(inst_id));
}
}
auto File::Verify() const -> ErrorOr<Success> {
// Invariants don't necessarily hold for invalid IR.
if (has_errors_) {
return Success();
}
// Check that every code block has a terminator sequence that appears at the
// end of the block.
for (const Function& function : functions_.array_ref()) {
for (InstBlockId block_id : function.body_block_ids) {
TerminatorKind prior_kind = TerminatorKind::NotTerminator;
for (InstId inst_id : inst_blocks().Get(block_id)) {
TerminatorKind inst_kind =
insts().Get(inst_id).kind().terminator_kind();
if (prior_kind == TerminatorKind::Terminator) {
return Error(llvm::formatv("Inst {0} in block {1} follows terminator",
inst_id, block_id));
}
if (prior_kind > inst_kind) {
return Error(
llvm::formatv("Non-terminator inst {0} in block {1} follows "
"terminator sequence",
inst_id, block_id));
}
prior_kind = inst_kind;
}
if (prior_kind != TerminatorKind::Terminator) {
return Error(llvm::formatv("No terminator in block {0}", block_id));
}
}
}
// TODO: Check that an instruction only references other instructions that are
// either global or that dominate it.
return Success();
}
auto File::OutputYaml(bool include_singletons) const -> Yaml::OutputMapping {
return Yaml::OutputMapping([this, include_singletons](
Yaml::OutputMapping::Map map) {
map.Add("filename", filename_);
map.Add(
"sem_ir", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
map.Add("import_irs", import_irs_.OutputYaml());
map.Add("import_ir_insts", import_ir_insts_.OutputYaml());
map.Add("name_scopes", name_scopes_.OutputYaml());
map.Add("entity_names", entity_names_.OutputYaml());
map.Add("functions", functions_.OutputYaml());
map.Add("classes", classes_.OutputYaml());
map.Add("generics", generics_.OutputYaml());
map.Add("specifics", specifics_.OutputYaml());
map.Add("struct_type_fields", struct_type_fields_.OutputYaml());
map.Add("types", types_.OutputYaml());
map.Add("type_blocks", type_blocks_.OutputYaml());
map.Add("insts",
Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
for (auto [id, inst] : insts_.enumerate()) {
if (!include_singletons && IsSingletonInstId(id)) {
continue;
}
map.Add(PrintToString(id), Yaml::OutputScalar(inst));
}
}));
map.Add("constant_values",
Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
for (auto [id, _] : insts_.enumerate()) {
if (!include_singletons && IsSingletonInstId(id)) {
continue;
}
auto value = constant_values_.Get(id);
if (!value.has_value() || value.is_constant()) {
map.Add(PrintToString(id), Yaml::OutputScalar(value));
}
}
}));
map.Add(
"symbolic_constants",
Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
for (const auto& [i, symbolic] :
llvm::enumerate(constant_values().symbolic_constants())) {
map.Add(
PrintToString(ConstantId::ForSymbolicConstantIndex(i)),
Yaml::OutputScalar(symbolic));
}
}));
map.Add("inst_blocks", inst_blocks_.OutputYaml());
}));
});
}
auto File::CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
-> void {
mem_usage.Collect(MemUsage::ConcatLabel(label, "allocator_"), allocator_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "entity_names_"),
entity_names_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "functions_"), functions_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "classes_"), classes_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "interfaces_"), interfaces_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "impls_"), impls_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "generics_"), generics_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "specifics_"), specifics_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "import_irs_"), import_irs_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "import_ir_insts_"),
import_ir_insts_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "struct_type_fields_"),
struct_type_fields_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "type_blocks_"), type_blocks_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "insts_"), insts_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "name_scopes_"), name_scopes_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "constant_values_"),
constant_values_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "inst_blocks_"), inst_blocks_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "constants_"), constants_);
mem_usage.Collect(MemUsage::ConcatLabel(label, "types_"), types_);
}
auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory {
const File* ir = &file;
// The overall expression category if the current instruction is a value
// expression.
ExprCategory value_category = ExprCategory::Value;
while (true) {
auto untyped_inst = ir->insts().Get(inst_id);
CARBON_KIND_SWITCH(untyped_inst) {
case AdaptDecl::Kind:
case AddrPattern::Kind:
case Assign::Kind:
case BaseDecl::Kind:
case BindingPattern::Kind:
case Branch::Kind:
case BranchIf::Kind:
case BranchWithArg::Kind:
case FieldDecl::Kind:
case FunctionDecl::Kind:
case ImplDecl::Kind:
case NameBindingDecl::Kind:
case Namespace::Kind:
case OutParamPattern::Kind:
case RefParamPattern::Kind:
case RequirementEquivalent::Kind:
case RequirementImpls::Kind:
case RequirementRewrite::Kind:
case Return::Kind:
case ReturnSlotPattern::Kind:
case ReturnExpr::Kind:
case TuplePattern::Kind:
case VarPattern::Kind:
case Vtable::Kind:
return ExprCategory::NotExpr;
case ImportRefUnloaded::Kind:
case ImportRefLoaded::Kind: {
auto import_ir_inst = ir->import_ir_insts().Get(
untyped_inst.As<SemIR::AnyImportRef>().import_ir_inst_id);
ir = ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
inst_id = import_ir_inst.inst_id;
continue;
}
case CARBON_KIND(AsCompatible inst): {
inst_id = inst.source_id;
continue;
}
case CARBON_KIND(BindAlias inst): {
inst_id = inst.value_id;
continue;
}
case CARBON_KIND(ExportDecl inst): {
inst_id = inst.value_id;
continue;
}
case CARBON_KIND(NameRef inst): {
inst_id = inst.value_id;
continue;
}
case CARBON_KIND(Converted inst): {
inst_id = inst.result_id;
continue;
}
case CARBON_KIND(SpecificConstant inst): {
inst_id = inst.inst_id;
continue;
}
case AccessMemberAction::Kind:
case AddrOf::Kind:
case ArrayType::Kind:
case AssociatedConstantDecl::Kind:
case AssociatedEntity::Kind:
case AssociatedEntityType::Kind:
case AutoType::Kind:
case BindSymbolicName::Kind:
case BindValue::Kind:
case BlockArg::Kind:
case BoolLiteral::Kind:
case BoolType::Kind:
case BoundMethod::Kind:
case BoundMethodType::Kind:
case ClassDecl::Kind:
case ClassType::Kind:
case CompleteTypeWitness::Kind:
case ConstType::Kind:
case ConvertToValueAction::Kind:
case FacetAccessType::Kind:
case FacetAccessWitness::Kind:
case FacetType::Kind:
case FacetValue::Kind:
case FloatLiteral::Kind:
case FloatType::Kind:
case FunctionType::Kind:
case FunctionTypeWithSelfType::Kind:
case GenericClassType::Kind:
case GenericInterfaceType::Kind:
case ImplSymbolicWitness::Kind:
case ImplWitness::Kind:
case ImplWitnessAccess::Kind:
case ImportCppDecl::Kind:
case ImportDecl::Kind:
case InstType::Kind:
case InstValue::Kind:
case IntLiteralType::Kind:
case IntType::Kind:
case IntValue::Kind:
case InterfaceDecl::Kind:
case LegacyFloatType::Kind:
case NamespaceType::Kind:
case PointerType::Kind:
case RefineTypeAction::Kind:
case RequireCompleteType::Kind:
case SpecificFunction::Kind:
case SpecificFunctionType::Kind:
case SpecificImplFunction::Kind:
case StringLiteral::Kind:
case StringType::Kind:
case StructType::Kind:
case StructValue::Kind:
case SymbolicBindingPattern::Kind:
case TupleType::Kind:
case TupleValue::Kind:
case TypeOfInst::Kind:
case TypeType::Kind:
case UnaryOperatorNot::Kind:
case UnboundElementType::Kind:
case ValueOfInitializer::Kind:
case ValueParam::Kind:
case ValueParamPattern::Kind:
case VtableType::Kind:
case WhereExpr::Kind:
case WitnessType::Kind:
return value_category;
case ErrorInst::Kind:
return ExprCategory::Error;
case CARBON_KIND(BindName inst): {
// TODO: Don't rely on value_id for expression category, since it may
// not be valid yet. This workaround only works because we don't support
// `var` in function signatures yet.
if (!inst.value_id.has_value()) {
return value_category;
}
inst_id = inst.value_id;
continue;
}
case CARBON_KIND(ArrayIndex inst): {
inst_id = inst.array_id;
continue;
}
case VtablePtr::Kind:
return ExprCategory::EphemeralRef;
case CARBON_KIND(ClassElementAccess inst): {
inst_id = inst.base_id;
// A value of class type is a pointer to an object representation.
// Therefore, if the base is a value, the result is an ephemeral
// reference.
value_category = ExprCategory::EphemeralRef;
continue;
}
case CARBON_KIND(StructAccess inst): {
inst_id = inst.struct_id;
continue;
}
case CARBON_KIND(TupleAccess inst): {
inst_id = inst.tuple_id;
continue;
}
case CARBON_KIND(SpliceBlock inst): {
inst_id = inst.result_id;
continue;
}
case SpliceInst::Kind:
// TODO: Add ExprCategory::Dependent.
return value_category;
case StructLiteral::Kind:
case TupleLiteral::Kind:
return ExprCategory::Mixed;
case ArrayInit::Kind:
case Call::Kind:
case InitializeFrom::Kind:
case ClassInit::Kind:
case StructInit::Kind:
case TupleInit::Kind:
return ExprCategory::Initializing;
case Deref::Kind:
case VarStorage::Kind:
case ReturnSlot::Kind:
return ExprCategory::DurableRef;
case Temporary::Kind:
case TemporaryStorage::Kind:
case ValueAsRef::Kind:
return ExprCategory::EphemeralRef;
case OutParam::Kind:
case RefParam::Kind:
// TODO: Consider introducing a separate category for OutParam:
// unlike other DurableRefs, it permits initialization.
return ExprCategory::DurableRef;
}
}
}
} // namespace Carbon::SemIR