eval_inst.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. // The `facet_value_inst_id` is always a facet value (has type facet type).
  195. CARBON_CHECK(context.types().Is<SemIR::FacetType>(
  196. context.insts().Get(inst.facet_value_inst_id).type_id()));
  197. // Other instructions (e.g. ImplWitnessAccess) of type FacetType can appear
  198. // here, in which case the constant inst is a FacetAccessType until those
  199. // instructions resolve to one of the above.
  200. return ConstantEvalResult::NewSamePhase(inst);
  201. }
  202. auto EvalConstantInst(Context& context, SemIR::FacetValue inst)
  203. -> ConstantEvalResult {
  204. // A FacetValue that just wraps a facet without adding/removing any witnesses
  205. // (which means they have the same type) is evaluated to the facet itself.
  206. if (auto access =
  207. context.insts().TryGetAs<SemIR::FacetAccessType>(inst.type_inst_id)) {
  208. if (context.insts().Get(access->facet_value_inst_id).type_id() ==
  209. inst.type_id) {
  210. return ConstantEvalResult::Existing(
  211. context.constant_values().Get(access->facet_value_inst_id));
  212. }
  213. }
  214. return ConstantEvalResult::NewSamePhase(inst);
  215. }
  216. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  217. SemIR::FloatType inst) -> ConstantEvalResult {
  218. return ValidateFloatTypeAndSetKind(context, SemIR::LocId(inst_id), inst)
  219. ? ConstantEvalResult::NewSamePhase(inst)
  220. : ConstantEvalResult::Error;
  221. }
  222. auto EvalConstantInst(Context& /*context*/, SemIR::FunctionDecl inst)
  223. -> ConstantEvalResult {
  224. // A function declaration evaluates to a function object, which is an empty
  225. // object of function type.
  226. // TODO: Eventually we may need to handle captures here.
  227. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  228. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  229. }
  230. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  231. SemIR::LookupImplWitness inst) -> ConstantEvalResult {
  232. // Canonicalize the query self to reduce the number of unique witness
  233. // instructions and enable constant value comparisons.
  234. auto self_facet_value_inst_id = SemIR::InstId::None;
  235. inst.query_self_inst_id = context.constant_values().GetInstId(
  236. GetCanonicalQuerySelfForLookupImplWitness(
  237. context, context.constant_values().Get(inst.query_self_inst_id),
  238. &self_facet_value_inst_id));
  239. auto witness_id = EvalLookupSingleFinalWitness(context, SemIR::LocId(inst_id),
  240. inst, self_facet_value_inst_id,
  241. EvalImplLookupMode::Normal);
  242. if (witness_id == SemIR::ErrorInst::ConstantId) {
  243. return ConstantEvalResult::Error;
  244. }
  245. if (witness_id.has_value()) {
  246. return ConstantEvalResult::Existing(witness_id);
  247. }
  248. // Try again when the query is modified by a specific.
  249. return ConstantEvalResult::NewSamePhase(inst);
  250. }
  251. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  252. SemIR::ImplWitnessAccess inst) -> ConstantEvalResult {
  253. CARBON_DIAGNOSTIC(ImplAccessMemberBeforeSet, Error,
  254. "accessing member from impl before it has a defined value");
  255. CARBON_KIND_SWITCH(context.insts().Get(inst.witness_id)) {
  256. case CARBON_KIND(SemIR::ImplWitness witness): {
  257. // This is PerformAggregateAccess followed by GetConstantValueInSpecific.
  258. auto witness_table = context.insts().GetAs<SemIR::ImplWitnessTable>(
  259. witness.witness_table_id);
  260. auto elements = context.inst_blocks().Get(witness_table.elements_id);
  261. // `elements` can be empty if there is only a forward declaration of the
  262. // impl.
  263. if (!elements.empty()) {
  264. auto index = static_cast<size_t>(inst.index.index);
  265. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  266. auto element = elements[index];
  267. if (element.has_value()) {
  268. LoadImportRef(context, element);
  269. return ConstantEvalResult::Existing(GetConstantValueInSpecific(
  270. context.sem_ir(), witness.specific_id, element));
  271. }
  272. }
  273. // If we get here, this impl witness table entry has not been populated
  274. // yet, because the impl was referenced within its own definition.
  275. // TODO: Add note pointing to the impl declaration.
  276. context.emitter().Emit(inst_id, ImplAccessMemberBeforeSet);
  277. return ConstantEvalResult::Error;
  278. }
  279. case CARBON_KIND(SemIR::CustomWitness custom_witness): {
  280. auto elements = context.inst_blocks().Get(custom_witness.elements_id);
  281. auto index = static_cast<size_t>(inst.index.index);
  282. // `elements` can be shorter than the number of associated entities while
  283. // we're building the synthetic witness.
  284. if (index < elements.size()) {
  285. return ConstantEvalResult::Existing(
  286. context.constant_values().Get(elements[index]));
  287. }
  288. // If we get here, this synthesized witness table entry has not been
  289. // populated yet.
  290. // TODO: Is this reachable? We have no test coverage for this diagnostic.
  291. context.emitter().Emit(inst_id, ImplAccessMemberBeforeSet);
  292. return ConstantEvalResult::Error;
  293. }
  294. case CARBON_KIND(SemIR::LookupImplWitness witness): {
  295. // If the witness is symbolic but has a self type that is a FacetType, it
  296. // can pull rewrite values from the self's facet type. If the access is
  297. // for one of those rewrites, evaluate to the RHS of the rewrite.
  298. // The type of the query self type (a FacetType or TypeType).
  299. auto access_self_type_id =
  300. context.insts().Get(witness.query_self_inst_id).type_id();
  301. if (context.types().Is<SemIR::TypeType>(access_self_type_id)) {
  302. // A self facet of type `type` has no rewrite constraints to look in.
  303. return ConstantEvalResult::NewSamePhase(inst);
  304. }
  305. // The `ImplWitnessAccess` is accessing a value, by index, for this
  306. // `self impls interface` combination.
  307. auto access_self =
  308. context.constant_values().Get(witness.query_self_inst_id);
  309. auto access_interface = context.specific_interfaces().Get(
  310. witness.query_specific_interface_id);
  311. auto access_self_facet_type_id =
  312. context.types()
  313. .GetAs<SemIR::FacetType>(access_self_type_id)
  314. .facet_type_id;
  315. // TODO: We could consider something better than linear search here, such
  316. // as a map. However that would probably require heap allocations which
  317. // may be worse overall since the number of rewrite constraints is
  318. // generally low. If the `rewrite_constraints` were sorted so that
  319. // associated constants are grouped together, as in
  320. // ResolveFacetTypeRewriteConstraints(), and limited to just the
  321. // `ImplWitnessAccess` entries, then a binary search may work here.
  322. for (const auto& rewrite : context.facet_types()
  323. .Get(access_self_facet_type_id)
  324. .rewrite_constraints) {
  325. // Look at each rewrite constraint in the self facet's type. If the LHS
  326. // is an `ImplWitnessAccess` into the same interface that `inst` is
  327. // indexing into, then we can use its RHS as the value.
  328. auto rewrite_lhs_access =
  329. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(rewrite.lhs_id);
  330. if (!rewrite_lhs_access) {
  331. continue;
  332. }
  333. if (rewrite_lhs_access->index != inst.index) {
  334. continue;
  335. }
  336. // Witnesses come from impl lookup, and the operands are from
  337. // IdentifiedFacetTypes, so `.Self` is replaced. However rewrite
  338. // constraints are not part of an IdentifiedFacetType, so they are not
  339. // replaced. We have to do the same replacement in the rewrite's LHS
  340. // witness in order to compare it with the access witness.
  341. //
  342. // However we don't substitute the witness directly as that would
  343. // re-evaluate it and cause us to do an impl lookup. Instead we
  344. // substitute and compare its operands.
  345. auto rewrite_lhs_witness =
  346. context.insts().GetAs<SemIR::LookupImplWitness>(
  347. rewrite_lhs_access->witness_id);
  348. SubstPeriodSelfCallbacks callbacks(&context, SemIR::LocId(inst_id),
  349. access_self);
  350. auto rewrite_lhs_self = context.constant_values().Get(
  351. rewrite_lhs_witness.query_self_inst_id);
  352. rewrite_lhs_self =
  353. SubstPeriodSelf(context, callbacks, rewrite_lhs_self);
  354. // Witnesses have a canonicalized self value. Perform the same
  355. // canonicalization here so that we can compare them.
  356. rewrite_lhs_self = GetCanonicalQuerySelfForLookupImplWitness(
  357. context, rewrite_lhs_self);
  358. if (rewrite_lhs_self != access_self) {
  359. // This rewrite is into a different self type than the access query.
  360. continue;
  361. }
  362. auto rewrite_lhs_interface = SubstPeriodSelf(
  363. context, callbacks,
  364. context.specific_interfaces().Get(
  365. rewrite_lhs_witness.query_specific_interface_id));
  366. if (rewrite_lhs_interface != access_interface) {
  367. // This rewrite is into a different interface than the access query.
  368. continue;
  369. }
  370. // The `ImplWitnessAccess` evaluates to the RHS from the witness self
  371. // facet value's type. Any `.Self` references in the RHS are also
  372. // replaced with the self type of the access.
  373. auto rewrite_rhs = SubstPeriodSelf(
  374. context, callbacks, context.constant_values().Get(rewrite.rhs_id));
  375. return ConstantEvalResult::Existing(rewrite_rhs);
  376. }
  377. break;
  378. }
  379. default:
  380. break;
  381. }
  382. return ConstantEvalResult::NewSamePhase(inst);
  383. }
  384. auto EvalConstantInst(Context& context,
  385. SemIR::ImplWitnessAccessSubstituted inst)
  386. -> ConstantEvalResult {
  387. return ConstantEvalResult::Existing(
  388. context.constant_values().Get(inst.value_id));
  389. }
  390. auto EvalConstantInst(Context& context,
  391. SemIR::ImplWitnessAssociatedConstant inst)
  392. -> ConstantEvalResult {
  393. return ConstantEvalResult::Existing(
  394. context.constant_values().Get(inst.inst_id));
  395. }
  396. auto EvalConstantInst(Context& /*context*/, SemIR::ImportRefUnloaded inst)
  397. -> ConstantEvalResult {
  398. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  399. inst);
  400. }
  401. auto EvalConstantInst(Context& context, SemIR::InPlaceInit inst)
  402. -> ConstantEvalResult {
  403. // Initialization is not performed in-place during constant evaluation, so
  404. // just return the value of the initializer.
  405. return ConstantEvalResult::Existing(
  406. context.constant_values().Get(inst.src_id));
  407. }
  408. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  409. SemIR::IntType inst) -> ConstantEvalResult {
  410. return ValidateIntType(context, SemIR::LocId(inst_id), inst)
  411. ? ConstantEvalResult::NewSamePhase(inst)
  412. : ConstantEvalResult::Error;
  413. }
  414. auto EvalConstantInst(Context& context, SemIR::InterfaceDecl inst)
  415. -> ConstantEvalResult {
  416. const auto& interface_info = context.interfaces().Get(inst.interface_id);
  417. // If the interface has generic parameters, we don't produce an interface
  418. // type, but a callable whose return value is an interface type.
  419. if (interface_info.has_parameters()) {
  420. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  421. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  422. }
  423. // A non-parameterized interface declaration evaluates to a declared facet
  424. // type containing just the interface.
  425. return ConstantEvalResult::NewAnyPhase(FacetTypeFromInterface(
  426. context, inst.interface_id,
  427. context.generics().GetSelfSpecific(interface_info.generic_id)));
  428. }
  429. auto EvalConstantInst(Context& context, SemIR::MarkInPlaceInit inst)
  430. -> ConstantEvalResult {
  431. return ConstantEvalResult::Existing(
  432. context.constant_values().Get(inst.src_id));
  433. }
  434. auto EvalConstantInst(Context& context, SemIR::NamedConstraintDecl inst)
  435. -> ConstantEvalResult {
  436. const auto& named_constraint_info =
  437. context.named_constraints().Get(inst.named_constraint_id);
  438. // If the named constraint has generic parameters, we don't produce a named
  439. // constraint type, but a callable whose return value is a named constraint
  440. // type.
  441. if (named_constraint_info.has_parameters()) {
  442. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  443. .type_id = inst.type_id, .elements_id = SemIR::InstBlockId::Empty});
  444. }
  445. // A non-parameterized named constraint declaration evaluates to a declared
  446. // facet type containing just the named constraint.
  447. return ConstantEvalResult::NewAnyPhase(FacetTypeFromNamedConstraint(
  448. context, inst.named_constraint_id,
  449. context.generics().GetSelfSpecific(named_constraint_info.generic_id)));
  450. }
  451. auto EvalConstantInst(Context& context, SemIR::NameRef inst)
  452. -> ConstantEvalResult {
  453. // A name reference evaluates to the value the name resolves to.
  454. return ConstantEvalResult::Existing(
  455. context.constant_values().Get(inst.value_id));
  456. }
  457. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  458. SemIR::RequireCompleteType inst) -> ConstantEvalResult {
  459. auto witness_type_id =
  460. GetSingletonType(context, SemIR::WitnessType::TypeInstId);
  461. // If the type is a concrete constant, require it to be complete now.
  462. auto complete_type_id =
  463. context.types().GetTypeIdForTypeInstId(inst.complete_type_inst_id);
  464. if (complete_type_id.is_concrete()) {
  465. Diagnostics::ContextScope diagnostic_context(
  466. &context.emitter(), [&](auto& builder) {
  467. CARBON_DIAGNOSTIC(IncompleteTypeInMonomorphization, Context,
  468. "{0} evaluates to incomplete type {1}",
  469. InstIdAsType, InstIdAsType);
  470. builder.Context(inst_id, IncompleteTypeInMonomorphization,
  471. context.insts()
  472. .GetAs<SemIR::RequireCompleteType>(inst_id)
  473. .complete_type_inst_id,
  474. inst.complete_type_inst_id);
  475. });
  476. // We use TryToCompleteType() instead of RequireCompleteType() because we
  477. // are currently evaluating a RequireCompleteType instruction, and calling
  478. // RequireCompleteType() would insert another copy of the same instruction.
  479. if (!TryToCompleteType(context, complete_type_id, SemIR::LocId(inst_id),
  480. true)) {
  481. return ConstantEvalResult::Error;
  482. }
  483. return ConstantEvalResult::NewAnyPhase(SemIR::CompleteTypeWitness{
  484. .type_id = witness_type_id,
  485. .object_repr_type_inst_id = context.types().GetTypeInstId(
  486. context.types().GetObjectRepr(complete_type_id))});
  487. }
  488. // If it's not a concrete constant, require it to be complete once it
  489. // becomes one.
  490. return ConstantEvalResult::NewSamePhase(inst);
  491. }
  492. auto EvalConstantInst(Context& context, SemIR::RequireSpecificDefinition inst)
  493. -> ConstantEvalResult {
  494. // This can return false, we just need to try it.
  495. ResolveSpecificDefinition(context, SemIR::LocId::None, inst.specific_id);
  496. return ConstantEvalResult::NewSamePhase(inst);
  497. }
  498. auto EvalConstantInst(Context& context, SemIR::SpecificConstant inst)
  499. -> ConstantEvalResult {
  500. // Pull the constant value out of the specific.
  501. return ConstantEvalResult::Existing(SemIR::GetConstantValueInSpecific(
  502. context.sem_ir(), inst.specific_id, inst.inst_id));
  503. }
  504. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  505. SemIR::SpecificImplFunction inst) -> ConstantEvalResult {
  506. auto callee_inst = context.insts().Get(inst.callee_id);
  507. // If the callee is not a function value, we're not ready to evaluate this
  508. // yet. Build a symbolic `SpecificImplFunction` constant.
  509. if (!callee_inst.Is<SemIR::StructValue>()) {
  510. return ConstantEvalResult::NewSamePhase(inst);
  511. }
  512. auto callee_type_id = callee_inst.type_id();
  513. auto callee_fn_type =
  514. context.types().TryGetAs<SemIR::FunctionType>(callee_type_id);
  515. if (!callee_fn_type) {
  516. return ConstantEvalResult::NewSamePhase(inst);
  517. }
  518. // If the callee function found in the impl witness is not generic, the result
  519. // is simply that function.
  520. // TODO: We could do this even before the callee is concrete.
  521. auto generic_id =
  522. context.functions().Get(callee_fn_type->function_id).generic_id;
  523. if (!generic_id.has_value()) {
  524. return ConstantEvalResult::Existing(
  525. context.constant_values().Get(inst.callee_id));
  526. }
  527. // Find the arguments to use.
  528. auto enclosing_specific_id = callee_fn_type->specific_id;
  529. auto enclosing_args = context.inst_blocks().Get(
  530. context.specifics().GetArgsOrEmpty(enclosing_specific_id));
  531. auto interface_fn_args = context.inst_blocks().Get(
  532. context.specifics().GetArgsOrEmpty(inst.specific_id));
  533. // Form new specific for the generic callee function. The arguments for this
  534. // specific are the enclosing arguments of the callee followed by the
  535. // remaining arguments from the interface function. Impl checking has ensured
  536. // that these arguments can also be used for the function in the impl witness.
  537. auto num_params = context.inst_blocks()
  538. .Get(context.generics().Get(generic_id).bindings_id)
  539. .size();
  540. llvm::SmallVector<SemIR::InstId> args;
  541. args.reserve(num_params);
  542. args.append(enclosing_args.begin(), enclosing_args.end());
  543. int remaining_params = num_params - args.size();
  544. CARBON_CHECK(static_cast<int>(interface_fn_args.size()) >= remaining_params);
  545. args.append(interface_fn_args.end() - remaining_params,
  546. interface_fn_args.end());
  547. auto specific_id =
  548. MakeSpecific(context, SemIR::LocId(inst_id), generic_id, args);
  549. context.definitions_required_by_use().push_back(
  550. {SemIR::LocId(inst_id), specific_id});
  551. return ConstantEvalResult::NewSamePhase(
  552. SemIR::SpecificFunction{.type_id = inst.type_id,
  553. .callee_id = inst.callee_id,
  554. .specific_id = specific_id});
  555. }
  556. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  557. SemIR::SpecificFunction inst) -> ConstantEvalResult {
  558. auto callee_function =
  559. SemIR::GetCalleeAsFunction(context.sem_ir(), inst.callee_id);
  560. const auto& fn = context.functions().Get(callee_function.function_id);
  561. if (!callee_function.self_type_id.has_value() &&
  562. fn.builtin_function_kind() != SemIR::BuiltinFunctionKind::NoOp &&
  563. fn.virtual_modifier != SemIR::Function::VirtualModifier::Abstract) {
  564. // This is not an associated function. Those will be required to be defined
  565. // as part of checking that the impl is complete.
  566. context.definitions_required_by_use().push_back(
  567. {SemIR::LocId(inst_id), inst.specific_id});
  568. }
  569. // Create new constant for a specific function.
  570. return ConstantEvalResult::NewSamePhase(inst);
  571. }
  572. auto EvalConstantInst(Context& context, SemIR::SpliceBlock inst)
  573. -> ConstantEvalResult {
  574. // SpliceBlock evaluates to the result value that is (typically) within the
  575. // block. This can be constant even if the block contains other non-constant
  576. // instructions.
  577. return ConstantEvalResult::Existing(
  578. context.constant_values().Get(inst.result_id));
  579. }
  580. auto EvalConstantInst(Context& context, SemIR::SpliceInst inst)
  581. -> ConstantEvalResult {
  582. // The constant value of a SpliceInst is the constant value of the instruction
  583. // being spliced. Note that `inst.inst_id` is the instruction being spliced,
  584. // so we need to go through another round of obtaining the constant value in
  585. // addition to the one performed by the eval infrastructure.
  586. auto nested_inst = context.insts().Get(inst.inst_id);
  587. if (auto inst_value = nested_inst.TryAs<SemIR::InstValue>()) {
  588. return ConstantEvalResult::Existing(
  589. context.constant_values().Get(inst_value->inst_id));
  590. }
  591. switch (nested_inst.kind().constant_kind()) {
  592. case SemIR::InstConstantKind::ConstantInstAction:
  593. return ConstantEvalResult::NewSamePhase(inst);
  594. case SemIR::InstConstantKind::InstAction:
  595. // TODO: Consider creating a new `ValueOfInst` instruction analogous to
  596. // `TypeOfInst` to defer determining the constant value until we know the
  597. // instruction. Alternatively, produce a symbolic `SpliceInst` constant.
  598. return ConstantEvalResult::NotConstant;
  599. default:
  600. CARBON_FATAL("Unexpected inst kind for inst splice: {0}", nested_inst);
  601. }
  602. }
  603. auto EvalConstantInst(Context& context, SemIR::StructAccess inst)
  604. -> ConstantEvalResult {
  605. return PerformAggregateAccess(context, inst);
  606. }
  607. auto EvalConstantInst(Context& /*context*/, SemIR::StructInit inst)
  608. -> ConstantEvalResult {
  609. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  610. .type_id = inst.type_id, .elements_id = inst.elements_id});
  611. }
  612. auto EvalConstantInst(Context& /*context*/, SemIR::StructLiteral inst)
  613. -> ConstantEvalResult {
  614. return ConstantEvalResult::NewSamePhase(SemIR::StructValue{
  615. .type_id = inst.type_id, .elements_id = inst.elements_id});
  616. }
  617. auto EvalConstantInst(Context& context, SemIR::TupleAccess inst)
  618. -> ConstantEvalResult {
  619. return PerformAggregateAccess(context, inst);
  620. }
  621. auto EvalConstantInst(Context& /*context*/, SemIR::TupleInit inst)
  622. -> ConstantEvalResult {
  623. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  624. .type_id = inst.type_id, .elements_id = inst.elements_id});
  625. }
  626. auto EvalConstantInst(Context& /*context*/, SemIR::TupleLiteral inst)
  627. -> ConstantEvalResult {
  628. return ConstantEvalResult::NewSamePhase(SemIR::TupleValue{
  629. .type_id = inst.type_id, .elements_id = inst.elements_id});
  630. }
  631. auto EvalConstantInst(Context& context, SemIR::TypeComponentOf inst)
  632. -> ConstantEvalResult {
  633. auto form_constant_inst_id =
  634. context.constant_values().GetConstantInstId(inst.form_inst_id);
  635. if (auto primitive_form = context.insts().TryGetAs<SemIR::AnyPrimitiveForm>(
  636. form_constant_inst_id)) {
  637. return ConstantEvalResult::Existing(
  638. context.constant_values().Get(primitive_form->type_component_id));
  639. }
  640. return ConstantEvalResult::NewSamePhase(inst);
  641. }
  642. auto EvalConstantInst(Context& context, SemIR::TypeLiteral inst)
  643. -> ConstantEvalResult {
  644. return ConstantEvalResult::Existing(
  645. context.constant_values().Get(inst.value_id));
  646. }
  647. auto EvalConstantInst(Context& context, SemIR::TypeOfInst inst)
  648. -> ConstantEvalResult {
  649. // Grab the type from the instruction produced as our operand.
  650. if (auto inst_value =
  651. context.insts().TryGetAs<SemIR::InstValue>(inst.inst_id)) {
  652. return ConstantEvalResult::Existing(context.types().GetConstantId(
  653. context.insts().Get(inst_value->inst_id).type_id()));
  654. }
  655. return ConstantEvalResult::NewSamePhase(inst);
  656. }
  657. auto EvalConstantInst(Context& context, SemIR::UnaryOperatorNot inst)
  658. -> ConstantEvalResult {
  659. // `not true` -> `false`, `not false` -> `true`.
  660. // All other uses of unary `not` are non-constant.
  661. auto const_id = context.constant_values().Get(inst.operand_id);
  662. if (const_id.is_concrete()) {
  663. auto value =
  664. context.constant_values().GetInstAs<SemIR::BoolLiteral>(const_id);
  665. value.value = SemIR::BoolValue::From(!value.value.ToBool());
  666. return ConstantEvalResult::NewSamePhase(value);
  667. }
  668. return ConstantEvalResult::NotConstant;
  669. }
  670. auto EvalConstantInst(Context& /*context*/, SemIR::UpdateInit /*inst*/)
  671. -> ConstantEvalResult {
  672. // TODO: Support folding together a ClassInit with an update that sets the
  673. // vptr.
  674. return ConstantEvalResult::TODO;
  675. }
  676. auto EvalConstantInst(Context& context, SemIR::ValueOfInitializer inst)
  677. -> ConstantEvalResult {
  678. // Values of value expressions and initializing expressions are represented in
  679. // the same way during constant evaluation, so just return the value of the
  680. // operand.
  681. return ConstantEvalResult::Existing(
  682. context.constant_values().Get(inst.init_id));
  683. }
  684. auto EvalConstantInst(Context& context, SemIR::InstId inst_id,
  685. SemIR::VarStorage inst) -> ConstantEvalResult {
  686. if (!inst.pattern_id.has_value()) {
  687. // This variable was not created from a `var` pattern, so isn't a global
  688. // variable.
  689. return ConstantEvalResult::NotConstant;
  690. }
  691. // A variable is constant if it's global.
  692. auto entity_name_id = SemIR::GetFirstBindingNameFromPatternId(
  693. context.sem_ir(), inst.pattern_id);
  694. if (!entity_name_id.has_value()) {
  695. // Variable doesn't introduce any bindings, so can only be referenced by its
  696. // own initializer. We treat such a reference as not being constant.
  697. return ConstantEvalResult::NotConstant;
  698. }
  699. auto scope_id = context.entity_names().Get(entity_name_id).parent_scope_id;
  700. if (!scope_id.has_value()) {
  701. return ConstantEvalResult::NotConstant;
  702. }
  703. auto scope_inst =
  704. context.insts().Get(context.name_scopes().Get(scope_id).inst_id());
  705. if (!scope_inst.Is<SemIR::Namespace>() &&
  706. !scope_inst.Is<SemIR::ClassDecl>()) {
  707. // Only namespace-scope and class-scope variables are reference constants.
  708. // Class-scope variables cannot currently be declared directly, but can
  709. // occur when static data members are imported from C++.
  710. return ConstantEvalResult::NotConstant;
  711. }
  712. // This is a constant reference expression denoting this global variable.
  713. return ConstantEvalResult::Existing(
  714. SemIR::ConstantId::ForConcreteConstant(inst_id));
  715. }
  716. } // namespace Carbon::Check