custom_witness.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/custom_witness.h"
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/facet_type.h"
  7. #include "toolchain/check/function.h"
  8. #include "toolchain/check/generic.h"
  9. #include "toolchain/check/impl.h"
  10. #include "toolchain/check/impl_lookup.h"
  11. #include "toolchain/check/import_ref.h"
  12. #include "toolchain/check/inst.h"
  13. #include "toolchain/check/name_lookup.h"
  14. #include "toolchain/check/type.h"
  15. #include "toolchain/sem_ir/builtin_function_kind.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::Check {
  19. // Given a value whose type `IsFacetTypeOrError`, returns the corresponding
  20. // type.
  21. static auto GetFacetAsType(Context& context,
  22. SemIR::ConstantId facet_or_type_const_id)
  23. -> SemIR::TypeId {
  24. auto facet_or_type_id =
  25. context.constant_values().GetInstId(facet_or_type_const_id);
  26. auto type_type_id = context.insts().Get(facet_or_type_id).type_id();
  27. CARBON_CHECK(context.types().IsFacetTypeOrError(type_type_id));
  28. if (context.types().Is<SemIR::FacetType>(type_type_id)) {
  29. // It's a facet; access its type.
  30. facet_or_type_id = context.types().GetTypeInstId(
  31. GetFacetAccessType(context, facet_or_type_id));
  32. }
  33. return context.types().GetTypeIdForTypeInstId(facet_or_type_id);
  34. }
  35. // Returns the body for `Destroy.Op`. This will return `None` if using the
  36. // builtin `NoOp` is appropriate.
  37. //
  38. // TODO: This is a placeholder still not actually destroying things, intended to
  39. // maintain mostly-consistent behavior with current logic while working. That
  40. // also means using `self`.
  41. // TODO: This mirrors `TypeCanDestroy` below, think about ways to share what's
  42. // handled.
  43. static auto MakeDestroyOpBody(Context& context, SemIR::LocId loc_id,
  44. SemIR::TypeId self_type_id)
  45. -> SemIR::InstBlockId {
  46. context.inst_block_stack().Push();
  47. auto inst = context.types().GetAsInst(self_type_id);
  48. while (auto class_type = inst.TryAs<SemIR::ClassType>()) {
  49. // Switch to looking at the object representation.
  50. auto class_info = context.classes().Get(class_type->class_id);
  51. CARBON_CHECK(class_info.is_complete());
  52. inst = context.types().GetAsInst(
  53. class_info.GetObjectRepr(context.sem_ir(), class_type->specific_id));
  54. }
  55. CARBON_KIND_SWITCH(inst) {
  56. case SemIR::ArrayType::Kind:
  57. case SemIR::ConstType::Kind:
  58. case SemIR::MaybeUnformedType::Kind:
  59. case SemIR::PartialType::Kind:
  60. case SemIR::StructType::Kind:
  61. case SemIR::TupleType::Kind:
  62. // TODO: Implement iterative destruction of types.
  63. break;
  64. case SemIR::BoolType::Kind:
  65. case SemIR::FloatType::Kind:
  66. case SemIR::IntType::Kind:
  67. case SemIR::PointerType::Kind:
  68. // For trivially destructible types, we don't generate anything, so that
  69. // this can collapse to a noop implementation when possible.
  70. break;
  71. case SemIR::ErrorInst::Kind:
  72. // Errors can't be destroyed, but we'll still try to generate calls for
  73. // other members.
  74. break;
  75. default:
  76. CARBON_FATAL("Unexpected type for destroy: {0}", inst);
  77. }
  78. if (context.inst_block_stack().PeekCurrentBlockContents().empty()) {
  79. context.inst_block_stack().PopAndDiscard();
  80. return SemIR::InstBlockId::None;
  81. }
  82. AddInst(context, loc_id, SemIR::Return{});
  83. return context.inst_block_stack().Pop();
  84. }
  85. // Returns a manufactured `Destroy.Op` function with the `self` parameter typed
  86. // to `self_type_id`.
  87. static auto MakeDestroyOpFunction(Context& context, SemIR::LocId loc_id,
  88. SemIR::TypeId self_type_id,
  89. SemIR::NameScopeId parent_scope_id)
  90. -> SemIR::InstId {
  91. auto name_id = context.core_identifiers().AddNameId(CoreIdentifier::Op);
  92. auto [decl_id, function_id] =
  93. MakeGeneratedFunctionDecl(context, loc_id,
  94. {.parent_scope_id = parent_scope_id,
  95. .name_id = name_id,
  96. .self_type_id = self_type_id});
  97. auto& function = context.functions().Get(function_id);
  98. auto body_id = MakeDestroyOpBody(context, loc_id, self_type_id);
  99. if (body_id.has_value()) {
  100. function.SetCoreWitness();
  101. function.body_block_ids.push_back(body_id);
  102. } else {
  103. function.SetCoreWitness(SemIR::BuiltinFunctionKind::NoOp);
  104. }
  105. return decl_id;
  106. }
  107. static auto MakeCustomWitnessConstantInst(
  108. Context& context, SemIR::LocId loc_id,
  109. SemIR::SpecificInterfaceId query_specific_interface_id,
  110. SemIR::InstBlockId associated_entities_block_id) -> SemIR::InstId {
  111. // The witness is a CustomWitness of the query interface with a table that
  112. // contains each associated entity.
  113. auto const_id = EvalOrAddInst<SemIR::CustomWitness>(
  114. context, loc_id,
  115. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  116. .elements_id = associated_entities_block_id,
  117. .query_specific_interface_id = query_specific_interface_id});
  118. return context.constant_values().GetInstId(const_id);
  119. }
  120. struct TypesForSelfFacet {
  121. // A FacetType that contains only the query interface.
  122. SemIR::TypeId facet_type_for_query_specific_interface;
  123. // The query self as a type, which involves a conversion if it was a facet.
  124. SemIR::TypeId query_self_as_type_id;
  125. };
  126. static auto GetTypesForSelfFacet(
  127. Context& context, SemIR::LocId loc_id,
  128. SemIR::ConstantId query_self_const_id,
  129. SemIR::SpecificInterfaceId query_specific_interface_id)
  130. -> TypesForSelfFacet {
  131. const auto query_specific_interface =
  132. context.specific_interfaces().Get(query_specific_interface_id);
  133. // The Self facet will have type FacetType, for the query interface.
  134. auto facet_type_for_query_specific_interface =
  135. context.types().GetTypeIdForTypeConstantId(
  136. EvalOrAddInst<SemIR::FacetType>(
  137. context, loc_id,
  138. FacetTypeFromInterface(context,
  139. query_specific_interface.interface_id,
  140. query_specific_interface.specific_id)));
  141. // The Self facet needs to point to a type value. If it's not one already,
  142. // convert to type.
  143. auto query_self_as_type_id = GetFacetAsType(context, query_self_const_id);
  144. return {facet_type_for_query_specific_interface, query_self_as_type_id};
  145. }
  146. // Build a new facet from the query self, using a CustomWitness for the query
  147. // interface with an entry for each associated entity so far.
  148. static auto MakeSelfFacetWithCustomWitness(
  149. Context& context, SemIR::LocId loc_id, TypesForSelfFacet query_types,
  150. SemIR::SpecificInterfaceId query_specific_interface_id,
  151. SemIR::InstBlockId associated_entities_block_id) -> SemIR::ConstantId {
  152. // We are building a facet value for a single interface, so the witness block
  153. // is a single witness for that interface.
  154. auto witnesses_block_id =
  155. context.inst_blocks().Add({MakeCustomWitnessConstantInst(
  156. context, loc_id, query_specific_interface_id,
  157. associated_entities_block_id)});
  158. return EvalOrAddInst<SemIR::FacetValue>(
  159. context, loc_id,
  160. {.type_id = query_types.facet_type_for_query_specific_interface,
  161. .type_inst_id =
  162. context.types().GetTypeInstId(query_types.query_self_as_type_id),
  163. .witnesses_block_id = witnesses_block_id});
  164. }
  165. auto BuildCustomWitness(Context& context, SemIR::LocId loc_id,
  166. SemIR::ConstantId query_self_const_id,
  167. SemIR::SpecificInterfaceId query_specific_interface_id,
  168. llvm::ArrayRef<SemIR::InstId> values) -> SemIR::InstId {
  169. const auto query_specific_interface =
  170. context.specific_interfaces().Get(query_specific_interface_id);
  171. const auto& interface =
  172. context.interfaces().Get(query_specific_interface.interface_id);
  173. auto assoc_entities =
  174. context.inst_blocks().GetOrEmpty(interface.associated_entities_id);
  175. if (assoc_entities.size() != values.size()) {
  176. context.TODO(loc_id, ("Unsupported definition of interface " +
  177. context.names().GetFormatted(interface.name_id))
  178. .str());
  179. return SemIR::ErrorInst::InstId;
  180. }
  181. auto query_types_for_self_facet = GetTypesForSelfFacet(
  182. context, loc_id, query_self_const_id, query_specific_interface_id);
  183. // The values that will go in the witness table.
  184. llvm::SmallVector<SemIR::InstId> entries;
  185. // Fill in the witness table.
  186. for (const auto& [assoc_entity_id, value_id] :
  187. llvm::zip_equal(assoc_entities, values)) {
  188. CARBON_DCHECK(value_id != SemIR::InstId::None);
  189. CARBON_DCHECK(value_id != SemIR::ErrorInst::InstId);
  190. LoadImportRef(context, assoc_entity_id);
  191. // Build a witness with the current contents of the witness table. This will
  192. // grow as we progress through the impl. In theory this will build O(n^2)
  193. // table entries, but in practice n <= 2, so that's OK.
  194. //
  195. // This is necessary because later associated entities may refer to earlier
  196. // associated entities in their signatures. In particular, an associated
  197. // result type may be used as the return type of an associated function.
  198. auto self_facet = MakeSelfFacetWithCustomWitness(
  199. context, loc_id, query_types_for_self_facet,
  200. query_specific_interface_id, context.inst_blocks().Add(entries));
  201. auto interface_with_self_specific_id = MakeSpecificWithInnerSelf(
  202. context, loc_id, interface.generic_id, interface.generic_with_self_id,
  203. query_specific_interface.specific_id, self_facet);
  204. auto decl_id =
  205. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  206. context.sem_ir(), interface_with_self_specific_id,
  207. assoc_entity_id));
  208. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  209. auto decl = context.insts().Get(decl_id);
  210. CARBON_KIND_SWITCH(decl) {
  211. case CARBON_KIND(SemIR::StructValue struct_value): {
  212. if (struct_value.type_id == SemIR::ErrorInst::TypeId) {
  213. return SemIR::ErrorInst::InstId;
  214. }
  215. // TODO: If a thunk is needed, this will build a different value each
  216. // time it's called, so we won't properly deduplicate repeated
  217. // witnesses.
  218. entries.push_back(CheckAssociatedFunctionImplementation(
  219. context,
  220. context.types().GetAs<SemIR::FunctionType>(struct_value.type_id),
  221. query_specific_interface.specific_id, value_id,
  222. /*defer_thunk_definition=*/false));
  223. break;
  224. }
  225. case SemIR::AssociatedConstantDecl::Kind: {
  226. context.TODO(loc_id,
  227. "Associated constant in interface with synthesized impl");
  228. return SemIR::ErrorInst::InstId;
  229. }
  230. default:
  231. CARBON_CHECK(decl_id == SemIR::ErrorInst::InstId,
  232. "Unexpected kind of associated entity {0}", decl);
  233. return SemIR::ErrorInst::InstId;
  234. }
  235. }
  236. // TODO: Consider building one witness after all associated constants, and
  237. // then a second after all associated functions, rather than building one in
  238. // each `StructValue`. Right now the code is written assuming at most one
  239. // function, though this CHECK can be removed as a temporary workaround.
  240. CARBON_CHECK(entries.size() <= 1,
  241. "TODO: Support multiple associated functions");
  242. return MakeCustomWitnessConstantInst(context, loc_id,
  243. query_specific_interface_id,
  244. context.inst_blocks().Add(entries));
  245. }
  246. auto GetCoreInterface(Context& context, SemIR::InterfaceId interface_id)
  247. -> CoreInterface {
  248. const auto& interface = context.interfaces().Get(interface_id);
  249. if (!context.name_scopes().IsCorePackage(interface.parent_scope_id) ||
  250. !interface.name_id.AsIdentifierId().has_value()) {
  251. return CoreInterface::Unknown;
  252. }
  253. for (auto [core_identifier, core_interface] :
  254. {std::pair{CoreIdentifier::Copy, CoreInterface::Copy},
  255. std::pair{CoreIdentifier::Destroy, CoreInterface::Destroy}}) {
  256. if (interface.name_id ==
  257. context.core_identifiers().AddNameId(core_identifier)) {
  258. return core_interface;
  259. }
  260. }
  261. return CoreInterface::Unknown;
  262. }
  263. // Returns true if the `Self` should impl `Destroy`.
  264. static auto TypeCanDestroy(Context& context,
  265. SemIR::ConstantId query_self_const_id,
  266. SemIR::InterfaceId destroy_interface_id) -> bool {
  267. auto inst = context.insts().Get(context.constant_values().GetInstId(
  268. GetCanonicalFacetOrTypeValue(context, query_self_const_id)));
  269. // For facet values, look if the FacetType provides the same.
  270. if (auto facet_type =
  271. context.types().TryGetAs<SemIR::FacetType>(inst.type_id())) {
  272. const auto& info = context.facet_types().Get(facet_type->facet_type_id);
  273. for (auto interface : info.extend_constraints) {
  274. if (interface.interface_id == destroy_interface_id) {
  275. return true;
  276. }
  277. }
  278. }
  279. CARBON_KIND_SWITCH(inst) {
  280. case CARBON_KIND(SemIR::ClassType class_type): {
  281. auto class_info = context.classes().Get(class_type.class_id);
  282. // Incomplete and abstract classes can't be destroyed.
  283. if (!class_info.is_complete() ||
  284. class_info.inheritance_kind ==
  285. SemIR::Class::InheritanceKind::Abstract) {
  286. return false;
  287. }
  288. // `LookupCppImpl` handles C++ types.
  289. if (context.name_scopes().Get(class_info.scope_id).is_cpp_scope()) {
  290. return false;
  291. }
  292. // TODO: Return false if the object repr doesn't impl `Destroy`.
  293. return true;
  294. }
  295. case SemIR::ArrayType::Kind:
  296. case SemIR::ConstType::Kind:
  297. case SemIR::MaybeUnformedType::Kind:
  298. case SemIR::PartialType::Kind:
  299. case SemIR::StructType::Kind:
  300. case SemIR::TupleType::Kind:
  301. // TODO: Return false for types that indirectly reference a type that
  302. // doesn't impl `Destroy`.
  303. return true;
  304. case SemIR::BoolType::Kind:
  305. case SemIR::FloatType::Kind:
  306. case SemIR::IntType::Kind:
  307. case SemIR::PointerType::Kind:
  308. // Trivially destructible.
  309. return true;
  310. default:
  311. return false;
  312. }
  313. }
  314. auto LookupCustomWitness(Context& context, SemIR::LocId loc_id,
  315. CoreInterface core_interface,
  316. SemIR::ConstantId query_self_const_id,
  317. SemIR::SpecificInterfaceId query_specific_interface_id)
  318. -> std::optional<SemIR::InstId> {
  319. // TODO: Handle more interfaces, particularly copy, move, and conversion.
  320. if (core_interface != CoreInterface::Destroy) {
  321. return std::nullopt;
  322. }
  323. auto query_specific_interface =
  324. context.specific_interfaces().Get(query_specific_interface_id);
  325. if (!TypeCanDestroy(context, query_self_const_id,
  326. query_specific_interface.interface_id)) {
  327. return std::nullopt;
  328. }
  329. if (query_self_const_id.is_symbolic()) {
  330. return SemIR::InstId::None;
  331. }
  332. // Mark functions with the interface's scope as a hint to mangling. This does
  333. // not add them to the scope.
  334. auto parent_scope_id = context.interfaces()
  335. .Get(query_specific_interface.interface_id)
  336. .scope_without_self_id;
  337. auto self_type_id = GetFacetAsType(context, query_self_const_id);
  338. auto op_id =
  339. MakeDestroyOpFunction(context, loc_id, self_type_id, parent_scope_id);
  340. return BuildCustomWitness(context, loc_id, query_self_const_id,
  341. query_specific_interface_id, {op_id});
  342. }
  343. } // namespace Carbon::Check