eval_inst.cpp 34 KB

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