eval_inst.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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. SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
  117. if (const auto* var_decl = GetAsClangVarDecl(context, inst.value_id)) {
  118. const_id =
  119. EvalCppVarDecl(context, SemIR::LocId(inst_id), var_decl, inst.type_id);
  120. } else if (auto temporary =
  121. context.insts().TryGetAs<SemIR::Temporary>(inst.value_id)) {
  122. const_id = context.constant_values().Get(temporary->init_id);
  123. }
  124. if (const_id.has_value() && const_id.is_constant()) {
  125. return ConstantEvalResult::Existing(const_id);
  126. }
  127. return ConstantEvalResult::NotConstant;
  128. }
  129. auto EvalConstantInst(Context& context, SemIR::ClassElementAccess inst)
  130. -> ConstantEvalResult {
  131. return PerformAggregateAccess(context, inst);
  132. }
  133. auto EvalConstantInst(Context& context, SemIR::ClassDecl inst)
  134. -> ConstantEvalResult {
  135. const auto& class_info = context.classes().Get(inst.class_id);
  136. // If the class has generic parameters, we don't produce a class type, but a
  137. // callable whose return value is a class type.
  138. if (class_info.has_parameters()) {
  139. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  140. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  141. }
  142. // A non-generic class declaration evaluates to the class type.
  143. return ConstantEvalResult::NewAnyPhase(SemIR::ClassType{
  144. .type_id = SemIR::TypeType::TypeId,
  145. .class_id = inst.class_id,
  146. .specific_id =
  147. context.generics().GetSelfSpecific(class_info.generic_id)});
  148. }
  149. auto EvalConstantInst(Context& /*context*/, SemIR::ClassInit inst)
  150. -> ConstantEvalResult {
  151. // TODO: Add a `ClassValue` to represent a constant class object
  152. // representation instead of using a `StructValue`.
  153. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  154. .type_id = inst.type_id, .elements_id = inst.elements_id});
  155. }
  156. auto EvalConstantInst(Context& context, SemIR::ConstType inst)
  157. -> ConstantEvalResult {
  158. // `const (const T)` evaluates to `const T`.
  159. if (context.insts().Is<SemIR::ConstType>(inst.inner_id)) {
  160. return ConstantEvalResult::Existing(
  161. context.constant_values().Get(inst.inner_id));
  162. }
  163. // Otherwise, `const T` evaluates to itself.
  164. return ConstantEvalResult::NewSamePhase(inst);
  165. }
  166. auto EvalConstantInst(Context& /*context*/, SemIR::PartialType inst)
  167. -> ConstantEvalResult {
  168. return ConstantEvalResult::NewSamePhase(inst);
  169. }
  170. auto EvalConstantInst(Context& context, SemIR::Converted inst)
  171. -> ConstantEvalResult {
  172. // A conversion evaluates to the result of the conversion.
  173. return ConstantEvalResult::Existing(
  174. context.constant_values().Get(inst.result_id));
  175. }
  176. auto EvalConstantInst(Context& /*context*/, SemIR::Deref /*inst*/)
  177. -> ConstantEvalResult {
  178. // TODO: Handle this.
  179. return ConstantEvalResult::TODO;
  180. }
  181. auto EvalConstantInst(Context& context, SemIR::ExportDecl inst)
  182. -> ConstantEvalResult {
  183. // An export instruction evaluates to the exported declaration.
  184. return ConstantEvalResult::Existing(
  185. context.constant_values().Get(inst.value_id));
  186. }
  187. auto EvalConstantInst(Context& context, SemIR::FacetAccessType inst)
  188. -> ConstantEvalResult {
  189. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  190. inst.facet_value_inst_id)) {
  191. return ConstantEvalResult::Existing(
  192. context.constant_values().Get(facet_value->type_inst_id));
  193. }
  194. if (auto bind_name = context.insts().TryGetAs<SemIR::SymbolicBinding>(
  195. inst.facet_value_inst_id)) {
  196. return ConstantEvalResult::NewSamePhase(SemIR::SymbolicBindingType{
  197. .type_id = SemIR::TypeType::TypeId,
  198. .entity_name_id = bind_name->entity_name_id,
  199. // TODO: This is to be removed, at which point explore if we should
  200. // replace NewSamePhase with NewAnyPhase (to make the constant value
  201. // concrete). This is still a symbolic type though even if the inst
  202. // doesn't contain a symbolic constant. Previously we crashed in CHECKs
  203. // when we had a symbolic instruction with only an EntityNameId, due to
  204. // it not changing in a generic eval block. Maybe that has improved in
  205. // the latest version of this instruction. If it's not symbolic, then
  206. // SubstConstantCallbacks and other Subst callers may need to handle
  207. // looking through concrete instructions which would be unfortunate.
  208. .facet_value_inst_id = inst.facet_value_inst_id});
  209. }
  210. // The `facet_value_inst_id` is always a facet value (has type facet type).
  211. CARBON_CHECK(context.types().Is<SemIR::FacetType>(
  212. context.insts().Get(inst.facet_value_inst_id).type_id()));
  213. // Other instructions (e.g. ImplWitnessAccess) of type FacetType can appear
  214. // here, in which case the constant inst is a FacetAccessType until those
  215. // instructions resolve to one of the above.
  216. return ConstantEvalResult::NewSamePhase(inst);
  217. }
  218. auto EvalConstantInst(Context& context, SemIR::FacetValue inst)
  219. -> ConstantEvalResult {
  220. // A FacetValue that just wraps a SymbolicBinding without adding/removing any
  221. // witnesses is evaluated back to the SymbolicBinding itself.
  222. if (auto bind_as_type = context.insts().TryGetAs<SemIR::SymbolicBindingType>(
  223. inst.type_inst_id)) {
  224. // TODO: Look in ScopeStack with the entity_name_id to find the facet value.
  225. auto bind_id = bind_as_type->facet_value_inst_id;
  226. auto bind = context.insts().GetAs<SemIR::SymbolicBinding>(bind_id);
  227. // If the FacetTypes are the same, then the FacetValue didn't add/remove
  228. // any witnesses.
  229. if (bind.type_id == inst.type_id) {
  230. return ConstantEvalResult::Existing(
  231. context.constant_values().Get(bind_id));
  232. }
  233. }
  234. return ConstantEvalResult::NewSamePhase(inst);
  235. }
  236. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  237. SemIR::FloatType inst) -> ConstantEvalResult {
  238. return ValidateFloatTypeAndSetKind(context, SemIR::LocId(inst_id), inst)
  239. ? ConstantEvalResult::NewSamePhase(inst)
  240. : ConstantEvalResult::Error;
  241. }
  242. auto EvalConstantInst(Context& /*context*/, SemIR::FunctionDecl inst)
  243. -> ConstantEvalResult {
  244. // A function declaration evaluates to a function object, which is an empty
  245. // object of function type.
  246. // TODO: Eventually we may need to handle captures here.
  247. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  248. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  249. }
  250. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  251. SemIR::LookupImplWitness inst) -> ConstantEvalResult {
  252. // If the monomorphized query self is a FacetValue, we may get a witness from
  253. // it under limited circumstances. If no final witness is found though, we
  254. // don't need to preserve it for future evaluations, so we strip it from the
  255. // LookupImplWitness instruction to reduce the number of distinct constant
  256. // values.
  257. auto self_facet_value_inst_id = SemIR::InstId::None;
  258. if (auto facet_value = context.insts().TryGetAs<SemIR::FacetValue>(
  259. inst.query_self_inst_id)) {
  260. self_facet_value_inst_id =
  261. std::exchange(inst.query_self_inst_id, facet_value->type_inst_id);
  262. }
  263. // The self value is canonicalized in order to produce a canonical
  264. // LookupImplWitness instruction, avoiding multiple constant values for
  265. // `<facet value>` and `<facet value>` as type, which always have the same
  266. // lookup result.
  267. inst.query_self_inst_id =
  268. GetCanonicalFacetOrTypeValue(context, inst.query_self_inst_id);
  269. auto witness_id = EvalLookupSingleFinalWitness(context, SemIR::LocId(inst_id),
  270. inst, self_facet_value_inst_id,
  271. EvalImplLookupMode::Normal);
  272. if (witness_id == SemIR::ErrorInst::ConstantId) {
  273. return ConstantEvalResult::Error;
  274. }
  275. if (witness_id.has_value()) {
  276. return ConstantEvalResult::Existing(witness_id);
  277. }
  278. // Try again when the query is modified by a specific.
  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::MarkInPlaceInit inst)
  428. -> ConstantEvalResult {
  429. return ConstantEvalResult::Existing(
  430. context.constant_values().Get(inst.src_id));
  431. }
  432. auto EvalConstantInst(Context& context, SemIR::NamedConstraintDecl inst)
  433. -> ConstantEvalResult {
  434. const auto& named_constraint_info =
  435. context.named_constraints().Get(inst.named_constraint_id);
  436. // If the named constraint has generic parameters, we don't produce a named
  437. // constraint type, but a callable whose return value is a named constraint
  438. // type.
  439. if (named_constraint_info.has_parameters()) {
  440. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  441. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  442. }
  443. // A non-parameterized named constraint declaration evaluates to a declared
  444. // facet type containing just the named constraint.
  445. return ConstantEvalResult::NewAnyPhase(FacetTypeFromNamedConstraint(
  446. context, inst.named_constraint_id,
  447. context.generics().GetSelfSpecific(named_constraint_info.generic_id)));
  448. }
  449. auto EvalConstantInst(Context& context, SemIR::NameRef inst)
  450. -> ConstantEvalResult {
  451. // A name reference evaluates to the value the name resolves to.
  452. return ConstantEvalResult::Existing(
  453. context.constant_values().Get(inst.value_id));
  454. }
  455. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  456. SemIR::RequireCompleteType inst) -> ConstantEvalResult {
  457. auto witness_type_id =
  458. GetSingletonType(context, SemIR::WitnessType::TypeInstId);
  459. // If the type is a concrete constant, require it to be complete now.
  460. auto complete_type_id =
  461. context.types().GetTypeIdForTypeInstId(inst.complete_type_inst_id);
  462. if (complete_type_id.is_concrete()) {
  463. Diagnostics::ContextScope diagnostic_context(
  464. &context.emitter(), [&](auto& builder) {
  465. CARBON_DIAGNOSTIC(IncompleteTypeInMonomorphization, Context,
  466. "{0} evaluates to incomplete type {1}",
  467. InstIdAsType, InstIdAsType);
  468. builder.Context(inst_id, IncompleteTypeInMonomorphization,
  469. context.insts()
  470. .GetAs<SemIR::RequireCompleteType>(inst_id)
  471. .complete_type_inst_id,
  472. inst.complete_type_inst_id);
  473. });
  474. // We use TryToCompleteType() instead of RequireCompleteType() because we
  475. // are currently evaluating a RequireCompleteType instruction, and calling
  476. // RequireCompleteType() would insert another copy of the same instruction.
  477. if (!TryToCompleteType(context, complete_type_id, SemIR::LocId(inst_id),
  478. true)) {
  479. return ConstantEvalResult::Error;
  480. }
  481. return ConstantEvalResult::NewAnyPhase(SemIR::CompleteTypeWitness{
  482. .type_id = witness_type_id,
  483. .object_repr_type_inst_id = context.types().GetTypeInstId(
  484. context.types().GetObjectRepr(complete_type_id))});
  485. }
  486. // If it's not a concrete constant, require it to be complete once it
  487. // becomes one.
  488. return ConstantEvalResult::NewSamePhase(inst);
  489. }
  490. auto EvalConstantInst(Context& context, SemIR::RequireSpecificDefinition inst)
  491. -> ConstantEvalResult {
  492. // This can return false, we just need to try it.
  493. ResolveSpecificDefinition(context, SemIR::LocId::None, inst.specific_id);
  494. return ConstantEvalResult::NewSamePhase(inst);
  495. }
  496. auto EvalConstantInst(Context& context, SemIR::SpecificConstant inst)
  497. -> ConstantEvalResult {
  498. // Pull the constant value out of the specific.
  499. return ConstantEvalResult::Existing(SemIR::GetConstantValueInSpecific(
  500. context.sem_ir(), inst.specific_id, inst.inst_id));
  501. }
  502. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  503. SemIR::SpecificImplFunction inst) -> ConstantEvalResult {
  504. auto callee_inst = context.insts().Get(inst.callee_id);
  505. // If the callee is not a function value, we're not ready to evaluate this
  506. // yet. Build a symbolic `SpecificImplFunction` constant.
  507. if (!callee_inst.Is<SemIR::StructValue>()) {
  508. return ConstantEvalResult::NewSamePhase(inst);
  509. }
  510. auto callee_type_id = callee_inst.type_id();
  511. auto callee_fn_type =
  512. context.types().TryGetAs<SemIR::FunctionType>(callee_type_id);
  513. if (!callee_fn_type) {
  514. return ConstantEvalResult::NewSamePhase(inst);
  515. }
  516. // If the callee function found in the impl witness is not generic, the result
  517. // is simply that function.
  518. // TODO: We could do this even before the callee is concrete.
  519. auto generic_id =
  520. context.functions().Get(callee_fn_type->function_id).generic_id;
  521. if (!generic_id.has_value()) {
  522. return ConstantEvalResult::Existing(
  523. context.constant_values().Get(inst.callee_id));
  524. }
  525. // Find the arguments to use.
  526. auto enclosing_specific_id = callee_fn_type->specific_id;
  527. auto enclosing_args = context.inst_blocks().Get(
  528. context.specifics().GetArgsOrEmpty(enclosing_specific_id));
  529. auto interface_fn_args = context.inst_blocks().Get(
  530. context.specifics().GetArgsOrEmpty(inst.specific_id));
  531. // Form new specific for the generic callee function. The arguments for this
  532. // specific are the enclosing arguments of the callee followed by the
  533. // remaining arguments from the interface function. Impl checking has ensured
  534. // that these arguments can also be used for the function in the impl witness.
  535. auto num_params = context.inst_blocks()
  536. .Get(context.generics().Get(generic_id).bindings_id)
  537. .size();
  538. llvm::SmallVector<SemIR::InstId> args;
  539. args.reserve(num_params);
  540. args.append(enclosing_args.begin(), enclosing_args.end());
  541. int remaining_params = num_params - args.size();
  542. CARBON_CHECK(static_cast<int>(interface_fn_args.size()) >= remaining_params);
  543. args.append(interface_fn_args.end() - remaining_params,
  544. interface_fn_args.end());
  545. auto specific_id =
  546. MakeSpecific(context, SemIR::LocId(inst_id), generic_id, args);
  547. context.definitions_required_by_use().push_back(
  548. {SemIR::LocId(inst_id), specific_id});
  549. return ConstantEvalResult::NewSamePhase(
  550. SemIR::SpecificFunction{.type_id = inst.type_id,
  551. .callee_id = inst.callee_id,
  552. .specific_id = specific_id});
  553. }
  554. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  555. SemIR::SpecificFunction inst) -> ConstantEvalResult {
  556. auto callee_function =
  557. SemIR::GetCalleeAsFunction(context.sem_ir(), inst.callee_id);
  558. const auto& fn = context.functions().Get(callee_function.function_id);
  559. if (!callee_function.self_type_id.has_value() &&
  560. fn.builtin_function_kind() != SemIR::BuiltinFunctionKind::NoOp &&
  561. fn.virtual_modifier != SemIR::Function::VirtualModifier::Abstract) {
  562. // This is not an associated function. Those will be required to be defined
  563. // as part of checking that the impl is complete.
  564. context.definitions_required_by_use().push_back(
  565. {SemIR::LocId(inst_id), inst.specific_id});
  566. }
  567. // Create new constant for a specific function.
  568. return ConstantEvalResult::NewSamePhase(inst);
  569. }
  570. auto EvalConstantInst(Context& context, SemIR::SpliceBlock inst)
  571. -> ConstantEvalResult {
  572. // SpliceBlock evaluates to the result value that is (typically) within the
  573. // block. This can be constant even if the block contains other non-constant
  574. // instructions.
  575. return ConstantEvalResult::Existing(
  576. context.constant_values().Get(inst.result_id));
  577. }
  578. auto EvalConstantInst(Context& context, SemIR::SpliceInst inst)
  579. -> ConstantEvalResult {
  580. // The constant value of a SpliceInst is the constant value of the instruction
  581. // being spliced. Note that `inst.inst_id` is the instruction being spliced,
  582. // so we need to go through another round of obtaining the constant value in
  583. // addition to the one performed by the eval infrastructure.
  584. if (auto inst_value =
  585. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  586. return ConstantEvalResult::Existing(
  587. context.constant_values().Get(inst_value->inst_id));
  588. }
  589. // TODO: Consider creating a new `ValueOfInst` instruction analogous to
  590. // `TypeOfInst` to defer determining the constant value until we know the
  591. // instruction. Alternatively, produce a symbolic `SpliceInst` constant.
  592. return ConstantEvalResult::NotConstant;
  593. }
  594. auto EvalConstantInst(Context& context, SemIR::StructAccess inst)
  595. -> ConstantEvalResult {
  596. return PerformAggregateAccess(context, inst);
  597. }
  598. auto EvalConstantInst(Context& /*context*/, SemIR::StructInit inst)
  599. -> ConstantEvalResult {
  600. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  601. .type_id = inst.type_id, .elements_id = inst.elements_id});
  602. }
  603. auto EvalConstantInst(Context& /*context*/, SemIR::StructLiteral inst)
  604. -> ConstantEvalResult {
  605. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  606. .type_id = inst.type_id, .elements_id = inst.elements_id});
  607. }
  608. auto EvalConstantInst(Context& context, SemIR::TupleAccess inst)
  609. -> ConstantEvalResult {
  610. return PerformAggregateAccess(context, inst);
  611. }
  612. auto EvalConstantInst(Context& /*context*/, SemIR::TupleInit inst)
  613. -> ConstantEvalResult {
  614. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  615. .type_id = inst.type_id, .elements_id = inst.elements_id});
  616. }
  617. auto EvalConstantInst(Context& /*context*/, SemIR::TupleLiteral inst)
  618. -> ConstantEvalResult {
  619. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  620. .type_id = inst.type_id, .elements_id = inst.elements_id});
  621. }
  622. auto EvalConstantInst(Context& context, SemIR::TypeComponentOf inst)
  623. -> ConstantEvalResult {
  624. auto form_constant_inst_id =
  625. context.constant_values().GetConstantInstId(inst.form_inst_id);
  626. if (auto primitive_form = context.insts().TryGetAs<SemIR::AnyPrimitiveForm>(
  627. form_constant_inst_id)) {
  628. return ConstantEvalResult::Existing(
  629. context.constant_values().Get(primitive_form->type_component_id));
  630. }
  631. return ConstantEvalResult::NewSamePhase(inst);
  632. }
  633. auto EvalConstantInst(Context& context, SemIR::TypeLiteral inst)
  634. -> ConstantEvalResult {
  635. return ConstantEvalResult::Existing(
  636. context.constant_values().Get(inst.value_id));
  637. }
  638. auto EvalConstantInst(Context& context, SemIR::TypeOfInst inst)
  639. -> ConstantEvalResult {
  640. // Grab the type from the instruction produced as our operand.
  641. if (auto inst_value =
  642. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  643. return ConstantEvalResult::Existing(context.types().GetConstantId(
  644. context.insts().Get(inst_value->inst_id).type_id()));
  645. }
  646. return ConstantEvalResult::NewSamePhase(inst);
  647. }
  648. auto EvalConstantInst(Context& context, SemIR::UnaryOperatorNot inst)
  649. -> ConstantEvalResult {
  650. // `not true` -> `false`, `not false` -> `true`.
  651. // All other uses of unary `not` are non-constant.
  652. auto const_id = context.constant_values().Get(inst.operand_id);
  653. if (const_id.is_concrete()) {
  654. auto value =
  655. context.constant_values().GetInstAs<SemIR::BoolLiteral>(const_id);
  656. value.value = SemIR::BoolValue::From(!value.value.ToBool());
  657. return ConstantEvalResult::NewSamePhase(value);
  658. }
  659. return ConstantEvalResult::NotConstant;
  660. }
  661. auto EvalConstantInst(Context& /*context*/, SemIR::UpdateInit /*inst*/)
  662. -> ConstantEvalResult {
  663. // TODO: Support folding together a ClassInit with an update that sets the
  664. // vptr.
  665. return ConstantEvalResult::TODO;
  666. }
  667. auto EvalConstantInst(Context& context, SemIR::ValueOfInitializer inst)
  668. -> ConstantEvalResult {
  669. // Values of value expressions and initializing expressions are represented in
  670. // the same way during constant evaluation, so just return the value of the
  671. // operand.
  672. return ConstantEvalResult::Existing(
  673. context.constant_values().Get(inst.init_id));
  674. }
  675. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  676. SemIR::VarStorage inst) -> ConstantEvalResult {
  677. if (!inst.pattern_id.has_value()) {
  678. // This variable was not created from a `var` pattern, so isn't a global
  679. // variable.
  680. return ConstantEvalResult::NotConstant;
  681. }
  682. // A variable is constant if it's global.
  683. auto entity_name_id = SemIR::GetFirstBindingNameFromPatternId(
  684. context.sem_ir(), inst.pattern_id);
  685. if (!entity_name_id.has_value()) {
  686. // Variable doesn't introduce any bindings, so can only be referenced by its
  687. // own initializer. We treat such a reference as not being constant.
  688. return ConstantEvalResult::NotConstant;
  689. }
  690. auto scope_id = context.entity_names().Get(entity_name_id).parent_scope_id;
  691. if (!scope_id.has_value()) {
  692. return ConstantEvalResult::NotConstant;
  693. }
  694. auto scope_inst =
  695. context.insts().Get(context.name_scopes().Get(scope_id).inst_id());
  696. if (!scope_inst.Is<SemIR::Namespace>() &&
  697. !scope_inst.Is<SemIR::ClassDecl>()) {
  698. // Only namespace-scope and class-scope variables are reference constants.
  699. // Class-scope variables cannot currently be declared directly, but can
  700. // occur when static data members are imported from C++.
  701. return ConstantEvalResult::NotConstant;
  702. }
  703. // This is a constant reference expression denoting this global variable.
  704. return ConstantEvalResult::Existing(
  705. SemIR::ConstantId::ForConcreteConstant(inst_id));
  706. }
  707. } // namespace Carbon::Check