eval.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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, SemIRLocation loc)
  265. -> void {
  266. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "Division by zero.");
  267. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  268. }
  269. // Performs a builtin unary integer -> integer operation.
  270. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLocation loc,
  271. SemIR::BuiltinFunctionKind builtin_kind,
  272. SemIR::InstId arg_id)
  273. -> SemIR::ConstantId {
  274. CARBON_CHECK(builtin_kind == SemIR::BuiltinFunctionKind::IntNegate)
  275. << "Unexpected builtin kind";
  276. auto op = context.insts().GetAs<SemIR::IntLiteral>(arg_id);
  277. auto op_val = context.ints().Get(op.int_id);
  278. if (context.types().IsSignedInt(op.type_id) && op_val.isMinSignedValue()) {
  279. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  280. "Integer overflow in negation of {0}.", TypedInt);
  281. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  282. TypedInt{op.type_id, op_val});
  283. }
  284. op_val.negate();
  285. auto result = context.ints().Add(op_val);
  286. return MakeConstantResult(context, SemIR::IntLiteral{op.type_id, result},
  287. Phase::Template);
  288. }
  289. // Performs a builtin binary integer -> integer operation.
  290. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLocation loc,
  291. SemIR::BuiltinFunctionKind builtin_kind,
  292. SemIR::InstId lhs_id,
  293. SemIR::InstId rhs_id)
  294. -> SemIR::ConstantId {
  295. auto lhs = context.insts().GetAs<SemIR::IntLiteral>(lhs_id);
  296. auto rhs = context.insts().GetAs<SemIR::IntLiteral>(rhs_id);
  297. auto lhs_val = context.ints().Get(lhs.int_id);
  298. auto rhs_val = context.ints().Get(rhs.int_id);
  299. bool is_signed = context.types().IsSignedInt(lhs.type_id);
  300. bool overflow = false;
  301. llvm::APInt result_val;
  302. llvm::StringLiteral op_str = "<error>";
  303. switch (builtin_kind) {
  304. case SemIR::BuiltinFunctionKind::IntAdd:
  305. result_val =
  306. is_signed ? lhs_val.sadd_ov(rhs_val, overflow) : lhs_val + rhs_val;
  307. op_str = "+";
  308. break;
  309. case SemIR::BuiltinFunctionKind::IntSub:
  310. result_val =
  311. is_signed ? lhs_val.ssub_ov(rhs_val, overflow) : lhs_val - rhs_val;
  312. op_str = "-";
  313. break;
  314. case SemIR::BuiltinFunctionKind::IntMul:
  315. result_val =
  316. is_signed ? lhs_val.smul_ov(rhs_val, overflow) : lhs_val * rhs_val;
  317. op_str = "*";
  318. break;
  319. case SemIR::BuiltinFunctionKind::IntDiv:
  320. if (rhs_val.isZero()) {
  321. DiagnoseDivisionByZero(context, loc);
  322. return SemIR::ConstantId::Error;
  323. }
  324. result_val = is_signed ? lhs_val.sdiv_ov(rhs_val, overflow)
  325. : lhs_val.udiv(rhs_val);
  326. op_str = "/";
  327. break;
  328. case SemIR::BuiltinFunctionKind::IntMod:
  329. if (rhs_val.isZero()) {
  330. DiagnoseDivisionByZero(context, loc);
  331. return SemIR::ConstantId::Error;
  332. }
  333. result_val = is_signed ? lhs_val.srem(rhs_val) : lhs_val.urem(rhs_val);
  334. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  335. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  336. overflow = is_signed && lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  337. op_str = "%";
  338. break;
  339. default:
  340. CARBON_FATAL() << "Unexpected operation kind.";
  341. }
  342. if (overflow) {
  343. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  344. "Integer overflow in calculation {0} {1} {2}.", TypedInt,
  345. llvm::StringLiteral, TypedInt);
  346. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  347. TypedInt{lhs.type_id, lhs_val}, op_str,
  348. TypedInt{rhs.type_id, rhs_val});
  349. }
  350. auto result = context.ints().Add(result_val);
  351. return MakeConstantResult(context, SemIR::IntLiteral{lhs.type_id, result},
  352. Phase::Template);
  353. }
  354. // Performs a builtin integer comparison.
  355. static auto PerformBuiltinIntComparison(Context& context,
  356. SemIR::BuiltinFunctionKind builtin_kind,
  357. SemIR::InstId lhs_id,
  358. SemIR::InstId rhs_id,
  359. SemIR::TypeId bool_type_id)
  360. -> SemIR::ConstantId {
  361. auto lhs_val = context.ints().Get(
  362. context.insts().GetAs<SemIR::IntLiteral>(lhs_id).int_id);
  363. auto rhs_val = context.ints().Get(
  364. context.insts().GetAs<SemIR::IntLiteral>(rhs_id).int_id);
  365. bool result;
  366. switch (builtin_kind) {
  367. case SemIR::BuiltinFunctionKind::IntEq:
  368. result = (lhs_val == rhs_val);
  369. break;
  370. case SemIR::BuiltinFunctionKind::IntNeq:
  371. result = (lhs_val != rhs_val);
  372. break;
  373. default:
  374. CARBON_FATAL() << "Unexpected operation kind.";
  375. }
  376. return MakeConstantResult(
  377. context, SemIR::BoolLiteral{bool_type_id, SemIR::BoolValue::From(result)},
  378. Phase::Template);
  379. }
  380. static auto PerformBuiltinCall(Context& context, SemIRLocation loc,
  381. SemIR::Call call,
  382. SemIR::BuiltinFunctionKind builtin_kind,
  383. llvm::ArrayRef<SemIR::InstId> arg_ids,
  384. Phase phase) -> SemIR::ConstantId {
  385. switch (builtin_kind) {
  386. case SemIR::BuiltinFunctionKind::None:
  387. CARBON_FATAL() << "Not a builtin function.";
  388. // Unary integer -> integer operations.
  389. case SemIR::BuiltinFunctionKind::IntNegate: {
  390. // TODO: Complement.
  391. if (phase != Phase::Template) {
  392. break;
  393. }
  394. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  395. }
  396. // Homogeneous binary integer -> integer operations.
  397. case SemIR::BuiltinFunctionKind::IntAdd:
  398. case SemIR::BuiltinFunctionKind::IntSub:
  399. case SemIR::BuiltinFunctionKind::IntMul:
  400. case SemIR::BuiltinFunctionKind::IntDiv:
  401. case SemIR::BuiltinFunctionKind::IntMod: {
  402. // TODO: Bitwise operators.
  403. if (phase != Phase::Template) {
  404. break;
  405. }
  406. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  407. arg_ids[1]);
  408. }
  409. // Integer comparisons.
  410. case SemIR::BuiltinFunctionKind::IntEq:
  411. case SemIR::BuiltinFunctionKind::IntNeq: {
  412. // TODO: Relational comparisons.
  413. if (phase != Phase::Template) {
  414. break;
  415. }
  416. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  417. arg_ids[1], call.type_id);
  418. }
  419. }
  420. return SemIR::ConstantId::NotConstant;
  421. }
  422. static auto PerformCall(Context& context, SemIRLocation loc, SemIR::Call call)
  423. -> SemIR::ConstantId {
  424. Phase phase = Phase::Template;
  425. // A call with an invalid argument list is used to represent an erroneous
  426. // call.
  427. //
  428. // TODO: Use a better representation for this.
  429. if (call.args_id == SemIR::InstBlockId::Invalid) {
  430. return SemIR::ConstantId::Error;
  431. }
  432. // If the callee isn't constant, this is not a constant call.
  433. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::callee_id,
  434. &phase)) {
  435. return SemIR::ConstantId::NotConstant;
  436. }
  437. // Handle calls to builtins.
  438. if (auto builtin_function_kind = SemIR::BuiltinFunctionKind::ForCallee(
  439. context.sem_ir(), call.callee_id);
  440. builtin_function_kind != SemIR::BuiltinFunctionKind::None) {
  441. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::args_id,
  442. &phase)) {
  443. return SemIR::ConstantId::NotConstant;
  444. }
  445. if (phase == Phase::UnknownDueToError) {
  446. return SemIR::ConstantId::Error;
  447. }
  448. return PerformBuiltinCall(context, loc, call, builtin_function_kind,
  449. context.inst_blocks().Get(call.args_id), phase);
  450. }
  451. return SemIR::ConstantId::NotConstant;
  452. }
  453. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  454. -> SemIR::ConstantId {
  455. // TODO: Ensure we have test coverage for each of these cases that can result
  456. // in a constant, once those situations are all reachable.
  457. switch (inst.kind()) {
  458. // These cases are constants if their operands are.
  459. case SemIR::AddrOf::Kind:
  460. return RebuildIfFieldsAreConstant(context, inst,
  461. &SemIR::AddrOf::lvalue_id);
  462. case SemIR::ArrayType::Kind:
  463. return RebuildAndValidateIfFieldsAreConstant(
  464. context, inst,
  465. [&](SemIR::ArrayType result) {
  466. auto bound_id = inst.As<SemIR::ArrayType>().bound_id;
  467. auto int_bound =
  468. context.insts().TryGetAs<SemIR::IntLiteral>(result.bound_id);
  469. if (!int_bound) {
  470. // TODO: Permit symbolic array bounds. This will require fixing
  471. // callers of `GetArrayBoundValue`.
  472. context.TODO(bound_id, "symbolic array bound");
  473. return false;
  474. }
  475. // TODO: We should check that the size of the resulting array type
  476. // fits in 64 bits, not just that the bound does. Should we use a
  477. // 32-bit limit for 32-bit targets?
  478. const auto& bound_val = context.ints().Get(int_bound->int_id);
  479. if (context.types().IsSignedInt(int_bound->type_id) &&
  480. bound_val.isNegative()) {
  481. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  482. "Array bound of {0} is negative.", TypedInt);
  483. context.emitter().Emit(bound_id, ArrayBoundNegative,
  484. TypedInt{int_bound->type_id, bound_val});
  485. return false;
  486. }
  487. if (bound_val.getActiveBits() > 64) {
  488. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  489. "Array bound of {0} is too large.", TypedInt);
  490. context.emitter().Emit(bound_id, ArrayBoundTooLarge,
  491. TypedInt{int_bound->type_id, bound_val});
  492. return false;
  493. }
  494. return true;
  495. },
  496. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  497. case SemIR::AssociatedEntityType::Kind:
  498. return RebuildIfFieldsAreConstant(
  499. context, inst, &SemIR::AssociatedEntityType::entity_type_id);
  500. case SemIR::BoundMethod::Kind:
  501. return RebuildIfFieldsAreConstant(context, inst,
  502. &SemIR::BoundMethod::object_id,
  503. &SemIR::BoundMethod::function_id);
  504. case SemIR::InterfaceWitness::Kind:
  505. return RebuildIfFieldsAreConstant(context, inst,
  506. &SemIR::InterfaceWitness::elements_id);
  507. case SemIR::PointerType::Kind:
  508. return RebuildIfFieldsAreConstant(context, inst,
  509. &SemIR::PointerType::pointee_id);
  510. case SemIR::StructType::Kind:
  511. return RebuildIfFieldsAreConstant(context, inst,
  512. &SemIR::StructType::fields_id);
  513. case SemIR::StructTypeField::Kind:
  514. return RebuildIfFieldsAreConstant(context, inst,
  515. &SemIR::StructTypeField::field_type_id);
  516. case SemIR::StructValue::Kind:
  517. return RebuildIfFieldsAreConstant(context, inst,
  518. &SemIR::StructValue::elements_id);
  519. case SemIR::TupleType::Kind:
  520. return RebuildIfFieldsAreConstant(context, inst,
  521. &SemIR::TupleType::elements_id);
  522. case SemIR::TupleValue::Kind:
  523. return RebuildIfFieldsAreConstant(context, inst,
  524. &SemIR::TupleValue::elements_id);
  525. case SemIR::UnboundElementType::Kind:
  526. return RebuildIfFieldsAreConstant(
  527. context, inst, &SemIR::UnboundElementType::class_type_id,
  528. &SemIR::UnboundElementType::element_type_id);
  529. // Initializers evaluate to a value of the object representation.
  530. case SemIR::ArrayInit::Kind:
  531. // TODO: Add an `ArrayValue` to represent a constant array object
  532. // representation instead of using a `TupleValue`.
  533. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  534. case SemIR::ClassInit::Kind:
  535. // TODO: Add a `ClassValue` to represent a constant class object
  536. // representation instead of using a `StructValue`.
  537. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  538. case SemIR::StructInit::Kind:
  539. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  540. case SemIR::TupleInit::Kind:
  541. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  542. case SemIR::AssociatedEntity::Kind:
  543. case SemIR::Builtin::Kind:
  544. // Builtins are always template constants.
  545. return MakeConstantResult(context, inst, Phase::Template);
  546. case SemIR::ClassDecl::Kind:
  547. // TODO: Once classes have generic arguments, handle them.
  548. return MakeConstantResult(
  549. context,
  550. SemIR::ClassType{SemIR::TypeId::TypeType,
  551. inst.As<SemIR::ClassDecl>().class_id},
  552. Phase::Template);
  553. case SemIR::InterfaceDecl::Kind:
  554. // TODO: Once interfaces have generic arguments, handle them.
  555. return MakeConstantResult(
  556. context,
  557. SemIR::InterfaceType{SemIR::TypeId::TypeType,
  558. inst.As<SemIR::InterfaceDecl>().interface_id},
  559. Phase::Template);
  560. case SemIR::ClassType::Kind:
  561. case SemIR::InterfaceType::Kind:
  562. CARBON_FATAL() << inst.kind()
  563. << " is only created during corresponding Decl handling.";
  564. // These cases are treated as being the unique canonical definition of the
  565. // corresponding constant value.
  566. // TODO: This doesn't properly handle redeclarations. Consider adding a
  567. // corresponding `Value` inst for each of these cases.
  568. case SemIR::AssociatedConstantDecl::Kind:
  569. case SemIR::BaseDecl::Kind:
  570. case SemIR::FieldDecl::Kind:
  571. case SemIR::FunctionDecl::Kind:
  572. case SemIR::Namespace::Kind:
  573. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  574. case SemIR::BoolLiteral::Kind:
  575. case SemIR::IntLiteral::Kind:
  576. case SemIR::RealLiteral::Kind:
  577. case SemIR::StringLiteral::Kind:
  578. // Promote literals to the constant block.
  579. // TODO: Convert literals into a canonical form. Currently we can form two
  580. // different `i32` constants with the same value if they are represented
  581. // by `APInt`s with different bit widths.
  582. return MakeConstantResult(context, inst, Phase::Template);
  583. // The elements of a constant aggregate can be accessed.
  584. case SemIR::ClassElementAccess::Kind:
  585. case SemIR::InterfaceWitnessAccess::Kind:
  586. case SemIR::StructAccess::Kind:
  587. case SemIR::TupleAccess::Kind:
  588. return PerformAggregateAccess(context, inst);
  589. case SemIR::ArrayIndex::Kind:
  590. case SemIR::TupleIndex::Kind:
  591. return PerformAggregateIndex(context, inst);
  592. case SemIR::Call::Kind:
  593. return PerformCall(context, inst_id, inst.As<SemIR::Call>());
  594. // TODO: These need special handling.
  595. case SemIR::BindValue::Kind:
  596. case SemIR::Deref::Kind:
  597. case SemIR::ImportRefUsed::Kind:
  598. case SemIR::Temporary::Kind:
  599. case SemIR::TemporaryStorage::Kind:
  600. case SemIR::ValueAsRef::Kind:
  601. break;
  602. case SemIR::BindSymbolicName::Kind:
  603. // TODO: Consider forming a constant value here using a de Bruijn index or
  604. // similar, so that corresponding symbolic parameters in redeclarations
  605. // are treated as the same value.
  606. return SemIR::ConstantId::ForSymbolicConstant(inst_id);
  607. // These semantic wrappers don't change the constant value.
  608. case SemIR::BindAlias::Kind:
  609. return context.constant_values().Get(
  610. inst.As<SemIR::BindAlias>().value_id);
  611. case SemIR::NameRef::Kind:
  612. return context.constant_values().Get(inst.As<SemIR::NameRef>().value_id);
  613. case SemIR::Converted::Kind:
  614. return context.constant_values().Get(
  615. inst.As<SemIR::Converted>().result_id);
  616. case SemIR::InitializeFrom::Kind:
  617. return context.constant_values().Get(
  618. inst.As<SemIR::InitializeFrom>().src_id);
  619. case SemIR::SpliceBlock::Kind:
  620. return context.constant_values().Get(
  621. inst.As<SemIR::SpliceBlock>().result_id);
  622. case SemIR::ValueOfInitializer::Kind:
  623. return context.constant_values().Get(
  624. inst.As<SemIR::ValueOfInitializer>().init_id);
  625. case SemIR::FacetTypeAccess::Kind:
  626. // TODO: Once we start tracking the witness in the facet value, remove it
  627. // here. For now, we model a facet value as just a type.
  628. return context.constant_values().Get(
  629. inst.As<SemIR::FacetTypeAccess>().facet_id);
  630. // `not true` -> `false`, `not false` -> `true`.
  631. // All other uses of unary `not` are non-constant.
  632. case SemIR::UnaryOperatorNot::Kind: {
  633. auto const_id = context.constant_values().Get(
  634. inst.As<SemIR::UnaryOperatorNot>().operand_id);
  635. auto phase = GetPhase(const_id);
  636. if (phase == Phase::Template) {
  637. auto value =
  638. context.insts().GetAs<SemIR::BoolLiteral>(const_id.inst_id());
  639. value.value = SemIR::BoolValue::From(!value.value.ToBool());
  640. return MakeConstantResult(context, value, Phase::Template);
  641. }
  642. if (phase == Phase::UnknownDueToError) {
  643. return SemIR::ConstantId::Error;
  644. }
  645. break;
  646. }
  647. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  648. // to itself.
  649. case SemIR::ConstType::Kind: {
  650. auto inner_id = context.constant_values().Get(
  651. context.types().GetInstId(inst.As<SemIR::ConstType>().inner_id));
  652. if (inner_id.is_constant() &&
  653. context.insts().Get(inner_id.inst_id()).Is<SemIR::ConstType>()) {
  654. return inner_id;
  655. }
  656. return MakeConstantResult(context, inst, GetPhase(inner_id));
  657. }
  658. // These cases are either not expressions or not constant.
  659. case SemIR::AddrPattern::Kind:
  660. case SemIR::Assign::Kind:
  661. case SemIR::BindName::Kind:
  662. case SemIR::BlockArg::Kind:
  663. case SemIR::Branch::Kind:
  664. case SemIR::BranchIf::Kind:
  665. case SemIR::BranchWithArg::Kind:
  666. case SemIR::ImplDecl::Kind:
  667. case SemIR::Param::Kind:
  668. case SemIR::ReturnExpr::Kind:
  669. case SemIR::Return::Kind:
  670. case SemIR::StructLiteral::Kind:
  671. case SemIR::TupleLiteral::Kind:
  672. case SemIR::VarStorage::Kind:
  673. break;
  674. case SemIR::ImportRefUnused::Kind:
  675. CARBON_FATAL() << "ImportRefUnused should transform to ImportRefUsed "
  676. "before TryEvalInst.";
  677. }
  678. return SemIR::ConstantId::NotConstant;
  679. }
  680. } // namespace Carbon::Check