custom_witness.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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/check/type_completion.h"
  16. #include "toolchain/sem_ir/associated_constant.h"
  17. #include "toolchain/sem_ir/builtin_function_kind.h"
  18. #include "toolchain/sem_ir/ids.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. // Given a value whose type `IsFacetTypeOrError`, returns the corresponding
  22. // type.
  23. static auto GetFacetAsType(Context& context,
  24. SemIR::ConstantId facet_or_type_const_id)
  25. -> SemIR::TypeId {
  26. auto facet_or_type_id =
  27. context.constant_values().GetInstId(facet_or_type_const_id);
  28. auto type_type_id = context.insts().Get(facet_or_type_id).type_id();
  29. CARBON_CHECK(context.types().IsFacetTypeOrError(type_type_id));
  30. if (context.types().Is<SemIR::FacetType>(type_type_id)) {
  31. // It's a facet; access its type.
  32. facet_or_type_id = context.types().GetTypeInstId(
  33. GetFacetAccessType(context, facet_or_type_id));
  34. }
  35. return context.types().GetTypeIdForTypeInstId(facet_or_type_id);
  36. }
  37. // Returns the body for `Destroy.Op`. This will return `None` if using the
  38. // builtin `NoOp` is appropriate.
  39. //
  40. // TODO: This is a placeholder still not actually destroying things, intended to
  41. // maintain mostly-consistent behavior with current logic while working. That
  42. // also means using `self`.
  43. // TODO: This mirrors `TypeCanDestroy` below, think about ways to share what's
  44. // handled.
  45. static auto MakeDestroyOpBody(Context& context, SemIR::LocId loc_id,
  46. SemIR::TypeId self_type_id)
  47. -> SemIR::InstBlockId {
  48. context.inst_block_stack().Push();
  49. auto inst = context.types().GetAsInst(self_type_id);
  50. while (auto class_type = inst.TryAs<SemIR::ClassType>()) {
  51. // Switch to looking at the object representation.
  52. auto class_info = context.classes().Get(class_type->class_id);
  53. CARBON_CHECK(class_info.is_complete());
  54. inst = context.types().GetAsInst(
  55. class_info.GetObjectRepr(context.sem_ir(), class_type->specific_id));
  56. }
  57. CARBON_KIND_SWITCH(inst) {
  58. case SemIR::ArrayType::Kind:
  59. case SemIR::ConstType::Kind:
  60. case SemIR::MaybeUnformedType::Kind:
  61. case SemIR::PartialType::Kind:
  62. case SemIR::StructType::Kind:
  63. case SemIR::TupleType::Kind:
  64. // TODO: Implement iterative destruction of types.
  65. break;
  66. case SemIR::BoolType::Kind:
  67. case SemIR::FloatType::Kind:
  68. case SemIR::IntType::Kind:
  69. case SemIR::PointerType::Kind:
  70. // For trivially destructible types, we don't generate anything, so that
  71. // this can collapse to a noop implementation when possible.
  72. break;
  73. case SemIR::ErrorInst::Kind:
  74. // Errors can't be destroyed, but we'll still try to generate calls for
  75. // other members.
  76. break;
  77. default:
  78. CARBON_FATAL("Unexpected type for destroy: {0}", inst);
  79. }
  80. if (context.inst_block_stack().PeekCurrentBlockContents().empty()) {
  81. context.inst_block_stack().PopAndDiscard();
  82. return SemIR::InstBlockId::None;
  83. }
  84. AddInst(context, loc_id, SemIR::Return{});
  85. return context.inst_block_stack().Pop();
  86. }
  87. // Returns a manufactured `Destroy.Op` function with the `self` parameter typed
  88. // to `self_type_id`.
  89. static auto MakeDestroyOpFunction(Context& context, SemIR::LocId loc_id,
  90. SemIR::TypeId self_type_id,
  91. SemIR::NameScopeId parent_scope_id)
  92. -> SemIR::InstId {
  93. auto name_id = context.core_identifiers().AddNameId(CoreIdentifier::Op);
  94. auto [decl_id, function_id] =
  95. MakeGeneratedFunctionDecl(context, loc_id,
  96. {.parent_scope_id = parent_scope_id,
  97. .name_id = name_id,
  98. .self_type_id = self_type_id});
  99. auto& function = context.functions().Get(function_id);
  100. auto body_id = MakeDestroyOpBody(context, loc_id, self_type_id);
  101. if (body_id.has_value()) {
  102. function.SetCoreWitness();
  103. function.body_block_ids.push_back(body_id);
  104. } else {
  105. function.SetCoreWitness(SemIR::BuiltinFunctionKind::NoOp);
  106. }
  107. return decl_id;
  108. }
  109. static auto MakeCustomWitnessConstantInst(
  110. Context& context, SemIR::LocId loc_id,
  111. SemIR::SpecificInterfaceId query_specific_interface_id,
  112. SemIR::InstBlockId associated_entities_block_id) -> SemIR::InstId {
  113. // The witness is a CustomWitness of the query interface with a table that
  114. // contains each associated entity.
  115. auto const_id = EvalOrAddInst<SemIR::CustomWitness>(
  116. context, loc_id,
  117. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  118. .elements_id = associated_entities_block_id,
  119. .query_specific_interface_id = query_specific_interface_id});
  120. return context.constant_values().GetInstId(const_id);
  121. }
  122. struct TypesForSelfFacet {
  123. // A FacetType that contains only the query interface.
  124. SemIR::TypeId facet_type_for_query_specific_interface;
  125. // The query self as a type, which involves a conversion if it was a facet.
  126. SemIR::TypeId query_self_as_type_id;
  127. };
  128. static auto GetTypesForSelfFacet(
  129. Context& context, SemIR::LocId loc_id,
  130. SemIR::ConstantId query_self_const_id,
  131. SemIR::SpecificInterfaceId query_specific_interface_id)
  132. -> TypesForSelfFacet {
  133. const auto query_specific_interface =
  134. context.specific_interfaces().Get(query_specific_interface_id);
  135. // The Self facet will have type FacetType, for the query interface.
  136. auto facet_type_for_query_specific_interface =
  137. context.types().GetTypeIdForTypeConstantId(
  138. EvalOrAddInst<SemIR::FacetType>(
  139. context, loc_id,
  140. FacetTypeFromInterface(context,
  141. query_specific_interface.interface_id,
  142. query_specific_interface.specific_id)));
  143. // The Self facet needs to point to a type value. If it's not one already,
  144. // convert to type.
  145. auto query_self_as_type_id = GetFacetAsType(context, query_self_const_id);
  146. return {facet_type_for_query_specific_interface, query_self_as_type_id};
  147. }
  148. // Build a new facet from the query self, using a CustomWitness for the query
  149. // interface with an entry for each associated entity so far.
  150. static auto MakeSelfFacetWithCustomWitness(
  151. Context& context, SemIR::LocId loc_id, TypesForSelfFacet query_types,
  152. SemIR::SpecificInterfaceId query_specific_interface_id,
  153. SemIR::InstBlockId associated_entities_block_id) -> SemIR::ConstantId {
  154. // We are building a facet value for a single interface, so the witness block
  155. // is a single witness for that interface.
  156. auto witnesses_block_id =
  157. context.inst_blocks().Add({MakeCustomWitnessConstantInst(
  158. context, loc_id, query_specific_interface_id,
  159. associated_entities_block_id)});
  160. return EvalOrAddInst<SemIR::FacetValue>(
  161. context, loc_id,
  162. {.type_id = query_types.facet_type_for_query_specific_interface,
  163. .type_inst_id =
  164. context.types().GetTypeInstId(query_types.query_self_as_type_id),
  165. .witnesses_block_id = witnesses_block_id});
  166. }
  167. auto BuildCustomWitness(Context& context, SemIR::LocId loc_id,
  168. SemIR::ConstantId query_self_const_id,
  169. SemIR::SpecificInterfaceId query_specific_interface_id,
  170. llvm::ArrayRef<SemIR::InstId> values) -> SemIR::InstId {
  171. const auto query_specific_interface =
  172. context.specific_interfaces().Get(query_specific_interface_id);
  173. const auto& interface =
  174. context.interfaces().Get(query_specific_interface.interface_id);
  175. auto assoc_entities =
  176. context.inst_blocks().GetOrEmpty(interface.associated_entities_id);
  177. if (assoc_entities.size() != values.size()) {
  178. context.TODO(loc_id, ("Unsupported definition of interface " +
  179. context.names().GetFormatted(interface.name_id))
  180. .str());
  181. return SemIR::ErrorInst::InstId;
  182. }
  183. auto query_types_for_self_facet = GetTypesForSelfFacet(
  184. context, loc_id, query_self_const_id, query_specific_interface_id);
  185. // The values that will go in the witness table.
  186. llvm::SmallVector<SemIR::InstId> entries;
  187. // Fill in the witness table.
  188. for (const auto& [assoc_entity_id, value_id] :
  189. llvm::zip_equal(assoc_entities, values)) {
  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 CARBON_KIND(SemIR::AssociatedConstantDecl decl): {
  226. if (decl.type_id == SemIR::ErrorInst::TypeId) {
  227. return SemIR::ErrorInst::InstId;
  228. }
  229. // TODO: remove once we have a test-case for all associated constants.
  230. // Special-case the ones we want to support in this if-statement, until
  231. // we're able to account for everything.
  232. if (decl.type_id != SemIR::TypeType::TypeId) {
  233. context.TODO(loc_id,
  234. "Associated constant of type other than `TypeType` in "
  235. "synthesized impl");
  236. return SemIR::ErrorInst::InstId;
  237. }
  238. auto type_id = context.insts().Get(value_id).type_id();
  239. CARBON_CHECK(type_id == SemIR::TypeType::TypeId ||
  240. type_id == SemIR::ErrorInst::TypeId);
  241. auto impl_witness_associated_constant =
  242. AddInst<SemIR::ImplWitnessAssociatedConstant>(
  243. context, loc_id, {.type_id = type_id, .inst_id = value_id});
  244. entries.push_back(impl_witness_associated_constant);
  245. break;
  246. }
  247. default:
  248. CARBON_CHECK(decl_id == SemIR::ErrorInst::InstId,
  249. "Unexpected kind of associated entity {0}", decl);
  250. return SemIR::ErrorInst::InstId;
  251. }
  252. }
  253. // TODO: Consider building one witness after all associated constants, and
  254. // then a second after all associated functions, rather than building one in
  255. // each `StructValue`. Right now the code is written assuming at most one
  256. // function, though this CHECK can be removed as a temporary workaround.
  257. auto associated_functions = llvm::count_if(entries, [&](SemIR::InstId id) {
  258. return context.insts().Get(id).kind() == SemIR::InstKind::FunctionDecl;
  259. });
  260. CARBON_CHECK(associated_functions <= 1,
  261. "TODO: Support multiple associated functions");
  262. return MakeCustomWitnessConstantInst(context, loc_id,
  263. query_specific_interface_id,
  264. context.inst_blocks().Add(entries));
  265. }
  266. auto GetCoreInterface(Context& context, SemIR::InterfaceId interface_id)
  267. -> CoreInterface {
  268. const auto& interface = context.interfaces().Get(interface_id);
  269. if (!context.name_scopes().IsCorePackage(interface.parent_scope_id) ||
  270. !interface.name_id.AsIdentifierId().has_value()) {
  271. return CoreInterface::Unknown;
  272. }
  273. constexpr auto CoreIdentifiersToInterfaces = std::array{
  274. std::pair{CoreIdentifier::Copy, CoreInterface::Copy},
  275. std::pair{CoreIdentifier::CppUnsafeDeref, CoreInterface::CppUnsafeDeref},
  276. std::pair{CoreIdentifier::Default, CoreInterface::Default},
  277. std::pair{CoreIdentifier::Destroy, CoreInterface::Destroy},
  278. std::pair{CoreIdentifier::IntFitsIn, CoreInterface::IntFitsIn}};
  279. for (auto [core_identifier, core_interface] : CoreIdentifiersToInterfaces) {
  280. if (interface.name_id ==
  281. context.core_identifiers().AddNameId(core_identifier)) {
  282. return core_interface;
  283. }
  284. }
  285. return CoreInterface::Unknown;
  286. }
  287. // Returns true if the `Self` should impl `Destroy`.
  288. static auto TypeCanDestroy(Context& context,
  289. SemIR::ConstantId query_self_const_id,
  290. SemIR::InterfaceId destroy_interface_id) -> bool {
  291. auto inst = context.insts().Get(context.constant_values().GetInstId(
  292. GetCanonicalFacetOrTypeValue(context, query_self_const_id)));
  293. // For facet values, look if the FacetType provides the same.
  294. if (auto facet_type =
  295. context.types().TryGetAs<SemIR::FacetType>(inst.type_id())) {
  296. const auto& info = context.facet_types().Get(facet_type->facet_type_id);
  297. for (auto interface : info.extend_constraints) {
  298. if (interface.interface_id == destroy_interface_id) {
  299. return true;
  300. }
  301. }
  302. }
  303. CARBON_KIND_SWITCH(inst) {
  304. case CARBON_KIND(SemIR::ClassType class_type): {
  305. auto class_info = context.classes().Get(class_type.class_id);
  306. // Incomplete and abstract classes can't be destroyed.
  307. if (!class_info.is_complete() ||
  308. class_info.inheritance_kind ==
  309. SemIR::Class::InheritanceKind::Abstract) {
  310. return false;
  311. }
  312. // `LookupCppImpl` handles C++ types.
  313. if (context.name_scopes().Get(class_info.scope_id).is_cpp_scope()) {
  314. return false;
  315. }
  316. // TODO: Return false if the object repr doesn't impl `Destroy`.
  317. return true;
  318. }
  319. case SemIR::ArrayType::Kind:
  320. case SemIR::ConstType::Kind:
  321. case SemIR::MaybeUnformedType::Kind:
  322. case SemIR::PartialType::Kind:
  323. case SemIR::StructType::Kind:
  324. case SemIR::TupleType::Kind:
  325. // TODO: Return false for types that indirectly reference a type that
  326. // doesn't impl `Destroy`.
  327. return true;
  328. case SemIR::BoolType::Kind:
  329. case SemIR::FloatType::Kind:
  330. case SemIR::IntType::Kind:
  331. case SemIR::PointerType::Kind:
  332. // Trivially destructible.
  333. return true;
  334. default:
  335. return false;
  336. }
  337. }
  338. static auto MakeDestroyWitness(
  339. Context& context, SemIR::LocId loc_id,
  340. SemIR::ConstantId query_self_const_id,
  341. SemIR::SpecificInterfaceId query_specific_interface_id)
  342. -> std::optional<SemIR::InstId> {
  343. auto query_specific_interface =
  344. context.specific_interfaces().Get(query_specific_interface_id);
  345. if (!TypeCanDestroy(context, query_self_const_id,
  346. query_specific_interface.interface_id)) {
  347. return std::nullopt;
  348. }
  349. if (query_self_const_id.is_symbolic()) {
  350. return SemIR::InstId::None;
  351. }
  352. // Mark functions with the interface's scope as a hint to mangling. This does
  353. // not add them to the scope.
  354. auto parent_scope_id = context.interfaces()
  355. .Get(query_specific_interface.interface_id)
  356. .scope_without_self_id;
  357. auto self_type_id = GetFacetAsType(context, query_self_const_id);
  358. auto op_id =
  359. MakeDestroyOpFunction(context, loc_id, self_type_id, parent_scope_id);
  360. return BuildCustomWitness(context, loc_id, query_self_const_id,
  361. query_specific_interface_id, {op_id});
  362. }
  363. static auto MakeIntFitsInWitness(
  364. Context& context, SemIR::LocId loc_id,
  365. SemIR::ConstantId query_self_const_id,
  366. SemIR::SpecificInterfaceId query_specific_interface_id)
  367. -> std::optional<SemIR::InstId> {
  368. auto query_specific_interface =
  369. context.specific_interfaces().Get(query_specific_interface_id);
  370. auto args_id = query_specific_interface.specific_id;
  371. if (!args_id.has_value()) {
  372. return std::nullopt;
  373. }
  374. auto args_block_id = context.specifics().Get(args_id).args_id;
  375. auto args_block = context.inst_blocks().Get(args_block_id);
  376. if (args_block.size() != 1) {
  377. return std::nullopt;
  378. }
  379. auto dest_const_id = context.constant_values().Get(args_block[0]);
  380. if (!dest_const_id.is_constant()) {
  381. return std::nullopt;
  382. }
  383. auto src_type_id = GetFacetAsType(context, query_self_const_id);
  384. auto dest_type_id = GetFacetAsType(context, dest_const_id);
  385. auto context_fn = [](DiagnosticContextBuilder& /*builder*/) -> void {};
  386. if (!RequireCompleteType(context, src_type_id, loc_id, context_fn) ||
  387. !RequireCompleteType(context, dest_type_id, loc_id, context_fn)) {
  388. return std::nullopt;
  389. }
  390. auto src_info = context.types().TryGetIntTypeInfo(src_type_id);
  391. auto dest_info = context.types().TryGetIntTypeInfo(dest_type_id);
  392. if (!src_info || !dest_info) {
  393. return std::nullopt;
  394. }
  395. // If the bit width is unknown (e.g., due to symbolic evaluation), we cannot
  396. // determine whether it fits yet.
  397. if (src_info->bit_width == IntId::None ||
  398. dest_info->bit_width == IntId::None) {
  399. return std::nullopt;
  400. }
  401. const auto& src_width = context.ints().Get(src_info->bit_width);
  402. const auto& dest_width = context.ints().Get(dest_info->bit_width);
  403. bool fits = false;
  404. if (src_info->is_signed && !dest_info->is_signed) {
  405. // Signed -> unsigned: would truncate the sign bit.
  406. fits = false;
  407. } else if (src_info->is_signed == dest_info->is_signed) {
  408. // Signed -> signed or unsigned -> unsigned: allow widening or preserving
  409. // width.
  410. fits = src_width.sle(dest_width);
  411. } else {
  412. // Unsigned -> signed: strict widening required.
  413. fits = src_width.slt(dest_width);
  414. }
  415. if (!fits) {
  416. return std::nullopt;
  417. }
  418. return BuildCustomWitness(context, loc_id, query_self_const_id,
  419. query_specific_interface_id, {});
  420. }
  421. auto LookupCustomWitness(Context& context, SemIR::LocId loc_id,
  422. CoreInterface core_interface,
  423. SemIR::ConstantId query_self_const_id,
  424. SemIR::SpecificInterfaceId query_specific_interface_id)
  425. -> std::optional<SemIR::InstId> {
  426. switch (core_interface) {
  427. case CoreInterface::Destroy:
  428. return MakeDestroyWitness(context, loc_id, query_self_const_id,
  429. query_specific_interface_id);
  430. case CoreInterface::IntFitsIn:
  431. return MakeIntFitsInWitness(context, loc_id, query_self_const_id,
  432. query_specific_interface_id);
  433. case CoreInterface::Copy:
  434. case CoreInterface::CppUnsafeDeref:
  435. case CoreInterface::Default:
  436. case CoreInterface::Unknown:
  437. // TODO: Handle more interfaces, particularly copy, move, and conversion.
  438. return std::nullopt;
  439. }
  440. }
  441. } // namespace Carbon::Check