eval_inst.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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/eval_inst.h"
  5. #include <variant>
  6. #include "toolchain/check/action.h"
  7. #include "toolchain/check/diagnostic_helpers.h"
  8. #include "toolchain/check/facet_type.h"
  9. #include "toolchain/check/generic.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/type.h"
  14. #include "toolchain/check/type_completion.h"
  15. #include "toolchain/diagnostics/diagnostic.h"
  16. #include "toolchain/parse/typed_nodes.h"
  17. #include "toolchain/sem_ir/builtin_function_kind.h"
  18. #include "toolchain/sem_ir/expr_info.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. #include "toolchain/sem_ir/pattern.h"
  21. #include "toolchain/sem_ir/typed_insts.h"
  22. namespace Carbon::Check {
  23. // Performs an access into an aggregate, retrieving the specified element.
  24. static auto PerformAggregateAccess(Context& context, SemIR::Inst inst)
  25. -> ConstantEvalResult {
  26. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  27. if (auto aggregate = context.insts().TryGetAs<SemIR::AnyAggregateValue>(
  28. access_inst.aggregate_id)) {
  29. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  30. auto index = static_cast<size_t>(access_inst.index.index);
  31. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  32. // `Phase` is not used here. If this element is a concrete constant, then
  33. // so is the result of indexing, even if the aggregate also contains a
  34. // symbolic context.
  35. return ConstantEvalResult::Existing(
  36. context.constant_values().Get(elements[index]));
  37. }
  38. return ConstantEvalResult::NewSamePhase(inst);
  39. }
  40. auto EvalConstantInst(Context& /*context*/, SemIR::ArrayInit inst)
  41. -> ConstantEvalResult {
  42. // TODO: Add an `ArrayValue` to represent a constant array object
  43. // representation instead of using a `TupleValue`.
  44. return ConstantEvalResult::NewSamePhase(
  45. SemIR::TupleValue{.type_id = inst.type_id, .elements_id = inst.inits_id});
  46. }
  47. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  48. SemIR::ArrayType inst) -> ConstantEvalResult {
  49. auto bound_inst = context.insts().Get(inst.bound_id);
  50. auto int_bound = bound_inst.TryAs<SemIR::IntValue>();
  51. if (!int_bound) {
  52. CARBON_CHECK(context.constant_values().Get(inst.bound_id).is_symbolic(),
  53. "Unexpected inst {0} for template constant int", bound_inst);
  54. return ConstantEvalResult::NewSamePhase(inst);
  55. }
  56. // TODO: We should check that the size of the resulting array type
  57. // fits in 64 bits, not just that the bound does. Should we use a
  58. // 32-bit limit for 32-bit targets?
  59. const auto& bound_val = context.ints().Get(int_bound->int_id);
  60. if (context.types().IsSignedInt(int_bound->type_id) &&
  61. bound_val.isNegative()) {
  62. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  63. "array bound of {0} is negative", TypedInt);
  64. context.emitter().Emit(
  65. context.insts().GetAs<SemIR::ArrayType>(inst_id).bound_id,
  66. ArrayBoundNegative, {.type = int_bound->type_id, .value = bound_val});
  67. return ConstantEvalResult::Error;
  68. }
  69. if (bound_val.getActiveBits() > 64) {
  70. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  71. "array bound of {0} is too large", TypedInt);
  72. context.emitter().Emit(
  73. context.insts().GetAs<SemIR::ArrayType>(inst_id).bound_id,
  74. ArrayBoundTooLarge, {.type = int_bound->type_id, .value = bound_val});
  75. return ConstantEvalResult::Error;
  76. }
  77. return ConstantEvalResult::NewSamePhase(inst);
  78. }
  79. auto EvalConstantInst(Context& context, SemIR::AsCompatible inst)
  80. -> ConstantEvalResult {
  81. // AsCompatible changes the type of the source instruction; its constant
  82. // value, if there is one, needs to be modified to be of the same type.
  83. auto value_id = context.constant_values().Get(inst.source_id);
  84. CARBON_CHECK(value_id.is_constant());
  85. auto value_inst =
  86. context.insts().Get(context.constant_values().GetInstId(value_id));
  87. value_inst.SetType(inst.type_id);
  88. return ConstantEvalResult::NewAnyPhase(value_inst);
  89. }
  90. auto EvalConstantInst(Context& context, SemIR::AliasBinding inst)
  91. -> ConstantEvalResult {
  92. // An alias evaluates to the value it's bound to.
  93. return ConstantEvalResult::Existing(
  94. context.constant_values().Get(inst.value_id));
  95. }
  96. auto EvalConstantInst(Context& context, SemIR::RefBinding inst)
  97. -> ConstantEvalResult {
  98. // A reference binding evaluates to the value it's bound to.
  99. if (inst.value_id.has_value()) {
  100. return ConstantEvalResult::Existing(
  101. context.constant_values().Get(inst.value_id));
  102. }
  103. return ConstantEvalResult::NotConstant;
  104. }
  105. auto EvalConstantInst(Context& /*context*/, SemIR::ValueBinding /*inst*/)
  106. -> ConstantEvalResult {
  107. // Non-`:!` value bindings are not constant.
  108. return ConstantEvalResult::NotConstant;
  109. }
  110. auto EvalConstantInst(Context& /*context*/, SemIR::AcquireValue /*inst*/)
  111. -> ConstantEvalResult {
  112. // TODO: Handle this once we've decided how to represent constant values of
  113. // reference expressions.
  114. return ConstantEvalResult::TODO;
  115. }
  116. auto EvalConstantInst(Context& context, SemIR::ClassElementAccess inst)
  117. -> ConstantEvalResult {
  118. return PerformAggregateAccess(context, inst);
  119. }
  120. auto EvalConstantInst(Context& context, SemIR::ClassDecl inst)
  121. -> ConstantEvalResult {
  122. const auto& class_info = context.classes().Get(inst.class_id);
  123. // If the class has generic parameters, we don't produce a class type, but a
  124. // callable whose return value is a class type.
  125. if (class_info.has_parameters()) {
  126. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  127. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  128. }
  129. // A non-generic class declaration evaluates to the class type.
  130. return ConstantEvalResult::NewAnyPhase(SemIR::ClassType{
  131. .type_id = SemIR::TypeType::TypeId,
  132. .class_id = inst.class_id,
  133. .specific_id =
  134. context.generics().GetSelfSpecific(class_info.generic_id)});
  135. }
  136. auto EvalConstantInst(Context& /*context*/, SemIR::ClassInit inst)
  137. -> ConstantEvalResult {
  138. // TODO: Add a `ClassValue` to represent a constant class object
  139. // representation instead of using a `StructValue`.
  140. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  141. .type_id = inst.type_id, .elements_id = inst.elements_id});
  142. }
  143. auto EvalConstantInst(Context& context, SemIR::ConstType inst)
  144. -> ConstantEvalResult {
  145. // `const (const T)` evaluates to `const T`.
  146. if (context.insts().Is<SemIR::ConstType>(inst.inner_id)) {
  147. return ConstantEvalResult::Existing(
  148. context.constant_values().Get(inst.inner_id));
  149. }
  150. // Otherwise, `const T` evaluates to itself.
  151. return ConstantEvalResult::NewSamePhase(inst);
  152. }
  153. auto EvalConstantInst(Context& /*context*/, SemIR::PartialType inst)
  154. -> ConstantEvalResult {
  155. return ConstantEvalResult::NewSamePhase(inst);
  156. }
  157. auto EvalConstantInst(Context& context, SemIR::Converted inst)
  158. -> ConstantEvalResult {
  159. // A conversion evaluates to the result of the conversion.
  160. return ConstantEvalResult::Existing(
  161. context.constant_values().Get(inst.result_id));
  162. }
  163. auto EvalConstantInst(Context& /*context*/, SemIR::Deref /*inst*/)
  164. -> ConstantEvalResult {
  165. // TODO: Handle this.
  166. return ConstantEvalResult::TODO;
  167. }
  168. auto EvalConstantInst(Context& context, SemIR::ExportDecl inst)
  169. -> ConstantEvalResult {
  170. // An export instruction evaluates to the exported declaration.
  171. return ConstantEvalResult::Existing(
  172. context.constant_values().Get(inst.value_id));
  173. }
  174. auto EvalConstantInst(Context& context, SemIR::FacetAccessType inst)
  175. -> ConstantEvalResult {
  176. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  177. inst.facet_value_inst_id)) {
  178. return ConstantEvalResult::Existing(
  179. context.constant_values().Get(facet_value->type_inst_id));
  180. }
  181. if (auto bind_name = context.insts().TryGetAs<SemIR::SymbolicBinding>(
  182. inst.facet_value_inst_id)) {
  183. return ConstantEvalResult::NewSamePhase(SemIR::SymbolicBindingType{
  184. .type_id = SemIR::TypeType::TypeId,
  185. .entity_name_id = bind_name->entity_name_id,
  186. // TODO: This is to be removed, at which point explore if we should
  187. // replace NewSamePhase with NewAnyPhase (to make the constant value
  188. // concrete). This is still a symbolic type though even if the inst
  189. // doesn't contain a symbolic constant. Previously we crashed in CHECKs
  190. // when we had a symbolic instruction with only an EntityNameId, due to
  191. // it not changing in a generic eval block. Maybe that has improved in
  192. // the latest version of this instruction. If it's not symbolic, then
  193. // SubstConstantCallbacks and other Subst callers may need to handle
  194. // looking through concrete instructions which would be unfortunate.
  195. .facet_value_inst_id = inst.facet_value_inst_id});
  196. }
  197. // The `facet_value_inst_id` is always a facet value (has type facet type).
  198. CARBON_CHECK(context.types().Is<SemIR::FacetType>(
  199. context.insts().Get(inst.facet_value_inst_id).type_id()));
  200. // Other instructions (e.g. ImplWitnessAccess) of type FacetType can appear
  201. // here, in which case the constant inst is a FacetAccessType until those
  202. // instructions resolve to one of the above.
  203. return ConstantEvalResult::NewSamePhase(inst);
  204. }
  205. auto EvalConstantInst(Context& context, SemIR::FacetValue inst)
  206. -> ConstantEvalResult {
  207. // A FacetValue that just wraps a SymbolicBinding without adding/removing any
  208. // witnesses is evaluated back to the SymbolicBinding itself.
  209. if (auto bind_as_type = context.insts().TryGetAs<SemIR::SymbolicBindingType>(
  210. inst.type_inst_id)) {
  211. // TODO: Look in ScopeStack with the entity_name_id to find the facet value.
  212. auto bind_id = bind_as_type->facet_value_inst_id;
  213. auto bind = context.insts().GetAs<SemIR::SymbolicBinding>(bind_id);
  214. // If the FacetTypes are the same, then the FacetValue didn't add/remove
  215. // any witnesses.
  216. if (bind.type_id == inst.type_id) {
  217. return ConstantEvalResult::Existing(
  218. context.constant_values().Get(bind_id));
  219. }
  220. }
  221. return ConstantEvalResult::NewSamePhase(inst);
  222. }
  223. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  224. SemIR::FloatType inst) -> ConstantEvalResult {
  225. return ValidateFloatTypeAndSetKind(context, SemIR::LocId(inst_id), inst)
  226. ? ConstantEvalResult::NewSamePhase(inst)
  227. : ConstantEvalResult::Error;
  228. }
  229. auto EvalConstantInst(Context& /*context*/, SemIR::FunctionDecl inst)
  230. -> ConstantEvalResult {
  231. // A function declaration evaluates to a function object, which is an empty
  232. // object of function type.
  233. // TODO: Eventually we may need to handle captures here.
  234. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  235. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  236. }
  237. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  238. SemIR::LookupImplWitness inst) -> ConstantEvalResult {
  239. // The self value is canonicalized in order to produce a canonical
  240. // LookupImplWitness instruction, avoiding multiple constant values for
  241. // `<facet value>` and `<facet value>` as type, which always have the same
  242. // lookup result.
  243. auto self_facet_value_inst_id =
  244. GetCanonicalFacetOrTypeValue(context, inst.query_self_inst_id);
  245. // When we look for a witness in the (facet) type of self, we may get a
  246. // concrete witness from a `FacetValue` (which is `self_facet_value_inst_id`)
  247. // in which case this instruction evaluates to that witness.
  248. //
  249. // If we only get a symbolic witness result though, then this instruction
  250. // evaluates to a `LookupImplWitness`. Since there was no concrete result in
  251. // the `FacetValue`, we don't need to preserve it. By looking through the
  252. // `FacetValue` at the type value it wraps to generate a more canonical value
  253. // for a symbolic `LookupImplWitness`. This makes us produce the same constant
  254. // value for symbolic lookups in `FacetValue(T)` and `T`, since they will
  255. // always have the same lookup result later, when `T` is replaced in a
  256. // specific by something that can provide a concrete witness.
  257. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  258. self_facet_value_inst_id)) {
  259. inst.query_self_inst_id =
  260. GetCanonicalFacetOrTypeValue(context, facet_value->type_inst_id);
  261. } else {
  262. inst.query_self_inst_id = self_facet_value_inst_id;
  263. }
  264. auto result = EvalLookupSingleImplWitness(context, SemIR::LocId(inst_id),
  265. inst, self_facet_value_inst_id,
  266. /*poison_final_results=*/true);
  267. if (!result.has_value()) {
  268. // We use NotConstant to communicate back to impl lookup that the lookup
  269. // failed. This can not happen for a deferred symbolic lookup in a generic
  270. // eval block, since we only add the deferred lookup instruction (being
  271. // evaluated here) to the SemIR if the lookup succeeds.
  272. return ConstantEvalResult::NotConstant;
  273. }
  274. if (result.has_final_value()) {
  275. return ConstantEvalResult::Existing(
  276. context.constant_values().Get(result.final_witness()));
  277. }
  278. return ConstantEvalResult::NewSamePhase(inst);
  279. }
  280. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  281. SemIR::ImplWitnessAccess inst) -> ConstantEvalResult {
  282. if (auto witness =
  283. context.insts().TryGetAs<SemIR::ImplWitness>(inst.witness_id)) {
  284. // This is PerformAggregateAccess followed by GetConstantValueInSpecific.
  285. auto witness_table = context.insts().GetAs<SemIR::ImplWitnessTable>(
  286. witness->witness_table_id);
  287. auto elements = context.inst_blocks().Get(witness_table.elements_id);
  288. // `elements` can be empty if there is only a forward declaration of the
  289. // impl.
  290. if (!elements.empty()) {
  291. auto index = static_cast<size_t>(inst.index.index);
  292. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  293. auto element = elements[index];
  294. if (element.has_value()) {
  295. LoadImportRef(context, element);
  296. return ConstantEvalResult::Existing(GetConstantValueInSpecific(
  297. context.sem_ir(), witness->specific_id, element));
  298. }
  299. }
  300. CARBON_DIAGNOSTIC(
  301. ImplAccessMemberBeforeSet, Error,
  302. "accessing member from impl before it has a defined value");
  303. // TODO: Add note pointing to the impl declaration.
  304. context.emitter().Emit(inst_id, ImplAccessMemberBeforeSet);
  305. return ConstantEvalResult::Error;
  306. } else if (auto witness = context.insts().TryGetAs<SemIR::LookupImplWitness>(
  307. inst.witness_id)) {
  308. // If the witness is symbolic but has a self type that is a FacetType, it
  309. // can pull rewrite values from the self type. If the access is for one of
  310. // those rewrites, evaluate to the RHS of the rewrite.
  311. auto witness_self_type_id =
  312. context.insts().Get(witness->query_self_inst_id).type_id();
  313. if (!context.types().Is<SemIR::FacetType>(witness_self_type_id)) {
  314. return ConstantEvalResult::NewSamePhase(inst);
  315. }
  316. // The `ImplWitnessAccess` is accessing a value, by index, for this
  317. // interface.
  318. auto access_interface_id = witness->query_specific_interface_id;
  319. auto witness_self_facet_type_id =
  320. context.types()
  321. .GetAs<SemIR::FacetType>(witness_self_type_id)
  322. .facet_type_id;
  323. // TODO: We could consider something better than linear search here, such as
  324. // a map. However that would probably require heap allocations which may be
  325. // worse overall since the number of rewrite constraints is generally low.
  326. // If the `rewrite_constraints` were sorted so that associated constants are
  327. // grouped together, as in ResolveFacetTypeRewriteConstraints(), and limited
  328. // to just the `ImplWitnessAccess` entries, then a binary search may work
  329. // here.
  330. for (auto witness_rewrite : context.facet_types()
  331. .Get(witness_self_facet_type_id)
  332. .rewrite_constraints) {
  333. // Look at each rewrite constraint in the self facet value's type. If the
  334. // LHS is an `ImplWitnessAccess` into the same interface that `inst` is
  335. // indexing into, then we can use its RHS as the value.
  336. auto witness_rewrite_lhs_access =
  337. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(
  338. witness_rewrite.lhs_id);
  339. if (!witness_rewrite_lhs_access) {
  340. continue;
  341. }
  342. if (witness_rewrite_lhs_access->index != inst.index) {
  343. continue;
  344. }
  345. auto witness_rewrite_lhs_interface_id =
  346. context.insts()
  347. .GetAs<SemIR::LookupImplWitness>(
  348. witness_rewrite_lhs_access->witness_id)
  349. .query_specific_interface_id;
  350. if (witness_rewrite_lhs_interface_id != access_interface_id) {
  351. continue;
  352. }
  353. // The `ImplWitnessAccess` evaluates to the RHS from the witness self
  354. // facet value's type.
  355. return ConstantEvalResult::Existing(
  356. context.constant_values().Get(witness_rewrite.rhs_id));
  357. }
  358. }
  359. return ConstantEvalResult::NewSamePhase(inst);
  360. }
  361. auto EvalConstantInst(Context& context,
  362. SemIR::ImplWitnessAccessSubstituted inst)
  363. -> ConstantEvalResult {
  364. return ConstantEvalResult::Existing(
  365. context.constant_values().Get(inst.value_id));
  366. }
  367. auto EvalConstantInst(Context& context,
  368. SemIR::ImplWitnessAssociatedConstant inst)
  369. -> ConstantEvalResult {
  370. return ConstantEvalResult::Existing(
  371. context.constant_values().Get(inst.inst_id));
  372. }
  373. auto EvalConstantInst(Context& /*context*/, SemIR::ImportRefUnloaded inst)
  374. -> ConstantEvalResult {
  375. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  376. inst);
  377. }
  378. auto EvalConstantInst(Context& context, SemIR::InitializeFrom inst)
  379. -> ConstantEvalResult {
  380. // Initialization is not performed in-place during constant evaluation, so
  381. // just return the value of the initializer.
  382. return ConstantEvalResult::Existing(
  383. context.constant_values().Get(inst.src_id));
  384. }
  385. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  386. SemIR::IntType inst) -> ConstantEvalResult {
  387. return ValidateIntType(context, SemIR::LocId(inst_id), inst)
  388. ? ConstantEvalResult::NewSamePhase(inst)
  389. : ConstantEvalResult::Error;
  390. }
  391. auto EvalConstantInst(Context& context, SemIR::InterfaceDecl inst)
  392. -> ConstantEvalResult {
  393. const auto& interface_info = context.interfaces().Get(inst.interface_id);
  394. // If the interface has generic parameters, we don't produce an interface
  395. // type, but a callable whose return value is an interface type.
  396. if (interface_info.has_parameters()) {
  397. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  398. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  399. }
  400. // A non-parameterized interface declaration evaluates to a declared facet
  401. // type containing just the interface.
  402. return ConstantEvalResult::NewAnyPhase(FacetTypeFromInterface(
  403. context, inst.interface_id,
  404. context.generics().GetSelfSpecific(interface_info.generic_id)));
  405. }
  406. auto EvalConstantInst(Context& context, SemIR::NamedConstraintDecl inst)
  407. -> ConstantEvalResult {
  408. const auto& named_constraint_info =
  409. context.named_constraints().Get(inst.named_constraint_id);
  410. // If the named constraint has generic parameters, we don't produce a named
  411. // constraint type, but a callable whose return value is a named constraint
  412. // type.
  413. if (named_constraint_info.has_parameters()) {
  414. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  415. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  416. }
  417. // A non-parameterized named constraint declaration evaluates to a declared
  418. // facet type containing just the named constraint.
  419. return ConstantEvalResult::NewAnyPhase(FacetTypeFromNamedConstraint(
  420. context, inst.named_constraint_id,
  421. context.generics().GetSelfSpecific(named_constraint_info.generic_id)));
  422. }
  423. auto EvalConstantInst(Context& context, SemIR::NameRef inst)
  424. -> ConstantEvalResult {
  425. // A name reference evaluates to the value the name resolves to.
  426. return ConstantEvalResult::Existing(
  427. context.constant_values().Get(inst.value_id));
  428. }
  429. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  430. SemIR::RequireCompleteType inst) -> ConstantEvalResult {
  431. auto witness_type_id =
  432. GetSingletonType(context, SemIR::WitnessType::TypeInstId);
  433. // If the type is a concrete constant, require it to be complete now.
  434. auto complete_type_id =
  435. context.types().GetTypeIdForTypeInstId(inst.complete_type_inst_id);
  436. if (complete_type_id.is_concrete()) {
  437. if (!TryToCompleteType(
  438. context, complete_type_id, SemIR::LocId(inst_id), [&] {
  439. CARBON_DIAGNOSTIC(IncompleteTypeInMonomorphization, Error,
  440. "{0} evaluates to incomplete type {1}",
  441. InstIdAsType, InstIdAsType);
  442. return context.emitter().Build(
  443. inst_id, IncompleteTypeInMonomorphization,
  444. context.insts()
  445. .GetAs<SemIR::RequireCompleteType>(inst_id)
  446. .complete_type_inst_id,
  447. inst.complete_type_inst_id);
  448. })) {
  449. return ConstantEvalResult::Error;
  450. }
  451. return ConstantEvalResult::NewSamePhase(SemIR::CompleteTypeWitness{
  452. .type_id = witness_type_id,
  453. .object_repr_type_inst_id = context.types().GetInstId(
  454. context.types().GetObjectRepr(complete_type_id))});
  455. }
  456. // If it's not a concrete constant, require it to be complete once it
  457. // becomes one.
  458. return ConstantEvalResult::NewSamePhase(inst);
  459. }
  460. auto EvalConstantInst(Context& context, SemIR::SpecificConstant inst)
  461. -> ConstantEvalResult {
  462. // Pull the constant value out of the specific.
  463. return ConstantEvalResult::Existing(SemIR::GetConstantValueInSpecific(
  464. context.sem_ir(), inst.specific_id, inst.inst_id));
  465. }
  466. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  467. SemIR::SpecificImplFunction inst) -> ConstantEvalResult {
  468. auto callee_inst = context.insts().Get(inst.callee_id);
  469. // If the callee is not a function value, we're not ready to evaluate this
  470. // yet. Build a symbolic `SpecificImplFunction` constant.
  471. if (!callee_inst.Is<SemIR::StructValue>()) {
  472. return ConstantEvalResult::NewSamePhase(inst);
  473. }
  474. auto callee_type_id = callee_inst.type_id();
  475. auto callee_fn_type =
  476. context.types().TryGetAs<SemIR::FunctionType>(callee_type_id);
  477. if (!callee_fn_type) {
  478. return ConstantEvalResult::NewSamePhase(inst);
  479. }
  480. // If the callee function found in the impl witness is not generic, the result
  481. // is simply that function.
  482. // TODO: We could do this even before the callee is concrete.
  483. auto generic_id =
  484. context.functions().Get(callee_fn_type->function_id).generic_id;
  485. if (!generic_id.has_value()) {
  486. return ConstantEvalResult::Existing(
  487. context.constant_values().Get(inst.callee_id));
  488. }
  489. // Find the arguments to use.
  490. auto enclosing_specific_id = callee_fn_type->specific_id;
  491. auto enclosing_args = context.inst_blocks().Get(
  492. context.specifics().GetArgsOrEmpty(enclosing_specific_id));
  493. auto interface_fn_args = context.inst_blocks().Get(
  494. context.specifics().GetArgsOrEmpty(inst.specific_id));
  495. // Form new specific for the generic callee function. The arguments for this
  496. // specific are the enclosing arguments of the callee followed by the
  497. // remaining arguments from the interface function. Impl checking has ensured
  498. // that these arguments can also be used for the function in the impl witness.
  499. auto num_params = context.inst_blocks()
  500. .Get(context.generics().Get(generic_id).bindings_id)
  501. .size();
  502. llvm::SmallVector<SemIR::InstId> args;
  503. args.reserve(num_params);
  504. args.append(enclosing_args.begin(), enclosing_args.end());
  505. int remaining_params = num_params - args.size();
  506. CARBON_CHECK(static_cast<int>(interface_fn_args.size()) >= remaining_params);
  507. args.append(interface_fn_args.end() - remaining_params,
  508. interface_fn_args.end());
  509. auto specific_id =
  510. MakeSpecific(context, SemIR::LocId(inst_id), generic_id, args);
  511. context.definitions_required_by_use().push_back(
  512. {SemIR::LocId(inst_id), specific_id});
  513. return ConstantEvalResult::NewSamePhase(
  514. SemIR::SpecificFunction{.type_id = inst.type_id,
  515. .callee_id = inst.callee_id,
  516. .specific_id = specific_id});
  517. }
  518. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  519. SemIR::SpecificFunction inst) -> ConstantEvalResult {
  520. auto callee_function =
  521. SemIR::GetCalleeAsFunction(context.sem_ir(), inst.callee_id);
  522. const auto& fn = context.functions().Get(callee_function.function_id);
  523. if (!callee_function.self_type_id.has_value() &&
  524. fn.builtin_function_kind() != SemIR::BuiltinFunctionKind::NoOp &&
  525. fn.virtual_modifier != SemIR::Function::VirtualModifier::Abstract) {
  526. // This is not an associated function. Those will be required to be defined
  527. // as part of checking that the impl is complete.
  528. context.definitions_required_by_use().push_back(
  529. {SemIR::LocId(inst_id), inst.specific_id});
  530. }
  531. // Create new constant for a specific function.
  532. return ConstantEvalResult::NewSamePhase(inst);
  533. }
  534. auto EvalConstantInst(Context& context, SemIR::SpliceBlock inst)
  535. -> ConstantEvalResult {
  536. // SpliceBlock evaluates to the result value that is (typically) within the
  537. // block. This can be constant even if the block contains other non-constant
  538. // instructions.
  539. return ConstantEvalResult::Existing(
  540. context.constant_values().Get(inst.result_id));
  541. }
  542. auto EvalConstantInst(Context& context, SemIR::SpliceInst inst)
  543. -> ConstantEvalResult {
  544. // The constant value of a SpliceInst is the constant value of the instruction
  545. // being spliced. Note that `inst.inst_id` is the instruction being spliced,
  546. // so we need to go through another round of obtaining the constant value in
  547. // addition to the one performed by the eval infrastructure.
  548. if (auto inst_value =
  549. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  550. return ConstantEvalResult::Existing(
  551. context.constant_values().Get(inst_value->inst_id));
  552. }
  553. // TODO: Consider creating a new `ValueOfInst` instruction analogous to
  554. // `TypeOfInst` to defer determining the constant value until we know the
  555. // instruction. Alternatively, produce a symbolic `SpliceInst` constant.
  556. return ConstantEvalResult::NotConstant;
  557. }
  558. auto EvalConstantInst(Context& context, SemIR::StructAccess inst)
  559. -> ConstantEvalResult {
  560. return PerformAggregateAccess(context, inst);
  561. }
  562. auto EvalConstantInst(Context& /*context*/, SemIR::StructInit inst)
  563. -> ConstantEvalResult {
  564. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  565. .type_id = inst.type_id, .elements_id = inst.elements_id});
  566. }
  567. auto EvalConstantInst(Context& /*context*/, SemIR::StructLiteral inst)
  568. -> ConstantEvalResult {
  569. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  570. .type_id = inst.type_id, .elements_id = inst.elements_id});
  571. }
  572. auto EvalConstantInst(Context& /*context*/, SemIR::Temporary /*inst*/)
  573. -> ConstantEvalResult {
  574. // TODO: Handle this. Can we just return the value of `init_id`?
  575. return ConstantEvalResult::TODO;
  576. }
  577. auto EvalConstantInst(Context& context, SemIR::TupleAccess inst)
  578. -> ConstantEvalResult {
  579. return PerformAggregateAccess(context, inst);
  580. }
  581. auto EvalConstantInst(Context& /*context*/, SemIR::TupleInit inst)
  582. -> ConstantEvalResult {
  583. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  584. .type_id = inst.type_id, .elements_id = inst.elements_id});
  585. }
  586. auto EvalConstantInst(Context& /*context*/, SemIR::TupleLiteral inst)
  587. -> ConstantEvalResult {
  588. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  589. .type_id = inst.type_id, .elements_id = inst.elements_id});
  590. }
  591. auto EvalConstantInst(Context& context, SemIR::TypeOfInst inst)
  592. -> ConstantEvalResult {
  593. // Grab the type from the instruction produced as our operand.
  594. if (auto inst_value =
  595. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  596. return ConstantEvalResult::Existing(context.types().GetConstantId(
  597. context.insts().Get(inst_value->inst_id).type_id()));
  598. }
  599. return ConstantEvalResult::NewSamePhase(inst);
  600. }
  601. auto EvalConstantInst(Context& context, SemIR::UnaryOperatorNot inst)
  602. -> ConstantEvalResult {
  603. // `not true` -> `false`, `not false` -> `true`.
  604. // All other uses of unary `not` are non-constant.
  605. auto const_id = context.constant_values().Get(inst.operand_id);
  606. if (const_id.is_concrete()) {
  607. auto value = context.insts().GetAs<SemIR::BoolLiteral>(
  608. context.constant_values().GetInstId(const_id));
  609. value.value = SemIR::BoolValue::From(!value.value.ToBool());
  610. return ConstantEvalResult::NewSamePhase(value);
  611. }
  612. return ConstantEvalResult::NotConstant;
  613. }
  614. auto EvalConstantInst(Context& context, SemIR::ValueOfInitializer inst)
  615. -> ConstantEvalResult {
  616. // Values of value expressions and initializing expressions are represented in
  617. // the same way during constant evaluation, so just return the value of the
  618. // operand.
  619. return ConstantEvalResult::Existing(
  620. context.constant_values().Get(inst.init_id));
  621. }
  622. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  623. SemIR::VarStorage inst) -> ConstantEvalResult {
  624. if (!inst.pattern_id.has_value()) {
  625. // This variable was not created from a `var` pattern, so isn't a global
  626. // variable.
  627. return ConstantEvalResult::NotConstant;
  628. }
  629. // A variable is constant if it's global.
  630. auto entity_name_id = SemIR::GetFirstBindingNameFromPatternId(
  631. context.sem_ir(), inst.pattern_id);
  632. if (!entity_name_id.has_value()) {
  633. // Variable doesn't introduce any bindings, so can only be referenced by its
  634. // own initializer. We treat such a reference as not being constant.
  635. return ConstantEvalResult::NotConstant;
  636. }
  637. auto scope_id = context.entity_names().Get(entity_name_id).parent_scope_id;
  638. if (!scope_id.has_value() ||
  639. !context.insts().Is<SemIR::Namespace>(
  640. context.name_scopes().Get(scope_id).inst_id())) {
  641. // Only namespace-scope variables are reference constants.
  642. return ConstantEvalResult::NotConstant;
  643. }
  644. // This is a constant reference expression denoting this global variable.
  645. return ConstantEvalResult::Existing(
  646. SemIR::ConstantId::ForConcreteConstant(inst_id));
  647. }
  648. } // namespace Carbon::Check