eval_inst.cpp 32 KB

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