eval.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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.h"
  5. #include "toolchain/check/diagnostic_helpers.h"
  6. #include "toolchain/diagnostics/diagnostic_emitter.h"
  7. #include "toolchain/sem_ir/builtin_function_kind.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. #include "toolchain/sem_ir/typed_insts.h"
  10. namespace Carbon::Check {
  11. namespace {
  12. // The evaluation phase for an expression, computed by evaluation. These are
  13. // ordered so that the phase of an expression is the numerically highest phase
  14. // of its constituent evaluations. Note that an expression with any runtime
  15. // component is known to have Runtime phase even if it involves an evaluation
  16. // with UnknownDueToError phase.
  17. enum class Phase : uint8_t {
  18. // Value could be entirely and concretely computed.
  19. Template,
  20. // Evaluation phase is symbolic because the expression involves a reference to
  21. // a symbolic binding.
  22. Symbolic,
  23. // The evaluation phase is unknown because evaluation encountered an
  24. // already-diagnosed semantic or syntax error. This is treated as being
  25. // potentially constant, but with an unknown phase.
  26. UnknownDueToError,
  27. // The expression has runtime phase because of a non-constant subexpression.
  28. Runtime,
  29. };
  30. } // namespace
  31. // Gets the phase in which the value of a constant will become available.
  32. static auto GetPhase(SemIR::ConstantId constant_id) -> Phase {
  33. if (!constant_id.is_constant()) {
  34. return Phase::Runtime;
  35. } else if (constant_id == SemIR::ConstantId::Error) {
  36. return Phase::UnknownDueToError;
  37. } else if (constant_id.is_template()) {
  38. return Phase::Template;
  39. } else {
  40. CARBON_CHECK(constant_id.is_symbolic());
  41. return Phase::Symbolic;
  42. }
  43. }
  44. // Returns the later of two phases.
  45. static auto LatestPhase(Phase a, Phase b) -> Phase {
  46. return static_cast<Phase>(
  47. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  48. }
  49. // Forms a `constant_id` describing a given evaluation result.
  50. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  51. -> SemIR::ConstantId {
  52. switch (phase) {
  53. case Phase::Template:
  54. return context.AddConstant(inst, /*is_symbolic=*/false);
  55. case Phase::Symbolic:
  56. return context.AddConstant(inst, /*is_symbolic=*/true);
  57. case Phase::UnknownDueToError:
  58. return SemIR::ConstantId::Error;
  59. case Phase::Runtime:
  60. return SemIR::ConstantId::NotConstant;
  61. }
  62. }
  63. // Forms a `constant_id` describing why an evaluation was not constant.
  64. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  65. return phase == Phase::UnknownDueToError ? SemIR::ConstantId::Error
  66. : SemIR::ConstantId::NotConstant;
  67. }
  68. // `GetConstantValue` checks to see whether the provided ID describes a value
  69. // with constant phase, and if so, returns the corresponding constant value.
  70. // Overloads are provided for different kinds of ID.
  71. // If the given instruction is constant, returns its constant value.
  72. static auto GetConstantValue(Context& context, SemIR::InstId inst_id,
  73. Phase* phase) -> SemIR::InstId {
  74. auto const_id = context.constant_values().Get(inst_id);
  75. *phase = LatestPhase(*phase, GetPhase(const_id));
  76. return const_id.inst_id();
  77. }
  78. // A type is always constant, but we still need to extract its phase.
  79. static auto GetConstantValue(Context& context, SemIR::TypeId type_id,
  80. Phase* phase) -> SemIR::TypeId {
  81. auto const_id = context.types().GetConstantId(type_id);
  82. *phase = LatestPhase(*phase, GetPhase(const_id));
  83. return type_id;
  84. }
  85. // If the given instruction block contains only constants, returns a
  86. // corresponding block of those values.
  87. static auto GetConstantValue(Context& context, SemIR::InstBlockId inst_block_id,
  88. Phase* phase) -> SemIR::InstBlockId {
  89. auto insts = context.inst_blocks().Get(inst_block_id);
  90. llvm::SmallVector<SemIR::InstId> const_insts;
  91. for (auto inst_id : insts) {
  92. auto const_inst_id = GetConstantValue(context, inst_id, phase);
  93. if (!const_inst_id.is_valid()) {
  94. return SemIR::InstBlockId::Invalid;
  95. }
  96. // Once we leave the small buffer, we know the first few elements are all
  97. // constant, so it's likely that the entire block is constant. Resize to the
  98. // target size given that we're going to allocate memory now anyway.
  99. if (const_insts.size() == const_insts.capacity()) {
  100. const_insts.reserve(insts.size());
  101. }
  102. const_insts.push_back(const_inst_id);
  103. }
  104. // TODO: If the new block is identical to the original block, return the
  105. // original ID.
  106. return context.inst_blocks().Add(const_insts);
  107. }
  108. // The constant value of a type block is that type block, but we still need to
  109. // extract its phase.
  110. static auto GetConstantValue(Context& context, SemIR::TypeBlockId type_block_id,
  111. Phase* phase) -> SemIR::TypeBlockId {
  112. auto types = context.type_blocks().Get(type_block_id);
  113. for (auto type_id : types) {
  114. GetConstantValue(context, type_id, phase);
  115. }
  116. return type_block_id;
  117. }
  118. // Replaces the specified field of the given typed instruction with its constant
  119. // value, if it has constant phase. Returns true on success, false if the value
  120. // has runtime phase.
  121. template <typename InstT, typename FieldIdT>
  122. static auto ReplaceFieldWithConstantValue(Context& context, InstT* inst,
  123. FieldIdT InstT::*field, Phase* phase)
  124. -> bool {
  125. auto unwrapped = GetConstantValue(context, inst->*field, phase);
  126. if (!unwrapped.is_valid()) {
  127. return false;
  128. }
  129. inst->*field = unwrapped;
  130. return true;
  131. }
  132. // If the specified fields of the given typed instruction have constant values,
  133. // replaces the fields with their constant values and builds a corresponding
  134. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  135. // `ConstantId::Error` if any subexpression is an error.
  136. //
  137. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  138. // which should return a `bool` indicating whether the new constant is valid. If
  139. // validation passes, a corresponding ConstantId for the new constant is
  140. // returned. If validation fails, it should produce a suitable error message.
  141. // `ConstantId::Error` is returned.
  142. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  143. static auto RebuildAndValidateIfFieldsAreConstant(
  144. Context& context, SemIR::Inst inst, ValidateFn validate_fn,
  145. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  146. // Build a constant instruction by replacing each non-constant operand with
  147. // its constant value.
  148. auto typed_inst = inst.As<InstT>();
  149. Phase phase = Phase::Template;
  150. if ((ReplaceFieldWithConstantValue(context, &typed_inst, each_field_id,
  151. &phase) &&
  152. ...)) {
  153. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  154. return SemIR::ConstantId::Error;
  155. }
  156. return MakeConstantResult(context, typed_inst, phase);
  157. }
  158. return MakeNonConstantResult(phase);
  159. }
  160. // Same as above but with no validation step.
  161. template <typename InstT, typename... EachFieldIdT>
  162. static auto RebuildIfFieldsAreConstant(Context& context, SemIR::Inst inst,
  163. EachFieldIdT InstT::*... each_field_id)
  164. -> SemIR::ConstantId {
  165. return RebuildAndValidateIfFieldsAreConstant(
  166. context, inst, [](...) { return true; }, each_field_id...);
  167. }
  168. // Rebuilds the given aggregate initialization instruction as a corresponding
  169. // constant aggregate value, if its elements are all constants.
  170. static auto RebuildInitAsValue(Context& context, SemIR::Inst inst,
  171. SemIR::InstKind value_kind)
  172. -> SemIR::ConstantId {
  173. auto init_inst = inst.As<SemIR::AnyAggregateInit>();
  174. Phase phase = Phase::Template;
  175. auto elements_id = GetConstantValue(context, init_inst.elements_id, &phase);
  176. return MakeConstantResult(
  177. context,
  178. SemIR::AnyAggregateValue{.kind = value_kind,
  179. .type_id = init_inst.type_id,
  180. .elements_id = elements_id},
  181. phase);
  182. }
  183. // Performs an access into an aggregate, retrieving the specified element.
  184. static auto PerformAggregateAccess(Context& context, SemIR::Inst inst)
  185. -> SemIR::ConstantId {
  186. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  187. Phase phase = Phase::Template;
  188. if (auto aggregate_id =
  189. GetConstantValue(context, access_inst.aggregate_id, &phase);
  190. aggregate_id.is_valid()) {
  191. if (auto aggregate =
  192. context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id)) {
  193. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  194. auto index = static_cast<size_t>(access_inst.index.index);
  195. CARBON_CHECK(index < elements.size()) << "Access out of bounds.";
  196. // `Phase` is not used here. If this element is a template constant, then
  197. // so is the result of indexing, even if the aggregate also contains a
  198. // symbolic context.
  199. return context.constant_values().Get(elements[index]);
  200. } else {
  201. CARBON_CHECK(phase != Phase::Template)
  202. << "Failed to evaluate template constant " << inst;
  203. }
  204. }
  205. return MakeNonConstantResult(phase);
  206. }
  207. // Performs an index into a homogeneous aggregate, retrieving the specified
  208. // element.
  209. static auto PerformAggregateIndex(Context& context, SemIR::Inst inst)
  210. -> SemIR::ConstantId {
  211. auto index_inst = inst.As<SemIR::AnyAggregateIndex>();
  212. Phase phase = Phase::Template;
  213. auto aggregate_id =
  214. GetConstantValue(context, index_inst.aggregate_id, &phase);
  215. auto index_id = GetConstantValue(context, index_inst.index_id, &phase);
  216. if (!index_id.is_valid()) {
  217. return MakeNonConstantResult(phase);
  218. }
  219. auto index = context.insts().TryGetAs<SemIR::IntLiteral>(index_id);
  220. if (!index) {
  221. CARBON_CHECK(phase != Phase::Template)
  222. << "Template constant integer should be a literal";
  223. return MakeNonConstantResult(phase);
  224. }
  225. // Array indexing is invalid if the index is constant and out of range.
  226. auto aggregate_type_id =
  227. context.insts().Get(index_inst.aggregate_id).type_id();
  228. const auto& index_val = context.ints().Get(index->int_id);
  229. if (auto array_type =
  230. context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  231. if (auto bound =
  232. context.insts().TryGetAs<SemIR::IntLiteral>(array_type->bound_id)) {
  233. // This awkward call to `getZExtValue` is a workaround for APInt not
  234. // supporting comparisons between integers of different bit widths.
  235. if (index_val.getActiveBits() > 64 ||
  236. context.ints().Get(bound->int_id).ule(index_val.getZExtValue())) {
  237. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  238. "Array index `{0}` is past the end of type `{1}`.",
  239. TypedInt, SemIR::TypeId);
  240. context.emitter().Emit(index_inst.index_id, ArrayIndexOutOfBounds,
  241. TypedInt{index->type_id, index_val},
  242. aggregate_type_id);
  243. return SemIR::ConstantId::Error;
  244. }
  245. }
  246. }
  247. if (!aggregate_id.is_valid()) {
  248. return MakeNonConstantResult(phase);
  249. }
  250. auto aggregate =
  251. context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  252. if (!aggregate) {
  253. CARBON_CHECK(phase != Phase::Template)
  254. << "Unexpected representation for template constant aggregate";
  255. return MakeNonConstantResult(phase);
  256. }
  257. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  258. // We checked this for the array case above.
  259. CARBON_CHECK(index_val.ult(elements.size()))
  260. << "Index out of bounds in tuple indexing";
  261. return context.constant_values().Get(elements[index_val.getZExtValue()]);
  262. }
  263. // Issues a diagnostic for a compile-time division by zero.
  264. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  265. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "Division by zero.");
  266. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  267. }
  268. // Performs a builtin unary integer -> integer operation.
  269. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  270. SemIR::BuiltinFunctionKind builtin_kind,
  271. SemIR::InstId arg_id)
  272. -> SemIR::ConstantId {
  273. CARBON_CHECK(builtin_kind == SemIR::BuiltinFunctionKind::IntNegate)
  274. << "Unexpected builtin kind";
  275. auto op = context.insts().GetAs<SemIR::IntLiteral>(arg_id);
  276. auto op_val = context.ints().Get(op.int_id);
  277. if (context.types().IsSignedInt(op.type_id) && op_val.isMinSignedValue()) {
  278. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  279. "Integer overflow in negation of {0}.", TypedInt);
  280. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  281. TypedInt{op.type_id, op_val});
  282. }
  283. op_val.negate();
  284. auto result = context.ints().Add(op_val);
  285. return MakeConstantResult(context, SemIR::IntLiteral{op.type_id, result},
  286. Phase::Template);
  287. }
  288. // Performs a builtin binary integer -> integer operation.
  289. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  290. SemIR::BuiltinFunctionKind builtin_kind,
  291. SemIR::InstId lhs_id,
  292. SemIR::InstId rhs_id)
  293. -> SemIR::ConstantId {
  294. auto lhs = context.insts().GetAs<SemIR::IntLiteral>(lhs_id);
  295. auto rhs = context.insts().GetAs<SemIR::IntLiteral>(rhs_id);
  296. auto lhs_val = context.ints().Get(lhs.int_id);
  297. auto rhs_val = context.ints().Get(rhs.int_id);
  298. bool is_signed = context.types().IsSignedInt(lhs.type_id);
  299. bool overflow = false;
  300. llvm::APInt result_val;
  301. llvm::StringLiteral op_str = "<error>";
  302. switch (builtin_kind) {
  303. case SemIR::BuiltinFunctionKind::IntAdd:
  304. result_val =
  305. is_signed ? lhs_val.sadd_ov(rhs_val, overflow) : lhs_val + rhs_val;
  306. op_str = "+";
  307. break;
  308. case SemIR::BuiltinFunctionKind::IntSub:
  309. result_val =
  310. is_signed ? lhs_val.ssub_ov(rhs_val, overflow) : lhs_val - rhs_val;
  311. op_str = "-";
  312. break;
  313. case SemIR::BuiltinFunctionKind::IntMul:
  314. result_val =
  315. is_signed ? lhs_val.smul_ov(rhs_val, overflow) : lhs_val * rhs_val;
  316. op_str = "*";
  317. break;
  318. case SemIR::BuiltinFunctionKind::IntDiv:
  319. if (rhs_val.isZero()) {
  320. DiagnoseDivisionByZero(context, loc);
  321. return SemIR::ConstantId::Error;
  322. }
  323. result_val = is_signed ? lhs_val.sdiv_ov(rhs_val, overflow)
  324. : lhs_val.udiv(rhs_val);
  325. op_str = "/";
  326. break;
  327. case SemIR::BuiltinFunctionKind::IntMod:
  328. if (rhs_val.isZero()) {
  329. DiagnoseDivisionByZero(context, loc);
  330. return SemIR::ConstantId::Error;
  331. }
  332. result_val = is_signed ? lhs_val.srem(rhs_val) : lhs_val.urem(rhs_val);
  333. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  334. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  335. overflow = is_signed && lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  336. op_str = "%";
  337. break;
  338. default:
  339. CARBON_FATAL() << "Unexpected operation kind.";
  340. }
  341. if (overflow) {
  342. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  343. "Integer overflow in calculation {0} {1} {2}.", TypedInt,
  344. llvm::StringLiteral, TypedInt);
  345. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  346. TypedInt{lhs.type_id, lhs_val}, op_str,
  347. TypedInt{rhs.type_id, rhs_val});
  348. }
  349. auto result = context.ints().Add(result_val);
  350. return MakeConstantResult(context, SemIR::IntLiteral{lhs.type_id, result},
  351. Phase::Template);
  352. }
  353. // Performs a builtin integer comparison.
  354. static auto PerformBuiltinIntComparison(Context& context,
  355. SemIR::BuiltinFunctionKind builtin_kind,
  356. SemIR::InstId lhs_id,
  357. SemIR::InstId rhs_id,
  358. SemIR::TypeId bool_type_id)
  359. -> SemIR::ConstantId {
  360. auto lhs_val = context.ints().Get(
  361. context.insts().GetAs<SemIR::IntLiteral>(lhs_id).int_id);
  362. auto rhs_val = context.ints().Get(
  363. context.insts().GetAs<SemIR::IntLiteral>(rhs_id).int_id);
  364. bool result;
  365. switch (builtin_kind) {
  366. case SemIR::BuiltinFunctionKind::IntEq:
  367. result = (lhs_val == rhs_val);
  368. break;
  369. case SemIR::BuiltinFunctionKind::IntNeq:
  370. result = (lhs_val != rhs_val);
  371. break;
  372. default:
  373. CARBON_FATAL() << "Unexpected operation kind.";
  374. }
  375. return MakeConstantResult(
  376. context, SemIR::BoolLiteral{bool_type_id, SemIR::BoolValue::From(result)},
  377. Phase::Template);
  378. }
  379. static auto PerformBuiltinCall(Context& context, SemIRLoc loc, SemIR::Call call,
  380. SemIR::BuiltinFunctionKind builtin_kind,
  381. llvm::ArrayRef<SemIR::InstId> arg_ids,
  382. Phase phase) -> SemIR::ConstantId {
  383. switch (builtin_kind) {
  384. case SemIR::BuiltinFunctionKind::None:
  385. CARBON_FATAL() << "Not a builtin function.";
  386. // Unary integer -> integer operations.
  387. case SemIR::BuiltinFunctionKind::IntNegate: {
  388. // TODO: Complement.
  389. if (phase != Phase::Template) {
  390. break;
  391. }
  392. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  393. }
  394. // Homogeneous binary integer -> integer operations.
  395. case SemIR::BuiltinFunctionKind::IntAdd:
  396. case SemIR::BuiltinFunctionKind::IntSub:
  397. case SemIR::BuiltinFunctionKind::IntMul:
  398. case SemIR::BuiltinFunctionKind::IntDiv:
  399. case SemIR::BuiltinFunctionKind::IntMod: {
  400. // TODO: Bitwise operators.
  401. if (phase != Phase::Template) {
  402. break;
  403. }
  404. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  405. arg_ids[1]);
  406. }
  407. // Integer comparisons.
  408. case SemIR::BuiltinFunctionKind::IntEq:
  409. case SemIR::BuiltinFunctionKind::IntNeq: {
  410. // TODO: Relational comparisons.
  411. if (phase != Phase::Template) {
  412. break;
  413. }
  414. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  415. arg_ids[1], call.type_id);
  416. }
  417. }
  418. return SemIR::ConstantId::NotConstant;
  419. }
  420. static auto PerformCall(Context& context, SemIRLoc loc, SemIR::Call call)
  421. -> SemIR::ConstantId {
  422. Phase phase = Phase::Template;
  423. // A call with an invalid argument list is used to represent an erroneous
  424. // call.
  425. //
  426. // TODO: Use a better representation for this.
  427. if (call.args_id == SemIR::InstBlockId::Invalid) {
  428. return SemIR::ConstantId::Error;
  429. }
  430. // If the callee isn't constant, this is not a constant call.
  431. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::callee_id,
  432. &phase)) {
  433. return SemIR::ConstantId::NotConstant;
  434. }
  435. // Handle calls to builtins.
  436. if (auto builtin_function_kind = SemIR::BuiltinFunctionKind::ForCallee(
  437. context.sem_ir(), call.callee_id);
  438. builtin_function_kind != SemIR::BuiltinFunctionKind::None) {
  439. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::args_id,
  440. &phase)) {
  441. return SemIR::ConstantId::NotConstant;
  442. }
  443. if (phase == Phase::UnknownDueToError) {
  444. return SemIR::ConstantId::Error;
  445. }
  446. return PerformBuiltinCall(context, loc, call, builtin_function_kind,
  447. context.inst_blocks().Get(call.args_id), phase);
  448. }
  449. return SemIR::ConstantId::NotConstant;
  450. }
  451. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  452. -> SemIR::ConstantId {
  453. // TODO: Ensure we have test coverage for each of these cases that can result
  454. // in a constant, once those situations are all reachable.
  455. switch (inst.kind()) {
  456. // These cases are constants if their operands are.
  457. case SemIR::AddrOf::Kind:
  458. return RebuildIfFieldsAreConstant(context, inst,
  459. &SemIR::AddrOf::lvalue_id);
  460. case SemIR::ArrayType::Kind:
  461. return RebuildAndValidateIfFieldsAreConstant(
  462. context, inst,
  463. [&](SemIR::ArrayType result) {
  464. auto bound_id = inst.As<SemIR::ArrayType>().bound_id;
  465. auto int_bound =
  466. context.insts().TryGetAs<SemIR::IntLiteral>(result.bound_id);
  467. if (!int_bound) {
  468. // TODO: Permit symbolic array bounds. This will require fixing
  469. // callers of `GetArrayBoundValue`.
  470. context.TODO(bound_id, "symbolic array bound");
  471. return false;
  472. }
  473. // TODO: We should check that the size of the resulting array type
  474. // fits in 64 bits, not just that the bound does. Should we use a
  475. // 32-bit limit for 32-bit targets?
  476. const auto& bound_val = context.ints().Get(int_bound->int_id);
  477. if (context.types().IsSignedInt(int_bound->type_id) &&
  478. bound_val.isNegative()) {
  479. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  480. "Array bound of {0} is negative.", TypedInt);
  481. context.emitter().Emit(bound_id, ArrayBoundNegative,
  482. TypedInt{int_bound->type_id, bound_val});
  483. return false;
  484. }
  485. if (bound_val.getActiveBits() > 64) {
  486. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  487. "Array bound of {0} is too large.", TypedInt);
  488. context.emitter().Emit(bound_id, ArrayBoundTooLarge,
  489. TypedInt{int_bound->type_id, bound_val});
  490. return false;
  491. }
  492. return true;
  493. },
  494. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  495. case SemIR::AssociatedEntityType::Kind:
  496. return RebuildIfFieldsAreConstant(
  497. context, inst, &SemIR::AssociatedEntityType::entity_type_id);
  498. case SemIR::BoundMethod::Kind:
  499. return RebuildIfFieldsAreConstant(context, inst,
  500. &SemIR::BoundMethod::object_id,
  501. &SemIR::BoundMethod::function_id);
  502. case SemIR::InterfaceWitness::Kind:
  503. return RebuildIfFieldsAreConstant(context, inst,
  504. &SemIR::InterfaceWitness::elements_id);
  505. case SemIR::PointerType::Kind:
  506. return RebuildIfFieldsAreConstant(context, inst,
  507. &SemIR::PointerType::pointee_id);
  508. case SemIR::StructType::Kind:
  509. return RebuildIfFieldsAreConstant(context, inst,
  510. &SemIR::StructType::fields_id);
  511. case SemIR::StructTypeField::Kind:
  512. return RebuildIfFieldsAreConstant(context, inst,
  513. &SemIR::StructTypeField::field_type_id);
  514. case SemIR::StructValue::Kind:
  515. return RebuildIfFieldsAreConstant(context, inst,
  516. &SemIR::StructValue::elements_id);
  517. case SemIR::TupleType::Kind:
  518. return RebuildIfFieldsAreConstant(context, inst,
  519. &SemIR::TupleType::elements_id);
  520. case SemIR::TupleValue::Kind:
  521. return RebuildIfFieldsAreConstant(context, inst,
  522. &SemIR::TupleValue::elements_id);
  523. case SemIR::UnboundElementType::Kind:
  524. return RebuildIfFieldsAreConstant(
  525. context, inst, &SemIR::UnboundElementType::class_type_id,
  526. &SemIR::UnboundElementType::element_type_id);
  527. // Initializers evaluate to a value of the object representation.
  528. case SemIR::ArrayInit::Kind:
  529. // TODO: Add an `ArrayValue` to represent a constant array object
  530. // representation instead of using a `TupleValue`.
  531. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  532. case SemIR::ClassInit::Kind:
  533. // TODO: Add a `ClassValue` to represent a constant class object
  534. // representation instead of using a `StructValue`.
  535. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  536. case SemIR::StructInit::Kind:
  537. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  538. case SemIR::TupleInit::Kind:
  539. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  540. case SemIR::AssociatedEntity::Kind:
  541. case SemIR::Builtin::Kind:
  542. // Builtins are always template constants.
  543. return MakeConstantResult(context, inst, Phase::Template);
  544. case SemIR::ClassDecl::Kind:
  545. // TODO: Once classes have generic arguments, handle them.
  546. return MakeConstantResult(
  547. context,
  548. SemIR::ClassType{SemIR::TypeId::TypeType,
  549. inst.As<SemIR::ClassDecl>().class_id},
  550. Phase::Template);
  551. case SemIR::InterfaceDecl::Kind:
  552. // TODO: Once interfaces have generic arguments, handle them.
  553. return MakeConstantResult(
  554. context,
  555. SemIR::InterfaceType{SemIR::TypeId::TypeType,
  556. inst.As<SemIR::InterfaceDecl>().interface_id},
  557. Phase::Template);
  558. case SemIR::ClassType::Kind:
  559. case SemIR::InterfaceType::Kind:
  560. CARBON_FATAL() << inst.kind()
  561. << " is only created during corresponding Decl handling.";
  562. // These cases are treated as being the unique canonical definition of the
  563. // corresponding constant value.
  564. // TODO: This doesn't properly handle redeclarations. Consider adding a
  565. // corresponding `Value` inst for each of these cases.
  566. case SemIR::AssociatedConstantDecl::Kind:
  567. case SemIR::BaseDecl::Kind:
  568. case SemIR::FieldDecl::Kind:
  569. case SemIR::FunctionDecl::Kind:
  570. case SemIR::Namespace::Kind:
  571. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  572. case SemIR::BoolLiteral::Kind:
  573. case SemIR::IntLiteral::Kind:
  574. case SemIR::RealLiteral::Kind:
  575. case SemIR::StringLiteral::Kind:
  576. // Promote literals to the constant block.
  577. // TODO: Convert literals into a canonical form. Currently we can form two
  578. // different `i32` constants with the same value if they are represented
  579. // by `APInt`s with different bit widths.
  580. return MakeConstantResult(context, inst, Phase::Template);
  581. // The elements of a constant aggregate can be accessed.
  582. case SemIR::ClassElementAccess::Kind:
  583. case SemIR::InterfaceWitnessAccess::Kind:
  584. case SemIR::StructAccess::Kind:
  585. case SemIR::TupleAccess::Kind:
  586. return PerformAggregateAccess(context, inst);
  587. case SemIR::ArrayIndex::Kind:
  588. case SemIR::TupleIndex::Kind:
  589. return PerformAggregateIndex(context, inst);
  590. case SemIR::Call::Kind:
  591. return PerformCall(context, inst_id, inst.As<SemIR::Call>());
  592. // TODO: These need special handling.
  593. case SemIR::BindValue::Kind:
  594. case SemIR::Deref::Kind:
  595. case SemIR::ImportRefUsed::Kind:
  596. case SemIR::Temporary::Kind:
  597. case SemIR::TemporaryStorage::Kind:
  598. case SemIR::ValueAsRef::Kind:
  599. break;
  600. case SemIR::BindSymbolicName::Kind:
  601. // TODO: Consider forming a constant value here using a de Bruijn index or
  602. // similar, so that corresponding symbolic parameters in redeclarations
  603. // are treated as the same value.
  604. return SemIR::ConstantId::ForSymbolicConstant(inst_id);
  605. // These semantic wrappers don't change the constant value.
  606. case SemIR::BindAlias::Kind:
  607. return context.constant_values().Get(
  608. inst.As<SemIR::BindAlias>().value_id);
  609. case SemIR::NameRef::Kind:
  610. return context.constant_values().Get(inst.As<SemIR::NameRef>().value_id);
  611. case SemIR::Converted::Kind:
  612. return context.constant_values().Get(
  613. inst.As<SemIR::Converted>().result_id);
  614. case SemIR::InitializeFrom::Kind:
  615. return context.constant_values().Get(
  616. inst.As<SemIR::InitializeFrom>().src_id);
  617. case SemIR::SpliceBlock::Kind:
  618. return context.constant_values().Get(
  619. inst.As<SemIR::SpliceBlock>().result_id);
  620. case SemIR::ValueOfInitializer::Kind:
  621. return context.constant_values().Get(
  622. inst.As<SemIR::ValueOfInitializer>().init_id);
  623. case SemIR::FacetTypeAccess::Kind:
  624. // TODO: Once we start tracking the witness in the facet value, remove it
  625. // here. For now, we model a facet value as just a type.
  626. return context.constant_values().Get(
  627. inst.As<SemIR::FacetTypeAccess>().facet_id);
  628. // `not true` -> `false`, `not false` -> `true`.
  629. // All other uses of unary `not` are non-constant.
  630. case SemIR::UnaryOperatorNot::Kind: {
  631. auto const_id = context.constant_values().Get(
  632. inst.As<SemIR::UnaryOperatorNot>().operand_id);
  633. auto phase = GetPhase(const_id);
  634. if (phase == Phase::Template) {
  635. auto value =
  636. context.insts().GetAs<SemIR::BoolLiteral>(const_id.inst_id());
  637. value.value = SemIR::BoolValue::From(!value.value.ToBool());
  638. return MakeConstantResult(context, value, Phase::Template);
  639. }
  640. if (phase == Phase::UnknownDueToError) {
  641. return SemIR::ConstantId::Error;
  642. }
  643. break;
  644. }
  645. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  646. // to itself.
  647. case SemIR::ConstType::Kind: {
  648. auto inner_id = context.constant_values().Get(
  649. context.types().GetInstId(inst.As<SemIR::ConstType>().inner_id));
  650. if (inner_id.is_constant() &&
  651. context.insts().Get(inner_id.inst_id()).Is<SemIR::ConstType>()) {
  652. return inner_id;
  653. }
  654. return MakeConstantResult(context, inst, GetPhase(inner_id));
  655. }
  656. // These cases are either not expressions or not constant.
  657. case SemIR::AddrPattern::Kind:
  658. case SemIR::Assign::Kind:
  659. case SemIR::BindName::Kind:
  660. case SemIR::BlockArg::Kind:
  661. case SemIR::Branch::Kind:
  662. case SemIR::BranchIf::Kind:
  663. case SemIR::BranchWithArg::Kind:
  664. case SemIR::ImplDecl::Kind:
  665. case SemIR::Param::Kind:
  666. case SemIR::ReturnExpr::Kind:
  667. case SemIR::Return::Kind:
  668. case SemIR::StructLiteral::Kind:
  669. case SemIR::TupleLiteral::Kind:
  670. case SemIR::VarStorage::Kind:
  671. break;
  672. case SemIR::ImportRefUnused::Kind:
  673. CARBON_FATAL() << "ImportRefUnused should transform to ImportRefUsed "
  674. "before TryEvalInst.";
  675. }
  676. return SemIR::ConstantId::NotConstant;
  677. }
  678. } // namespace Carbon::Check