eval_inst.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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. EvalImplLookupMode::Normal);
  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. CARBON_DIAGNOSTIC(ImplAccessMemberBeforeSet, Error,
  283. "accessing member from impl before it has a defined value");
  284. if (auto witness =
  285. context.insts().TryGetAs<SemIR::ImplWitness>(inst.witness_id)) {
  286. // This is PerformAggregateAccess followed by GetConstantValueInSpecific.
  287. auto witness_table = context.insts().GetAs<SemIR::ImplWitnessTable>(
  288. witness->witness_table_id);
  289. auto elements = context.inst_blocks().Get(witness_table.elements_id);
  290. // `elements` can be empty if there is only a forward declaration of the
  291. // impl.
  292. if (!elements.empty()) {
  293. auto index = static_cast<size_t>(inst.index.index);
  294. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  295. auto element = elements[index];
  296. if (element.has_value()) {
  297. LoadImportRef(context, element);
  298. return ConstantEvalResult::Existing(GetConstantValueInSpecific(
  299. context.sem_ir(), witness->specific_id, element));
  300. }
  301. }
  302. // If we get here, this impl witness table entry has not been populated yet,
  303. // because the impl was referenced within its own definition.
  304. // TODO: Add note pointing to the impl declaration.
  305. context.emitter().Emit(inst_id, ImplAccessMemberBeforeSet);
  306. return ConstantEvalResult::Error;
  307. } else if (auto cpp_witness =
  308. context.insts().TryGetAs<SemIR::CppWitness>(inst.witness_id)) {
  309. auto elements = context.inst_blocks().Get(cpp_witness->elements_id);
  310. auto index = static_cast<size_t>(inst.index.index);
  311. // `elements` can be shorter than the number of associated entities while
  312. // we're building the synthetic witness.
  313. if (index < elements.size()) {
  314. return ConstantEvalResult::Existing(
  315. context.constant_values().Get(elements[index]));
  316. }
  317. // If we get here, this synthesized witness table entry has not been
  318. // populated yet.
  319. // TODO: Is this reachable? We have no test coverage for this diagnostic.
  320. context.emitter().Emit(inst_id, ImplAccessMemberBeforeSet);
  321. return ConstantEvalResult::Error;
  322. } else if (auto witness = context.insts().TryGetAs<SemIR::LookupImplWitness>(
  323. inst.witness_id)) {
  324. // If the witness is symbolic but has a self type that is a FacetType, it
  325. // can pull rewrite values from the self type. If the access is for one of
  326. // those rewrites, evaluate to the RHS of the rewrite.
  327. auto witness_self_type_id =
  328. context.insts().Get(witness->query_self_inst_id).type_id();
  329. if (!context.types().Is<SemIR::FacetType>(witness_self_type_id)) {
  330. return ConstantEvalResult::NewSamePhase(inst);
  331. }
  332. // The `ImplWitnessAccess` is accessing a value, by index, for this
  333. // interface.
  334. auto access_interface_id = witness->query_specific_interface_id;
  335. auto witness_self_facet_type_id =
  336. context.types()
  337. .GetAs<SemIR::FacetType>(witness_self_type_id)
  338. .facet_type_id;
  339. // TODO: We could consider something better than linear search here, such as
  340. // a map. However that would probably require heap allocations which may be
  341. // worse overall since the number of rewrite constraints is generally low.
  342. // If the `rewrite_constraints` were sorted so that associated constants are
  343. // grouped together, as in ResolveFacetTypeRewriteConstraints(), and limited
  344. // to just the `ImplWitnessAccess` entries, then a binary search may work
  345. // here.
  346. for (auto witness_rewrite : context.facet_types()
  347. .Get(witness_self_facet_type_id)
  348. .rewrite_constraints) {
  349. // Look at each rewrite constraint in the self facet value's type. If the
  350. // LHS is an `ImplWitnessAccess` into the same interface that `inst` is
  351. // indexing into, then we can use its RHS as the value.
  352. auto witness_rewrite_lhs_access =
  353. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(
  354. witness_rewrite.lhs_id);
  355. if (!witness_rewrite_lhs_access) {
  356. continue;
  357. }
  358. if (witness_rewrite_lhs_access->index != inst.index) {
  359. continue;
  360. }
  361. auto witness_rewrite_lhs_interface_id =
  362. context.insts()
  363. .GetAs<SemIR::LookupImplWitness>(
  364. witness_rewrite_lhs_access->witness_id)
  365. .query_specific_interface_id;
  366. if (witness_rewrite_lhs_interface_id != access_interface_id) {
  367. continue;
  368. }
  369. // The `ImplWitnessAccess` evaluates to the RHS from the witness self
  370. // facet value's type.
  371. return ConstantEvalResult::Existing(
  372. context.constant_values().Get(witness_rewrite.rhs_id));
  373. }
  374. }
  375. return ConstantEvalResult::NewSamePhase(inst);
  376. }
  377. auto EvalConstantInst(Context& context,
  378. SemIR::ImplWitnessAccessSubstituted inst)
  379. -> ConstantEvalResult {
  380. return ConstantEvalResult::Existing(
  381. context.constant_values().Get(inst.value_id));
  382. }
  383. auto EvalConstantInst(Context& context,
  384. SemIR::ImplWitnessAssociatedConstant inst)
  385. -> ConstantEvalResult {
  386. return ConstantEvalResult::Existing(
  387. context.constant_values().Get(inst.inst_id));
  388. }
  389. auto EvalConstantInst(Context& /*context*/, SemIR::ImportRefUnloaded inst)
  390. -> ConstantEvalResult {
  391. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  392. inst);
  393. }
  394. auto EvalConstantInst(Context& context, SemIR::InitializeFrom inst)
  395. -> ConstantEvalResult {
  396. // Initialization is not performed in-place during constant evaluation, so
  397. // just return the value of the initializer.
  398. return ConstantEvalResult::Existing(
  399. context.constant_values().Get(inst.src_id));
  400. }
  401. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  402. SemIR::IntType inst) -> ConstantEvalResult {
  403. return ValidateIntType(context, SemIR::LocId(inst_id), inst)
  404. ? ConstantEvalResult::NewSamePhase(inst)
  405. : ConstantEvalResult::Error;
  406. }
  407. auto EvalConstantInst(Context& context, SemIR::InterfaceDecl inst)
  408. -> ConstantEvalResult {
  409. const auto& interface_info = context.interfaces().Get(inst.interface_id);
  410. // If the interface has generic parameters, we don't produce an interface
  411. // type, but a callable whose return value is an interface type.
  412. if (interface_info.has_parameters()) {
  413. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  414. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  415. }
  416. // A non-parameterized interface declaration evaluates to a declared facet
  417. // type containing just the interface.
  418. return ConstantEvalResult::NewAnyPhase(FacetTypeFromInterface(
  419. context, inst.interface_id,
  420. context.generics().GetSelfSpecific(interface_info.generic_id)));
  421. }
  422. auto EvalConstantInst(Context& context, SemIR::NamedConstraintDecl inst)
  423. -> ConstantEvalResult {
  424. const auto& named_constraint_info =
  425. context.named_constraints().Get(inst.named_constraint_id);
  426. // If the named constraint has generic parameters, we don't produce a named
  427. // constraint type, but a callable whose return value is a named constraint
  428. // type.
  429. if (named_constraint_info.has_parameters()) {
  430. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  431. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  432. }
  433. // A non-parameterized named constraint declaration evaluates to a declared
  434. // facet type containing just the named constraint.
  435. return ConstantEvalResult::NewAnyPhase(FacetTypeFromNamedConstraint(
  436. context, inst.named_constraint_id,
  437. context.generics().GetSelfSpecific(named_constraint_info.generic_id)));
  438. }
  439. auto EvalConstantInst(Context& context, SemIR::NameRef inst)
  440. -> ConstantEvalResult {
  441. // A name reference evaluates to the value the name resolves to.
  442. return ConstantEvalResult::Existing(
  443. context.constant_values().Get(inst.value_id));
  444. }
  445. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  446. SemIR::RequireCompleteType inst) -> ConstantEvalResult {
  447. auto witness_type_id =
  448. GetSingletonType(context, SemIR::WitnessType::TypeInstId);
  449. // If the type is a concrete constant, require it to be complete now.
  450. auto complete_type_id =
  451. context.types().GetTypeIdForTypeInstId(inst.complete_type_inst_id);
  452. if (complete_type_id.is_concrete()) {
  453. if (!TryToCompleteType(
  454. context, complete_type_id, SemIR::LocId(inst_id), [&] {
  455. CARBON_DIAGNOSTIC(IncompleteTypeInMonomorphization, Error,
  456. "{0} evaluates to incomplete type {1}",
  457. InstIdAsType, InstIdAsType);
  458. return context.emitter().Build(
  459. inst_id, IncompleteTypeInMonomorphization,
  460. context.insts()
  461. .GetAs<SemIR::RequireCompleteType>(inst_id)
  462. .complete_type_inst_id,
  463. inst.complete_type_inst_id);
  464. })) {
  465. return ConstantEvalResult::Error;
  466. }
  467. return ConstantEvalResult::NewSamePhase(SemIR::CompleteTypeWitness{
  468. .type_id = witness_type_id,
  469. .object_repr_type_inst_id = context.types().GetInstId(
  470. context.types().GetObjectRepr(complete_type_id))});
  471. }
  472. // If it's not a concrete constant, require it to be complete once it
  473. // becomes one.
  474. return ConstantEvalResult::NewSamePhase(inst);
  475. }
  476. auto EvalConstantInst(Context& context, SemIR::RequireSpecificDefinition inst)
  477. -> ConstantEvalResult {
  478. // This can return false, we just need to try it.
  479. ResolveSpecificDefinition(context, SemIR::LocId::None, inst.specific_id);
  480. return ConstantEvalResult::NewSamePhase(inst);
  481. }
  482. auto EvalConstantInst(Context& context, SemIR::SpecificConstant inst)
  483. -> ConstantEvalResult {
  484. // Pull the constant value out of the specific.
  485. return ConstantEvalResult::Existing(SemIR::GetConstantValueInSpecific(
  486. context.sem_ir(), inst.specific_id, inst.inst_id));
  487. }
  488. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  489. SemIR::SpecificImplFunction inst) -> ConstantEvalResult {
  490. auto callee_inst = context.insts().Get(inst.callee_id);
  491. // If the callee is not a function value, we're not ready to evaluate this
  492. // yet. Build a symbolic `SpecificImplFunction` constant.
  493. if (!callee_inst.Is<SemIR::StructValue>()) {
  494. return ConstantEvalResult::NewSamePhase(inst);
  495. }
  496. auto callee_type_id = callee_inst.type_id();
  497. auto callee_fn_type =
  498. context.types().TryGetAs<SemIR::FunctionType>(callee_type_id);
  499. if (!callee_fn_type) {
  500. return ConstantEvalResult::NewSamePhase(inst);
  501. }
  502. // If the callee function found in the impl witness is not generic, the result
  503. // is simply that function.
  504. // TODO: We could do this even before the callee is concrete.
  505. auto generic_id =
  506. context.functions().Get(callee_fn_type->function_id).generic_id;
  507. if (!generic_id.has_value()) {
  508. return ConstantEvalResult::Existing(
  509. context.constant_values().Get(inst.callee_id));
  510. }
  511. // Find the arguments to use.
  512. auto enclosing_specific_id = callee_fn_type->specific_id;
  513. auto enclosing_args = context.inst_blocks().Get(
  514. context.specifics().GetArgsOrEmpty(enclosing_specific_id));
  515. auto interface_fn_args = context.inst_blocks().Get(
  516. context.specifics().GetArgsOrEmpty(inst.specific_id));
  517. // Form new specific for the generic callee function. The arguments for this
  518. // specific are the enclosing arguments of the callee followed by the
  519. // remaining arguments from the interface function. Impl checking has ensured
  520. // that these arguments can also be used for the function in the impl witness.
  521. auto num_params = context.inst_blocks()
  522. .Get(context.generics().Get(generic_id).bindings_id)
  523. .size();
  524. llvm::SmallVector<SemIR::InstId> args;
  525. args.reserve(num_params);
  526. args.append(enclosing_args.begin(), enclosing_args.end());
  527. int remaining_params = num_params - args.size();
  528. CARBON_CHECK(static_cast<int>(interface_fn_args.size()) >= remaining_params);
  529. args.append(interface_fn_args.end() - remaining_params,
  530. interface_fn_args.end());
  531. auto specific_id =
  532. MakeSpecific(context, SemIR::LocId(inst_id), generic_id, args);
  533. context.definitions_required_by_use().push_back(
  534. {SemIR::LocId(inst_id), specific_id});
  535. return ConstantEvalResult::NewSamePhase(
  536. SemIR::SpecificFunction{.type_id = inst.type_id,
  537. .callee_id = inst.callee_id,
  538. .specific_id = specific_id});
  539. }
  540. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  541. SemIR::SpecificFunction inst) -> ConstantEvalResult {
  542. auto callee_function =
  543. SemIR::GetCalleeAsFunction(context.sem_ir(), inst.callee_id);
  544. const auto& fn = context.functions().Get(callee_function.function_id);
  545. if (!callee_function.self_type_id.has_value() &&
  546. fn.builtin_function_kind() != SemIR::BuiltinFunctionKind::NoOp &&
  547. fn.virtual_modifier != SemIR::Function::VirtualModifier::Abstract) {
  548. // This is not an associated function. Those will be required to be defined
  549. // as part of checking that the impl is complete.
  550. context.definitions_required_by_use().push_back(
  551. {SemIR::LocId(inst_id), inst.specific_id});
  552. }
  553. // Create new constant for a specific function.
  554. return ConstantEvalResult::NewSamePhase(inst);
  555. }
  556. auto EvalConstantInst(Context& context, SemIR::SpliceBlock inst)
  557. -> ConstantEvalResult {
  558. // SpliceBlock evaluates to the result value that is (typically) within the
  559. // block. This can be constant even if the block contains other non-constant
  560. // instructions.
  561. return ConstantEvalResult::Existing(
  562. context.constant_values().Get(inst.result_id));
  563. }
  564. auto EvalConstantInst(Context& context, SemIR::SpliceInst inst)
  565. -> ConstantEvalResult {
  566. // The constant value of a SpliceInst is the constant value of the instruction
  567. // being spliced. Note that `inst.inst_id` is the instruction being spliced,
  568. // so we need to go through another round of obtaining the constant value in
  569. // addition to the one performed by the eval infrastructure.
  570. if (auto inst_value =
  571. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  572. return ConstantEvalResult::Existing(
  573. context.constant_values().Get(inst_value->inst_id));
  574. }
  575. // TODO: Consider creating a new `ValueOfInst` instruction analogous to
  576. // `TypeOfInst` to defer determining the constant value until we know the
  577. // instruction. Alternatively, produce a symbolic `SpliceInst` constant.
  578. return ConstantEvalResult::NotConstant;
  579. }
  580. auto EvalConstantInst(Context& context, SemIR::StructAccess inst)
  581. -> ConstantEvalResult {
  582. return PerformAggregateAccess(context, inst);
  583. }
  584. auto EvalConstantInst(Context& /*context*/, SemIR::StructInit inst)
  585. -> ConstantEvalResult {
  586. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  587. .type_id = inst.type_id, .elements_id = inst.elements_id});
  588. }
  589. auto EvalConstantInst(Context& /*context*/, SemIR::StructLiteral inst)
  590. -> ConstantEvalResult {
  591. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  592. .type_id = inst.type_id, .elements_id = inst.elements_id});
  593. }
  594. auto EvalConstantInst(Context& /*context*/, SemIR::Temporary /*inst*/)
  595. -> ConstantEvalResult {
  596. // TODO: Handle this. Can we just return the value of `init_id`?
  597. return ConstantEvalResult::TODO;
  598. }
  599. auto EvalConstantInst(Context& context, SemIR::TupleAccess inst)
  600. -> ConstantEvalResult {
  601. return PerformAggregateAccess(context, inst);
  602. }
  603. auto EvalConstantInst(Context& /*context*/, SemIR::TupleInit inst)
  604. -> ConstantEvalResult {
  605. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  606. .type_id = inst.type_id, .elements_id = inst.elements_id});
  607. }
  608. auto EvalConstantInst(Context& /*context*/, SemIR::TupleLiteral inst)
  609. -> ConstantEvalResult {
  610. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  611. .type_id = inst.type_id, .elements_id = inst.elements_id});
  612. }
  613. auto EvalConstantInst(Context& context, SemIR::TypeOfInst inst)
  614. -> ConstantEvalResult {
  615. // Grab the type from the instruction produced as our operand.
  616. if (auto inst_value =
  617. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  618. return ConstantEvalResult::Existing(context.types().GetConstantId(
  619. context.insts().Get(inst_value->inst_id).type_id()));
  620. }
  621. return ConstantEvalResult::NewSamePhase(inst);
  622. }
  623. auto EvalConstantInst(Context& context, SemIR::UnaryOperatorNot inst)
  624. -> ConstantEvalResult {
  625. // `not true` -> `false`, `not false` -> `true`.
  626. // All other uses of unary `not` are non-constant.
  627. auto const_id = context.constant_values().Get(inst.operand_id);
  628. if (const_id.is_concrete()) {
  629. auto value = context.insts().GetAs<SemIR::BoolLiteral>(
  630. context.constant_values().GetInstId(const_id));
  631. value.value = SemIR::BoolValue::From(!value.value.ToBool());
  632. return ConstantEvalResult::NewSamePhase(value);
  633. }
  634. return ConstantEvalResult::NotConstant;
  635. }
  636. auto EvalConstantInst(Context& context, SemIR::ValueOfInitializer inst)
  637. -> ConstantEvalResult {
  638. // Values of value expressions and initializing expressions are represented in
  639. // the same way during constant evaluation, so just return the value of the
  640. // operand.
  641. return ConstantEvalResult::Existing(
  642. context.constant_values().Get(inst.init_id));
  643. }
  644. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  645. SemIR::VarStorage inst) -> ConstantEvalResult {
  646. if (!inst.pattern_id.has_value()) {
  647. // This variable was not created from a `var` pattern, so isn't a global
  648. // variable.
  649. return ConstantEvalResult::NotConstant;
  650. }
  651. // A variable is constant if it's global.
  652. auto entity_name_id = SemIR::GetFirstBindingNameFromPatternId(
  653. context.sem_ir(), inst.pattern_id);
  654. if (!entity_name_id.has_value()) {
  655. // Variable doesn't introduce any bindings, so can only be referenced by its
  656. // own initializer. We treat such a reference as not being constant.
  657. return ConstantEvalResult::NotConstant;
  658. }
  659. auto scope_id = context.entity_names().Get(entity_name_id).parent_scope_id;
  660. if (!scope_id.has_value() ||
  661. !context.insts().Is<SemIR::Namespace>(
  662. context.name_scopes().Get(scope_id).inst_id())) {
  663. // Only namespace-scope variables are reference constants.
  664. return ConstantEvalResult::NotConstant;
  665. }
  666. // This is a constant reference expression denoting this global variable.
  667. return ConstantEvalResult::Existing(
  668. SemIR::ConstantId::ForConcreteConstant(inst_id));
  669. }
  670. } // namespace Carbon::Check