facet_type.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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/facet_type.h"
  5. #include <compare>
  6. #include "llvm/ADT/ArrayRef.h"
  7. #include "llvm/ADT/STLExtras.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/diagnostic_helpers.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/import_ref.h"
  12. #include "toolchain/check/inst.h"
  13. #include "toolchain/check/interface.h"
  14. #include "toolchain/check/subst.h"
  15. #include "toolchain/check/type.h"
  16. #include "toolchain/check/type_completion.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. auto FacetTypeFromInterface(Context& context, SemIR::InterfaceId interface_id,
  21. SemIR::SpecificId specific_id) -> SemIR::FacetType {
  22. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(
  23. SemIR::FacetTypeInfo{.extend_constraints = {{interface_id, specific_id}},
  24. .other_requirements = false});
  25. return {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id};
  26. }
  27. // Returns whether the `LookupImplWitness` of `witness_id` matches `interface`.
  28. static auto WitnessQueryMatchesInterface(
  29. Context& context, SemIR::InstId witness_id,
  30. const SemIR::SpecificInterface& interface) -> bool {
  31. auto lookup = context.insts().GetAs<SemIR::LookupImplWitness>(witness_id);
  32. return interface ==
  33. context.specific_interfaces().Get(lookup.query_specific_interface_id);
  34. }
  35. static auto IncompleteFacetTypeDiagnosticBuilder(
  36. Context& context, SemIR::LocId loc_id, SemIR::TypeInstId facet_type_inst_id,
  37. bool is_definition) -> DiagnosticBuilder {
  38. if (is_definition) {
  39. CARBON_DIAGNOSTIC(ImplAsIncompleteFacetTypeDefinition, Error,
  40. "definition of impl as incomplete facet type {0}",
  41. InstIdAsType);
  42. return context.emitter().Build(loc_id, ImplAsIncompleteFacetTypeDefinition,
  43. facet_type_inst_id);
  44. } else {
  45. CARBON_DIAGNOSTIC(
  46. ImplAsIncompleteFacetTypeRewrites, Error,
  47. "declaration of impl as incomplete facet type {0} with rewrites",
  48. InstIdAsType);
  49. return context.emitter().Build(loc_id, ImplAsIncompleteFacetTypeRewrites,
  50. facet_type_inst_id);
  51. }
  52. }
  53. auto InitialFacetTypeImplWitness(
  54. Context& context, SemIR::LocId witness_loc_id,
  55. SemIR::TypeInstId facet_type_inst_id, SemIR::TypeInstId self_type_inst_id,
  56. const SemIR::SpecificInterface& interface_to_witness,
  57. SemIR::SpecificId self_specific_id, bool is_definition) -> SemIR::InstId {
  58. auto facet_type_id =
  59. context.types().GetTypeIdForTypeInstId(facet_type_inst_id);
  60. CARBON_CHECK(facet_type_id != SemIR::ErrorInst::TypeId);
  61. auto facet_type = context.types().GetAs<SemIR::FacetType>(facet_type_id);
  62. const auto& facet_type_info =
  63. context.facet_types().Get(facet_type.facet_type_id);
  64. if (!is_definition && facet_type_info.rewrite_constraints.empty()) {
  65. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  66. context, witness_loc_id,
  67. {.elements_id = context.inst_blocks().AddPlaceholder(),
  68. .impl_id = SemIR::ImplId::None});
  69. return AddInst<SemIR::ImplWitness>(
  70. context, witness_loc_id,
  71. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  72. .witness_table_id = witness_table_inst_id,
  73. .specific_id = self_specific_id});
  74. }
  75. if (!RequireCompleteType(
  76. context, facet_type_id, SemIR::LocId(facet_type_inst_id), [&] {
  77. return IncompleteFacetTypeDiagnosticBuilder(
  78. context, witness_loc_id, facet_type_inst_id, is_definition);
  79. })) {
  80. return SemIR::ErrorInst::InstId;
  81. }
  82. const auto& interface =
  83. context.interfaces().Get(interface_to_witness.interface_id);
  84. auto assoc_entities =
  85. context.inst_blocks().Get(interface.associated_entities_id);
  86. // TODO: When this function is used for things other than just impls, may want
  87. // to only load the specific associated entities that are mentioned in rewrite
  88. // rules.
  89. for (auto decl_id : assoc_entities) {
  90. LoadImportRef(context, decl_id);
  91. }
  92. SemIR::InstId witness_inst_id = SemIR::InstId::None;
  93. llvm::MutableArrayRef<SemIR::InstId> table;
  94. {
  95. auto elements_id =
  96. context.inst_blocks().AddUninitialized(assoc_entities.size());
  97. table = context.inst_blocks().GetMutable(elements_id);
  98. for (auto& uninit : table) {
  99. uninit = SemIR::ImplWitnessTablePlaceholder::TypeInstId;
  100. }
  101. auto witness_table_inst_id = AddInst<SemIR::ImplWitnessTable>(
  102. context, witness_loc_id,
  103. {.elements_id = elements_id, .impl_id = SemIR::ImplId::None});
  104. witness_inst_id = AddInst<SemIR::ImplWitness>(
  105. context, witness_loc_id,
  106. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  107. .witness_table_id = witness_table_inst_id,
  108. .specific_id = self_specific_id});
  109. }
  110. for (auto rewrite : facet_type_info.rewrite_constraints) {
  111. auto access =
  112. context.insts().GetAs<SemIR::ImplWitnessAccess>(rewrite.lhs_id);
  113. if (!WitnessQueryMatchesInterface(context, access.witness_id,
  114. interface_to_witness)) {
  115. continue;
  116. }
  117. auto& table_entry = table[access.index.index];
  118. if (table_entry == SemIR::ErrorInst::InstId) {
  119. // Don't overwrite an error value. This prioritizes not generating
  120. // multiple errors for one associated constant over picking a value
  121. // for it to use to attempt recovery.
  122. continue;
  123. }
  124. auto rewrite_inst_id = rewrite.rhs_id;
  125. if (rewrite_inst_id == SemIR::ErrorInst::InstId) {
  126. table_entry = SemIR::ErrorInst::InstId;
  127. continue;
  128. }
  129. auto decl_id = context.constant_values().GetConstantInstId(
  130. assoc_entities[access.index.index]);
  131. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  132. if (decl_id == SemIR::ErrorInst::InstId) {
  133. table_entry = SemIR::ErrorInst::InstId;
  134. continue;
  135. }
  136. auto assoc_constant_decl =
  137. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id);
  138. if (!assoc_constant_decl) {
  139. auto type_id = context.insts().Get(decl_id).type_id();
  140. auto type_inst = context.types().GetAsInst(type_id);
  141. auto fn_type = type_inst.As<SemIR::FunctionType>();
  142. const auto& fn = context.functions().Get(fn_type.function_id);
  143. CARBON_DIAGNOSTIC(RewriteForAssociatedFunction, Error,
  144. "rewrite specified for associated function {0}",
  145. SemIR::NameId);
  146. context.emitter().Emit(facet_type_inst_id, RewriteForAssociatedFunction,
  147. fn.name_id);
  148. table_entry = SemIR::ErrorInst::InstId;
  149. continue;
  150. }
  151. // FacetTypes resolution disallows two rewrites to the same associated
  152. // constant, so we won't ever have a facet write twice to the same position
  153. // in the witness table.
  154. CARBON_CHECK(table_entry == SemIR::ImplWitnessTablePlaceholder::TypeInstId);
  155. // If the associated constant has a symbolic type, convert the rewrite
  156. // value to that type now we know the value of `Self`.
  157. SemIR::TypeId assoc_const_type_id = assoc_constant_decl->type_id;
  158. if (assoc_const_type_id.is_symbolic()) {
  159. // Get the type of the associated constant in this interface with this
  160. // value for `Self`.
  161. assoc_const_type_id = GetTypeForSpecificAssociatedEntity(
  162. context, SemIR::LocId(facet_type_inst_id),
  163. interface_to_witness.specific_id, decl_id,
  164. context.types().GetTypeIdForTypeInstId(self_type_inst_id),
  165. witness_inst_id);
  166. // Perform the conversion of the value to the type. We skipped this when
  167. // forming the facet type because the type of the associated constant
  168. // was symbolic.
  169. auto converted_inst_id =
  170. ConvertToValueOfType(context, SemIR::LocId(facet_type_inst_id),
  171. rewrite_inst_id, assoc_const_type_id);
  172. // Canonicalize the converted constant value.
  173. converted_inst_id =
  174. context.constant_values().GetConstantInstId(converted_inst_id);
  175. // The result of conversion can be non-constant even if the original
  176. // value was constant.
  177. if (converted_inst_id.has_value()) {
  178. rewrite_inst_id = converted_inst_id;
  179. } else {
  180. const auto& assoc_const = context.associated_constants().Get(
  181. assoc_constant_decl->assoc_const_id);
  182. CARBON_DIAGNOSTIC(
  183. AssociatedConstantNotConstantAfterConversion, Error,
  184. "associated constant {0} given value {1} that is not constant "
  185. "after conversion to {2}",
  186. SemIR::NameId, InstIdAsConstant, SemIR::TypeId);
  187. context.emitter().Emit(
  188. facet_type_inst_id, AssociatedConstantNotConstantAfterConversion,
  189. assoc_const.name_id, rewrite_inst_id, assoc_const_type_id);
  190. rewrite_inst_id = SemIR::ErrorInst::InstId;
  191. }
  192. }
  193. CARBON_CHECK(rewrite_inst_id == context.constant_values().GetConstantInstId(
  194. rewrite_inst_id),
  195. "Rewritten value for associated constant is not canonical.");
  196. table_entry = AddInst<SemIR::ImplWitnessAssociatedConstant>(
  197. context, witness_loc_id,
  198. {.type_id = context.insts().Get(rewrite_inst_id).type_id(),
  199. .inst_id = rewrite_inst_id});
  200. }
  201. return witness_inst_id;
  202. }
  203. auto RequireCompleteFacetTypeForImplDefinition(
  204. Context& context, SemIR::LocId loc_id, SemIR::TypeInstId facet_type_inst_id)
  205. -> bool {
  206. auto facet_type_id =
  207. context.types().GetTypeIdForTypeInstId(facet_type_inst_id);
  208. return RequireCompleteType(
  209. context, facet_type_id, SemIR::LocId(facet_type_inst_id), [&] {
  210. return IncompleteFacetTypeDiagnosticBuilder(context, loc_id,
  211. facet_type_inst_id,
  212. /*is_definition=*/true);
  213. });
  214. }
  215. auto AllocateFacetTypeImplWitness(Context& context,
  216. SemIR::InterfaceId interface_id,
  217. SemIR::InstBlockId witness_id) -> void {
  218. const auto& interface = context.interfaces().Get(interface_id);
  219. CARBON_CHECK(interface.is_complete());
  220. auto assoc_entities =
  221. context.inst_blocks().Get(interface.associated_entities_id);
  222. for (auto decl_id : assoc_entities) {
  223. LoadImportRef(context, decl_id);
  224. }
  225. llvm::SmallVector<SemIR::InstId> empty_table(
  226. assoc_entities.size(), SemIR::ImplWitnessTablePlaceholder::TypeInstId);
  227. context.inst_blocks().ReplacePlaceholder(witness_id, empty_table);
  228. }
  229. namespace {
  230. struct FacetTypeConstraintValue {
  231. SemIR::EntityNameId entity_name_id;
  232. SemIR::ElementIndex access_index;
  233. SemIR::SpecificInterfaceId specific_interface_id;
  234. friend auto operator==(const FacetTypeConstraintValue& lhs,
  235. const FacetTypeConstraintValue& rhs) -> bool = default;
  236. };
  237. } // namespace
  238. static auto GetFacetTypeConstraintValue(Context& context,
  239. SemIR::ImplWitnessAccess access)
  240. -> std::optional<FacetTypeConstraintValue> {
  241. auto lookup =
  242. context.insts().TryGetAs<SemIR::LookupImplWitness>(access.witness_id);
  243. if (lookup) {
  244. auto self = context.insts().TryGetAs<SemIR::BindSymbolicName>(
  245. context.constant_values().GetConstantInstId(
  246. lookup->query_self_inst_id));
  247. if (self) {
  248. return {{.entity_name_id = self->entity_name_id,
  249. .access_index = access.index,
  250. .specific_interface_id = lookup->query_specific_interface_id}};
  251. }
  252. }
  253. return std::nullopt;
  254. }
  255. // Returns true if two values in a rewrite constraint are equivalent. Two
  256. // `ImplWitnessAccess` instructions that refer to the same associated constant
  257. // through the same facet value are treated as equivalent.
  258. static auto CompareFacetTypeConstraintValues(Context& context,
  259. SemIR::InstId lhs_id,
  260. SemIR::InstId rhs_id) -> bool {
  261. if (lhs_id == rhs_id) {
  262. return true;
  263. }
  264. auto lhs_access = context.insts().TryGetAs<SemIR::ImplWitnessAccess>(lhs_id);
  265. auto rhs_access = context.insts().TryGetAs<SemIR::ImplWitnessAccess>(rhs_id);
  266. if (lhs_access && rhs_access) {
  267. auto lhs_access_value = GetFacetTypeConstraintValue(context, *lhs_access);
  268. auto rhs_access_value = GetFacetTypeConstraintValue(context, *rhs_access);
  269. // We do *not* want to get the evaluated result of `ImplWitnessAccess` here,
  270. // we want to keep them as a reference to an associated constant for the
  271. // resolution phase.
  272. return lhs_access_value && rhs_access_value &&
  273. *lhs_access_value == *rhs_access_value;
  274. }
  275. return context.constant_values().GetConstantInstId(lhs_id) ==
  276. context.constant_values().GetConstantInstId(rhs_id);
  277. }
  278. // A mapping of each associated constant (represented as `ImplWitnessAccess`) to
  279. // its value (represented as an `InstId`). Used to track rewrite constraints,
  280. // with the LHS mapping to the resolved value of the RHS.
  281. class AccessRewriteValues {
  282. public:
  283. enum State {
  284. NotRewritten,
  285. BeingRewritten,
  286. FullyRewritten,
  287. };
  288. struct Value {
  289. State state;
  290. SemIR::InstId inst_id;
  291. };
  292. auto InsertNotRewritten(Context& context, SemIR::ImplWitnessAccess access,
  293. SemIR::InstId inst_id) -> void {
  294. map_.insert({*GetKey(context, access), {NotRewritten, inst_id}});
  295. }
  296. // Finds and returns a pointer into the cache for a given ImplWitnessAccess.
  297. // The pointer will be invalidated by mutating the cache. Returns `nullptr`
  298. // if `access` is not found.
  299. auto FindRef(Context& context, SemIR::ImplWitnessAccess access) -> Value* {
  300. auto key = GetKey(context, access);
  301. if (!key) {
  302. return nullptr;
  303. }
  304. auto it = map_.find(*key);
  305. if (it == map_.end()) {
  306. return nullptr;
  307. }
  308. return &it->second;
  309. }
  310. auto SetBeingRewritten(Value& value) -> void {
  311. if (value.state == NotRewritten) {
  312. value.state = BeingRewritten;
  313. }
  314. }
  315. auto SetFullyRewritten(Context& context, Value& value, SemIR::InstId inst_id)
  316. -> void {
  317. CARBON_CHECK(
  318. value.state == BeingRewritten ||
  319. CompareFacetTypeConstraintValues(context, value.inst_id, inst_id));
  320. value = {FullyRewritten, inst_id};
  321. }
  322. private:
  323. using Key = FacetTypeConstraintValue;
  324. struct KeyInfo {
  325. static auto getEmptyKey() -> Key {
  326. return {
  327. .entity_name_id = SemIR::EntityNameId::None,
  328. .access_index = SemIR::ElementIndex(-1),
  329. .specific_interface_id = SemIR::SpecificInterfaceId::None,
  330. };
  331. }
  332. static auto getTombstoneKey() -> Key {
  333. return {
  334. .entity_name_id = SemIR::EntityNameId::None,
  335. .access_index = SemIR::ElementIndex(-2),
  336. .specific_interface_id = SemIR::SpecificInterfaceId::None,
  337. };
  338. }
  339. static auto getHashValue(Key key) -> unsigned {
  340. // This hash produces the same value if two ImplWitnessAccess are
  341. // pointing to the same associated constant, even if they are different
  342. // instruction ids.
  343. //
  344. // TODO: This truncates the high bits of the hash code which does not
  345. // make for a good hash function.
  346. return static_cast<unsigned>(static_cast<uint64_t>(HashValue(key)));
  347. }
  348. static auto isEqual(Key lhs, Key rhs) -> bool {
  349. // This comparison is true if the two ImplWitnessAccess are pointing to
  350. // the same associated constant, even if they are different instruction
  351. // ids.
  352. return lhs == rhs;
  353. }
  354. };
  355. // Returns a key for the `access` to an associated context if the access is
  356. // through a facet value. If the access it through another `ImplWitnessAccess`
  357. // then no key is able to be made.
  358. auto GetKey(Context& context, SemIR::ImplWitnessAccess access)
  359. -> std::optional<Key> {
  360. return GetFacetTypeConstraintValue(context, access);
  361. }
  362. // Try avoid heap allocations in the common case where there are a small
  363. // number of rewrite rules referring to each other by keeping up to 16 on
  364. // the stack.
  365. //
  366. // TODO: Revisit if 16 is an appropriate number when we can measure how deep
  367. // rewrite constraint chains go in practice.
  368. llvm::SmallDenseMap<Key, Value, 16, KeyInfo> map_;
  369. };
  370. // To be used for substituting into the RHS of a rewrite constraint.
  371. //
  372. // It will substitute any `ImplWitnessAccess` into `.Self` (a reference to an
  373. // associated constant) with the RHS of another rewrite constraint that writes
  374. // to the same associated constant. For example:
  375. // ```
  376. // Z where .X = () and .Y = .X
  377. // ```
  378. // Here the second `.X` is an `ImplWitnessAccess` which would be substituted by
  379. // finding the first rewrite constraint, where the LHS is for the same
  380. // associated constant and using its RHS. So the substitution would produce:
  381. // ```
  382. // Z where .X = () and .Y = ()
  383. // ```
  384. //
  385. // This additionally diagnoses cycles when the `ImplWitnessAccess` is reading
  386. // from the same rewrite constraint, and is thus assigning to the associated
  387. // constant a value that refers to the same associated constant, such as with `Z
  388. // where .X = C(.X)`. In the event of a cycle, the `ImplWitnessAccess` is
  389. // replaced with `ErrorInst` so that further evaluation of the
  390. // `ImplWitnessAccess` will not loop infinitely.
  391. //
  392. // The `rewrite_values` given to the constructor must be set up initially with
  393. // each rewrite rule of an associated constant inserted with its unresolved
  394. // value via `InsertNotRewritten`. Then for each rewrite rule of an associated
  395. // constant, the LHS access should be set as being rewritten with its state
  396. // changed to `BeingRewritten` in order to detect cycles before performing
  397. // SubstInst. The result of SubstInst should be preserved afterward by changing
  398. // the state and value for the LHS to `FullyRewritten` and the subst output
  399. // instruction, respectively, to avoid duplicating work.
  400. class SubstImplWitnessAccessCallbacks : public SubstInstCallbacks {
  401. public:
  402. explicit SubstImplWitnessAccessCallbacks(Context* context,
  403. SemIR::LocId loc_id,
  404. AccessRewriteValues* rewrite_values)
  405. : SubstInstCallbacks(context),
  406. loc_id_(loc_id),
  407. rewrite_values_(rewrite_values) {}
  408. auto Subst(SemIR::InstId& rhs_inst_id) -> SubstResult override {
  409. auto rhs_access =
  410. context().insts().TryGetAs<SemIR::ImplWitnessAccess>(rhs_inst_id);
  411. if (!rhs_access) {
  412. // We only want to substitute ImplWitnessAccesses written directly on the
  413. // RHS of the rewrite constraint, not when they are nested inside facet
  414. // types that are part of the RHS, like `.X = C as (I where .Y = {})`.
  415. if (context().insts().Is<SemIR::FacetType>(rhs_inst_id)) {
  416. return SubstResult::FullySubstituted;
  417. }
  418. if (context().constant_values().Get(rhs_inst_id).is_concrete()) {
  419. // There's no ImplWitnessAccess that we care about inside this
  420. // instruction.
  421. return SubstResult::FullySubstituted;
  422. } else {
  423. // SubstOperands will result in a Rebuild or ReuseUnchanged callback, so
  424. // push the non-ImplWitnessAccess to get proper bracketing, allowing us
  425. // to pop it in the paired callback.
  426. substs_in_progress_.push_back(rhs_inst_id);
  427. return SubstResult::SubstOperands;
  428. }
  429. }
  430. // If the access is going through a nested `ImplWitnessAccess`, that
  431. // access needs to be resolved to a facet value first. If it can't be
  432. // resolved then the outer one can not be either.
  433. if (auto lookup = context().insts().TryGetAs<SemIR::LookupImplWitness>(
  434. rhs_access->witness_id)) {
  435. if (context().insts().Is<SemIR::ImplWitnessAccess>(
  436. lookup->query_self_inst_id)) {
  437. substs_in_progress_.push_back(rhs_inst_id);
  438. return SubstResult::SubstOperandsAndRetry;
  439. }
  440. }
  441. auto* rewrite_value = rewrite_values_->FindRef(context(), *rhs_access);
  442. if (!rewrite_value) {
  443. // The RHS refers to an associated constant for which there is no rewrite
  444. // rule.
  445. return SubstResult::FullySubstituted;
  446. }
  447. // Diagnose a cycle if the RHS refers to something that depends on the value
  448. // of the RHS.
  449. if (rewrite_value->state == AccessRewriteValues::BeingRewritten) {
  450. CARBON_DIAGNOSTIC(FacetTypeConstraintCycle, Error,
  451. "found cycle in facet type constraint for {0}",
  452. InstIdAsConstant);
  453. // TODO: It would be nice to note the places where the values are
  454. // assigned but rewrite constraint instructions are from canonical
  455. // constant values, and have no locations. We'd need to store a location
  456. // along with them in the rewrite constraints, and track propagation of
  457. // locations here, which may imply heap allocations.
  458. context().emitter().Emit(loc_id_, FacetTypeConstraintCycle, rhs_inst_id);
  459. rhs_inst_id = SemIR::ErrorInst::InstId;
  460. return SubstResult::FullySubstituted;
  461. } else if (rewrite_value->state == AccessRewriteValues::FullyRewritten) {
  462. rhs_inst_id = rewrite_value->inst_id;
  463. return SubstResult::FullySubstituted;
  464. }
  465. // We have a non-rewritten RHS. We need to recurse on rewriting it. Reuse
  466. // the previous lookup by mutating it in place.
  467. rewrite_values_->SetBeingRewritten(*rewrite_value);
  468. // The ImplWitnessAccess was replaced with some other instruction, which may
  469. // contain or be another ImplWitnessAccess. Keep track of the associated
  470. // constant we are now computing the value of.
  471. substs_in_progress_.push_back(rhs_inst_id);
  472. rhs_inst_id = rewrite_value->inst_id;
  473. return SubstResult::SubstAgain;
  474. }
  475. auto Rebuild(SemIR::InstId /*orig_inst_id*/, SemIR::Inst new_inst)
  476. -> SemIR::InstId override {
  477. auto inst_id = RebuildNewInst(loc_id_, new_inst);
  478. auto subst_inst_id = substs_in_progress_.pop_back_val();
  479. if (auto access = context().insts().TryGetAs<SemIR::ImplWitnessAccess>(
  480. subst_inst_id)) {
  481. if (auto* rewrite_value = rewrite_values_->FindRef(context(), *access)) {
  482. rewrite_values_->SetFullyRewritten(context(), *rewrite_value, inst_id);
  483. }
  484. }
  485. return inst_id;
  486. }
  487. auto ReuseUnchanged(SemIR::InstId orig_inst_id) -> SemIR::InstId override {
  488. auto subst_inst_id = substs_in_progress_.pop_back_val();
  489. if (auto access = context().insts().TryGetAs<SemIR::ImplWitnessAccess>(
  490. subst_inst_id)) {
  491. if (auto* rewrite_value = rewrite_values_->FindRef(context(), *access)) {
  492. rewrite_values_->SetFullyRewritten(context(), *rewrite_value,
  493. orig_inst_id);
  494. }
  495. }
  496. return orig_inst_id;
  497. }
  498. private:
  499. struct SubstInProgress {
  500. // The associated constant whose value is being determined, represented as
  501. // an ImplWitnessAccess. Or another instruction that we are recursing
  502. // through.
  503. SemIR::InstId inst_id;
  504. };
  505. // The location of the rewrite constraints as a whole.
  506. SemIR::LocId loc_id_;
  507. // Tracks the resolved value of each rewrite constraint, keyed by the
  508. // `ImplWitnessAccess` of the associated constant on the LHS of the
  509. // constraint. The value of each associated constant may be changed during
  510. // substitution, replaced with a fully resolved value for the RHS. This allows
  511. // us to cache work; when a value for an associated constant is found once it
  512. // can be reused cheaply, avoiding exponential runtime when rewrite rules
  513. // refer to each other in ways that create exponential references.
  514. AccessRewriteValues* rewrite_values_;
  515. // A stack of instructions being replaced in Subst(). When it's an associated
  516. // constant, then it represents the constant value is being determined,
  517. // represented as an ImplWitnessAccess.
  518. //
  519. // Avoid heap allocations in common cases, if there are chains of instructions
  520. // in associated constants with a depth at most 16.
  521. llvm::SmallVector<SemIR::InstId, 16> substs_in_progress_;
  522. };
  523. auto ResolveFacetTypeRewriteConstraints(
  524. Context& context, SemIR::LocId loc_id,
  525. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>& rewrites)
  526. -> bool {
  527. if (rewrites.empty()) {
  528. return true;
  529. }
  530. AccessRewriteValues rewrite_values;
  531. for (auto& constraint : rewrites) {
  532. auto lhs_access =
  533. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(constraint.lhs_id);
  534. if (!lhs_access) {
  535. continue;
  536. }
  537. rewrite_values.InsertNotRewritten(context, *lhs_access, constraint.rhs_id);
  538. }
  539. for (auto& constraint : rewrites) {
  540. auto lhs_access =
  541. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(constraint.lhs_id);
  542. if (!lhs_access) {
  543. continue;
  544. }
  545. auto* lhs_rewrite_value = rewrite_values.FindRef(context, *lhs_access);
  546. // Every LHS was added with InsertNotRewritten above.
  547. CARBON_CHECK(lhs_rewrite_value);
  548. rewrite_values.SetBeingRewritten(*lhs_rewrite_value);
  549. auto replace_witness_callbacks =
  550. SubstImplWitnessAccessCallbacks(&context, loc_id, &rewrite_values);
  551. auto rhs_subst_inst_id =
  552. SubstInst(context, constraint.rhs_id, replace_witness_callbacks);
  553. if (rhs_subst_inst_id == SemIR::ErrorInst::InstId) {
  554. return false;
  555. }
  556. if (lhs_rewrite_value->state == AccessRewriteValues::FullyRewritten &&
  557. !CompareFacetTypeConstraintValues(context, lhs_rewrite_value->inst_id,
  558. rhs_subst_inst_id)) {
  559. if (lhs_rewrite_value->inst_id != SemIR::ErrorInst::InstId) {
  560. CARBON_DIAGNOSTIC(AssociatedConstantWithDifferentValues, Error,
  561. "associated constant {0} given two different "
  562. "values {1} and {2}",
  563. InstIdAsConstant, InstIdAsConstant, InstIdAsConstant);
  564. // Use inst id ordering as a simple proxy for source ordering, to
  565. // try to name the values in the same order they appear in the facet
  566. // type.
  567. auto source_order1 =
  568. lhs_rewrite_value->inst_id.index < rhs_subst_inst_id.index
  569. ? lhs_rewrite_value->inst_id
  570. : rhs_subst_inst_id;
  571. auto source_order2 =
  572. lhs_rewrite_value->inst_id.index >= rhs_subst_inst_id.index
  573. ? lhs_rewrite_value->inst_id
  574. : rhs_subst_inst_id;
  575. // TODO: It would be nice to note the places where the values are
  576. // assigned but rewrite constraint instructions are from canonical
  577. // constant values, and have no locations. We'd need to store a
  578. // location along with them in the rewrite constraints.
  579. context.emitter().Emit(loc_id, AssociatedConstantWithDifferentValues,
  580. constraint.lhs_id, source_order1, source_order2);
  581. }
  582. return false;
  583. }
  584. rewrite_values.SetFullyRewritten(context, *lhs_rewrite_value,
  585. rhs_subst_inst_id);
  586. }
  587. // Rebuild the `rewrites` vector with resolved values for the RHS. Drop any
  588. // duplicate rewrites in the `rewrites` vector by walking through the
  589. // `rewrite_values` map and dropping the computed RHS value for each LHS the
  590. // first time we see it, and erasing the constraint from the vector if we see
  591. // the same LHS again.
  592. size_t keep_size = rewrites.size();
  593. for (size_t i = 0; i < keep_size;) {
  594. auto& constraint = rewrites[i];
  595. auto lhs_access =
  596. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(constraint.lhs_id);
  597. if (!lhs_access) {
  598. ++i;
  599. continue;
  600. }
  601. auto& rewrite_value = *rewrite_values.FindRef(context, *lhs_access);
  602. auto rhs_id = std::exchange(rewrite_value.inst_id, SemIR::InstId::None);
  603. if (rhs_id == SemIR::InstId::None) {
  604. std::swap(rewrites[i], rewrites[keep_size - 1]);
  605. --keep_size;
  606. } else {
  607. rewrites[i].rhs_id = rhs_id;
  608. ++i;
  609. }
  610. }
  611. rewrites.erase(rewrites.begin() + keep_size, rewrites.end());
  612. return true;
  613. }
  614. } // namespace Carbon::Check