eval_inst.cpp 33 KB

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