eval.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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/base/kind_switch.h"
  6. #include "toolchain/check/diagnostic_helpers.h"
  7. #include "toolchain/diagnostics/diagnostic_emitter.h"
  8. #include "toolchain/sem_ir/builtin_function_kind.h"
  9. #include "toolchain/sem_ir/function.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/typed_insts.h"
  12. namespace Carbon::Check {
  13. namespace {
  14. // The evaluation phase for an expression, computed by evaluation. These are
  15. // ordered so that the phase of an expression is the numerically highest phase
  16. // of its constituent evaluations. Note that an expression with any runtime
  17. // component is known to have Runtime phase even if it involves an evaluation
  18. // with UnknownDueToError phase.
  19. enum class Phase : uint8_t {
  20. // Value could be entirely and concretely computed.
  21. Template,
  22. // Evaluation phase is symbolic because the expression involves a reference to
  23. // a symbolic binding.
  24. Symbolic,
  25. // The evaluation phase is unknown because evaluation encountered an
  26. // already-diagnosed semantic or syntax error. This is treated as being
  27. // potentially constant, but with an unknown phase.
  28. UnknownDueToError,
  29. // The expression has runtime phase because of a non-constant subexpression.
  30. Runtime,
  31. };
  32. } // namespace
  33. // Gets the phase in which the value of a constant will become available.
  34. static auto GetPhase(SemIR::ConstantId constant_id) -> Phase {
  35. if (!constant_id.is_constant()) {
  36. return Phase::Runtime;
  37. } else if (constant_id == SemIR::ConstantId::Error) {
  38. return Phase::UnknownDueToError;
  39. } else if (constant_id.is_template()) {
  40. return Phase::Template;
  41. } else {
  42. CARBON_CHECK(constant_id.is_symbolic());
  43. return Phase::Symbolic;
  44. }
  45. }
  46. // Returns the later of two phases.
  47. static auto LatestPhase(Phase a, Phase b) -> Phase {
  48. return static_cast<Phase>(
  49. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  50. }
  51. // Forms a `constant_id` describing a given evaluation result.
  52. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  53. -> SemIR::ConstantId {
  54. switch (phase) {
  55. case Phase::Template:
  56. return context.AddConstant(inst, /*is_symbolic=*/false);
  57. case Phase::Symbolic:
  58. return context.AddConstant(inst, /*is_symbolic=*/true);
  59. case Phase::UnknownDueToError:
  60. return SemIR::ConstantId::Error;
  61. case Phase::Runtime:
  62. return SemIR::ConstantId::NotConstant;
  63. }
  64. }
  65. // Forms a `constant_id` describing why an evaluation was not constant.
  66. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  67. return phase == Phase::UnknownDueToError ? SemIR::ConstantId::Error
  68. : SemIR::ConstantId::NotConstant;
  69. }
  70. // Converts a bool value into a ConstantId.
  71. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  72. bool result) -> SemIR::ConstantId {
  73. return MakeConstantResult(
  74. context,
  75. SemIR::BoolLiteral{.type_id = bool_type_id,
  76. .value = SemIR::BoolValue::From(result)},
  77. Phase::Template);
  78. }
  79. // Converts an APInt value into a ConstantId.
  80. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  81. llvm::APInt value) -> SemIR::ConstantId {
  82. auto result = context.ints().Add(std::move(value));
  83. return MakeConstantResult(
  84. context, SemIR::IntLiteral{.type_id = type_id, .int_id = result},
  85. Phase::Template);
  86. }
  87. // Converts an APFloat value into a ConstantId.
  88. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  89. llvm::APFloat value) -> SemIR::ConstantId {
  90. auto result = context.floats().Add(std::move(value));
  91. return MakeConstantResult(
  92. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  93. Phase::Template);
  94. }
  95. // `GetConstantValue` checks to see whether the provided ID describes a value
  96. // with constant phase, and if so, returns the corresponding constant value.
  97. // Overloads are provided for different kinds of ID.
  98. // If the given instruction is constant, returns its constant value.
  99. static auto GetConstantValue(Context& context, SemIR::InstId inst_id,
  100. Phase* phase) -> SemIR::InstId {
  101. auto const_id = context.constant_values().Get(inst_id);
  102. *phase = LatestPhase(*phase, GetPhase(const_id));
  103. return const_id.inst_id();
  104. }
  105. // A type is always constant, but we still need to extract its phase.
  106. static auto GetConstantValue(Context& context, SemIR::TypeId type_id,
  107. Phase* phase) -> SemIR::TypeId {
  108. auto const_id = context.types().GetConstantId(type_id);
  109. *phase = LatestPhase(*phase, GetPhase(const_id));
  110. return type_id;
  111. }
  112. // If the given instruction block contains only constants, returns a
  113. // corresponding block of those values.
  114. static auto GetConstantValue(Context& context, SemIR::InstBlockId inst_block_id,
  115. Phase* phase) -> SemIR::InstBlockId {
  116. auto insts = context.inst_blocks().Get(inst_block_id);
  117. llvm::SmallVector<SemIR::InstId> const_insts;
  118. for (auto inst_id : insts) {
  119. auto const_inst_id = GetConstantValue(context, inst_id, phase);
  120. if (!const_inst_id.is_valid()) {
  121. return SemIR::InstBlockId::Invalid;
  122. }
  123. // Once we leave the small buffer, we know the first few elements are all
  124. // constant, so it's likely that the entire block is constant. Resize to the
  125. // target size given that we're going to allocate memory now anyway.
  126. if (const_insts.size() == const_insts.capacity()) {
  127. const_insts.reserve(insts.size());
  128. }
  129. const_insts.push_back(const_inst_id);
  130. }
  131. // TODO: If the new block is identical to the original block, and we know the
  132. // old ID was canonical, return the original ID.
  133. return context.inst_blocks().AddCanonical(const_insts);
  134. }
  135. // The constant value of a type block is that type block, but we still need to
  136. // extract its phase.
  137. static auto GetConstantValue(Context& context, SemIR::TypeBlockId type_block_id,
  138. Phase* phase) -> SemIR::TypeBlockId {
  139. auto types = context.type_blocks().Get(type_block_id);
  140. for (auto type_id : types) {
  141. GetConstantValue(context, type_id, phase);
  142. }
  143. return type_block_id;
  144. }
  145. // Replaces the specified field of the given typed instruction with its constant
  146. // value, if it has constant phase. Returns true on success, false if the value
  147. // has runtime phase.
  148. template <typename InstT, typename FieldIdT>
  149. static auto ReplaceFieldWithConstantValue(Context& context, InstT* inst,
  150. FieldIdT InstT::*field, Phase* phase)
  151. -> bool {
  152. auto unwrapped = GetConstantValue(context, inst->*field, phase);
  153. if (!unwrapped.is_valid()) {
  154. return false;
  155. }
  156. inst->*field = unwrapped;
  157. return true;
  158. }
  159. // If the specified fields of the given typed instruction have constant values,
  160. // replaces the fields with their constant values and builds a corresponding
  161. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  162. // `ConstantId::Error` if any subexpression is an error.
  163. //
  164. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  165. // which should return a `bool` indicating whether the new constant is valid. If
  166. // validation passes, a corresponding ConstantId for the new constant is
  167. // returned. If validation fails, it should produce a suitable error message.
  168. // `ConstantId::Error` is returned.
  169. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  170. static auto RebuildAndValidateIfFieldsAreConstant(
  171. Context& context, SemIR::Inst inst, ValidateFn validate_fn,
  172. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  173. // Build a constant instruction by replacing each non-constant operand with
  174. // its constant value.
  175. auto typed_inst = inst.As<InstT>();
  176. Phase phase = Phase::Template;
  177. if ((ReplaceFieldWithConstantValue(context, &typed_inst, each_field_id,
  178. &phase) &&
  179. ...)) {
  180. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  181. return SemIR::ConstantId::Error;
  182. }
  183. return MakeConstantResult(context, typed_inst, phase);
  184. }
  185. return MakeNonConstantResult(phase);
  186. }
  187. // Same as above but with no validation step.
  188. template <typename InstT, typename... EachFieldIdT>
  189. static auto RebuildIfFieldsAreConstant(Context& context, SemIR::Inst inst,
  190. EachFieldIdT InstT::*... each_field_id)
  191. -> SemIR::ConstantId {
  192. return RebuildAndValidateIfFieldsAreConstant(
  193. context, inst, [](...) { return true; }, each_field_id...);
  194. }
  195. // Rebuilds the given aggregate initialization instruction as a corresponding
  196. // constant aggregate value, if its elements are all constants.
  197. static auto RebuildInitAsValue(Context& context, SemIR::Inst inst,
  198. SemIR::InstKind value_kind)
  199. -> SemIR::ConstantId {
  200. auto init_inst = inst.As<SemIR::AnyAggregateInit>();
  201. Phase phase = Phase::Template;
  202. auto elements_id = GetConstantValue(context, init_inst.elements_id, &phase);
  203. return MakeConstantResult(
  204. context,
  205. SemIR::AnyAggregateValue{.kind = value_kind,
  206. .type_id = init_inst.type_id,
  207. .elements_id = elements_id},
  208. phase);
  209. }
  210. // Performs an access into an aggregate, retrieving the specified element.
  211. static auto PerformAggregateAccess(Context& context, SemIR::Inst inst)
  212. -> SemIR::ConstantId {
  213. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  214. Phase phase = Phase::Template;
  215. if (auto aggregate_id =
  216. GetConstantValue(context, access_inst.aggregate_id, &phase);
  217. aggregate_id.is_valid()) {
  218. if (auto aggregate =
  219. context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id)) {
  220. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  221. auto index = static_cast<size_t>(access_inst.index.index);
  222. CARBON_CHECK(index < elements.size()) << "Access out of bounds.";
  223. // `Phase` is not used here. If this element is a template constant, then
  224. // so is the result of indexing, even if the aggregate also contains a
  225. // symbolic context.
  226. return context.constant_values().Get(elements[index]);
  227. } else {
  228. CARBON_CHECK(phase != Phase::Template)
  229. << "Failed to evaluate template constant " << inst;
  230. }
  231. }
  232. return MakeNonConstantResult(phase);
  233. }
  234. // Performs an index into a homogeneous aggregate, retrieving the specified
  235. // element.
  236. static auto PerformAggregateIndex(Context& context, SemIR::Inst inst)
  237. -> SemIR::ConstantId {
  238. auto index_inst = inst.As<SemIR::AnyAggregateIndex>();
  239. Phase phase = Phase::Template;
  240. auto aggregate_id =
  241. GetConstantValue(context, index_inst.aggregate_id, &phase);
  242. auto index_id = GetConstantValue(context, index_inst.index_id, &phase);
  243. if (!index_id.is_valid()) {
  244. return MakeNonConstantResult(phase);
  245. }
  246. auto index = context.insts().TryGetAs<SemIR::IntLiteral>(index_id);
  247. if (!index) {
  248. CARBON_CHECK(phase != Phase::Template)
  249. << "Template constant integer should be a literal";
  250. return MakeNonConstantResult(phase);
  251. }
  252. // Array indexing is invalid if the index is constant and out of range.
  253. auto aggregate_type_id =
  254. context.insts().Get(index_inst.aggregate_id).type_id();
  255. const auto& index_val = context.ints().Get(index->int_id);
  256. if (auto array_type =
  257. context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  258. if (auto bound =
  259. context.insts().TryGetAs<SemIR::IntLiteral>(array_type->bound_id)) {
  260. // This awkward call to `getZExtValue` is a workaround for APInt not
  261. // supporting comparisons between integers of different bit widths.
  262. if (index_val.getActiveBits() > 64 ||
  263. context.ints().Get(bound->int_id).ule(index_val.getZExtValue())) {
  264. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  265. "Array index `{0}` is past the end of type `{1}`.",
  266. TypedInt, SemIR::TypeId);
  267. context.emitter().Emit(index_inst.index_id, ArrayIndexOutOfBounds,
  268. {.type = index->type_id, .value = index_val},
  269. aggregate_type_id);
  270. return SemIR::ConstantId::Error;
  271. }
  272. }
  273. }
  274. if (!aggregate_id.is_valid()) {
  275. return MakeNonConstantResult(phase);
  276. }
  277. auto aggregate =
  278. context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  279. if (!aggregate) {
  280. CARBON_CHECK(phase != Phase::Template)
  281. << "Unexpected representation for template constant aggregate";
  282. return MakeNonConstantResult(phase);
  283. }
  284. auto elements = context.inst_blocks().Get(aggregate->elements_id);
  285. // We checked this for the array case above.
  286. CARBON_CHECK(index_val.ult(elements.size()))
  287. << "Index out of bounds in tuple indexing";
  288. return context.constant_values().Get(elements[index_val.getZExtValue()]);
  289. }
  290. // Enforces that an integer type has a valid bit width.
  291. auto ValidateIntType(Context& context, SemIRLoc loc, SemIR::IntType result)
  292. -> bool {
  293. auto bit_width =
  294. context.insts().TryGetAs<SemIR::IntLiteral>(result.bit_width_id);
  295. if (!bit_width) {
  296. // Symbolic bit width.
  297. return true;
  298. }
  299. const auto& bit_width_val = context.ints().Get(bit_width->int_id);
  300. if (bit_width_val.isZero() ||
  301. (context.types().IsSignedInt(bit_width->type_id) &&
  302. bit_width_val.isNegative())) {
  303. CARBON_DIAGNOSTIC(IntWidthNotPositive, Error,
  304. "Integer type width of {0} is not positive.", TypedInt);
  305. context.emitter().Emit(
  306. loc, IntWidthNotPositive,
  307. {.type = bit_width->type_id, .value = bit_width_val});
  308. return false;
  309. }
  310. // TODO: Pick a maximum size and document it in the design. For now
  311. // we use 2^^23, because that's the largest size that LLVM supports.
  312. constexpr int MaxIntWidth = 1 << 23;
  313. if (bit_width_val.ugt(MaxIntWidth)) {
  314. CARBON_DIAGNOSTIC(IntWidthTooLarge, Error,
  315. "Integer type width of {0} is greater than the "
  316. "maximum supported width of {1}.",
  317. TypedInt, int);
  318. context.emitter().Emit(loc, IntWidthTooLarge,
  319. {.type = bit_width->type_id, .value = bit_width_val},
  320. MaxIntWidth);
  321. return false;
  322. }
  323. return true;
  324. }
  325. // Forms a constant int type as an evaluation result. Requires that width_id is
  326. // constant.
  327. auto MakeIntTypeResult(Context& context, SemIRLoc loc, SemIR::IntKind int_kind,
  328. SemIR::InstId width_id, Phase phase)
  329. -> SemIR::ConstantId {
  330. auto result = SemIR::IntType{
  331. .type_id = context.GetBuiltinType(SemIR::BuiltinKind::TypeType),
  332. .int_kind = int_kind,
  333. .bit_width_id = width_id};
  334. if (!ValidateIntType(context, loc, result)) {
  335. return SemIR::ConstantId::Error;
  336. }
  337. return MakeConstantResult(context, result, phase);
  338. }
  339. // Enforces that the bit width is 64 for a float.
  340. static auto ValidateFloatBitWidth(Context& context, SemIRLoc loc,
  341. SemIR::InstId inst_id) -> bool {
  342. auto inst = context.insts().GetAs<SemIR::IntLiteral>(inst_id);
  343. if (context.ints().Get(inst.int_id) == 64) {
  344. return true;
  345. }
  346. CARBON_DIAGNOSTIC(CompileTimeFloatBitWidth, Error, "Bit width must be 64.");
  347. context.emitter().Emit(loc, CompileTimeFloatBitWidth);
  348. return false;
  349. }
  350. // Enforces that a float type has a valid bit width.
  351. auto ValidateFloatType(Context& context, SemIRLoc loc, SemIR::FloatType result)
  352. -> bool {
  353. auto bit_width =
  354. context.insts().TryGetAs<SemIR::IntLiteral>(result.bit_width_id);
  355. if (!bit_width) {
  356. // Symbolic bit width.
  357. return true;
  358. }
  359. return ValidateFloatBitWidth(context, loc, result.bit_width_id);
  360. }
  361. // Issues a diagnostic for a compile-time division by zero.
  362. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  363. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "Division by zero.");
  364. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  365. }
  366. // Performs a builtin unary integer -> integer operation.
  367. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  368. SemIR::BuiltinFunctionKind builtin_kind,
  369. SemIR::InstId arg_id)
  370. -> SemIR::ConstantId {
  371. auto op = context.insts().GetAs<SemIR::IntLiteral>(arg_id);
  372. auto op_val = context.ints().Get(op.int_id);
  373. switch (builtin_kind) {
  374. case SemIR::BuiltinFunctionKind::IntSNegate:
  375. if (context.types().IsSignedInt(op.type_id) &&
  376. op_val.isMinSignedValue()) {
  377. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  378. "Integer overflow in negation of {0}.", TypedInt);
  379. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  380. {.type = op.type_id, .value = op_val});
  381. }
  382. op_val.negate();
  383. break;
  384. case SemIR::BuiltinFunctionKind::IntUNegate:
  385. op_val.negate();
  386. break;
  387. case SemIR::BuiltinFunctionKind::IntComplement:
  388. op_val.flipAllBits();
  389. break;
  390. default:
  391. CARBON_FATAL() << "Unexpected builtin kind";
  392. }
  393. return MakeIntResult(context, op.type_id, std::move(op_val));
  394. }
  395. // Performs a builtin binary integer -> integer operation.
  396. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  397. SemIR::BuiltinFunctionKind builtin_kind,
  398. SemIR::InstId lhs_id,
  399. SemIR::InstId rhs_id)
  400. -> SemIR::ConstantId {
  401. auto lhs = context.insts().GetAs<SemIR::IntLiteral>(lhs_id);
  402. auto rhs = context.insts().GetAs<SemIR::IntLiteral>(rhs_id);
  403. const auto& lhs_val = context.ints().Get(lhs.int_id);
  404. const auto& rhs_val = context.ints().Get(rhs.int_id);
  405. // Check for division by zero.
  406. switch (builtin_kind) {
  407. case SemIR::BuiltinFunctionKind::IntSDiv:
  408. case SemIR::BuiltinFunctionKind::IntSMod:
  409. case SemIR::BuiltinFunctionKind::IntUDiv:
  410. case SemIR::BuiltinFunctionKind::IntUMod:
  411. if (rhs_val.isZero()) {
  412. DiagnoseDivisionByZero(context, loc);
  413. return SemIR::ConstantId::Error;
  414. }
  415. break;
  416. default:
  417. break;
  418. }
  419. bool overflow = false;
  420. llvm::APInt result_val;
  421. llvm::StringLiteral op_str = "<error>";
  422. switch (builtin_kind) {
  423. // Arithmetic.
  424. case SemIR::BuiltinFunctionKind::IntSAdd:
  425. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  426. op_str = "+";
  427. break;
  428. case SemIR::BuiltinFunctionKind::IntSSub:
  429. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  430. op_str = "-";
  431. break;
  432. case SemIR::BuiltinFunctionKind::IntSMul:
  433. result_val = lhs_val.smul_ov(rhs_val, overflow);
  434. op_str = "*";
  435. break;
  436. case SemIR::BuiltinFunctionKind::IntSDiv:
  437. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  438. op_str = "/";
  439. break;
  440. case SemIR::BuiltinFunctionKind::IntSMod:
  441. result_val = lhs_val.srem(rhs_val);
  442. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  443. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  444. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  445. op_str = "%";
  446. break;
  447. case SemIR::BuiltinFunctionKind::IntUAdd:
  448. result_val = lhs_val + rhs_val;
  449. op_str = "+";
  450. break;
  451. case SemIR::BuiltinFunctionKind::IntUSub:
  452. result_val = lhs_val - rhs_val;
  453. op_str = "-";
  454. break;
  455. case SemIR::BuiltinFunctionKind::IntUMul:
  456. result_val = lhs_val * rhs_val;
  457. op_str = "*";
  458. break;
  459. case SemIR::BuiltinFunctionKind::IntUDiv:
  460. result_val = lhs_val.udiv(rhs_val);
  461. op_str = "/";
  462. break;
  463. case SemIR::BuiltinFunctionKind::IntUMod:
  464. result_val = lhs_val.urem(rhs_val);
  465. op_str = "%";
  466. break;
  467. // Bitwise.
  468. case SemIR::BuiltinFunctionKind::IntAnd:
  469. result_val = lhs_val & rhs_val;
  470. op_str = "&";
  471. break;
  472. case SemIR::BuiltinFunctionKind::IntOr:
  473. result_val = lhs_val | rhs_val;
  474. op_str = "|";
  475. break;
  476. case SemIR::BuiltinFunctionKind::IntXor:
  477. result_val = lhs_val ^ rhs_val;
  478. op_str = "^";
  479. break;
  480. // Bit shift.
  481. case SemIR::BuiltinFunctionKind::IntLeftShift:
  482. case SemIR::BuiltinFunctionKind::IntRightShift:
  483. op_str = (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift)
  484. ? llvm::StringLiteral("<<")
  485. : llvm::StringLiteral(">>");
  486. if (rhs_val.uge(lhs_val.getBitWidth()) ||
  487. (rhs_val.isNegative() && context.types().IsSignedInt(rhs.type_id))) {
  488. CARBON_DIAGNOSTIC(
  489. CompileTimeShiftOutOfRange, Error,
  490. "Shift distance not in range [0, {0}) in {1} {2} {3}.", unsigned,
  491. TypedInt, llvm::StringLiteral, TypedInt);
  492. context.emitter().Emit(loc, CompileTimeShiftOutOfRange,
  493. lhs_val.getBitWidth(),
  494. {.type = lhs.type_id, .value = lhs_val}, op_str,
  495. {.type = rhs.type_id, .value = rhs_val});
  496. // TODO: Is it useful to recover by returning 0 or -1?
  497. return SemIR::ConstantId::Error;
  498. }
  499. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  500. result_val = lhs_val.shl(rhs_val);
  501. } else if (context.types().IsSignedInt(lhs.type_id)) {
  502. result_val = lhs_val.ashr(rhs_val);
  503. } else {
  504. result_val = lhs_val.lshr(rhs_val);
  505. }
  506. break;
  507. default:
  508. CARBON_FATAL() << "Unexpected operation kind.";
  509. }
  510. if (overflow) {
  511. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  512. "Integer overflow in calculation {0} {1} {2}.", TypedInt,
  513. llvm::StringLiteral, TypedInt);
  514. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  515. {.type = lhs.type_id, .value = lhs_val}, op_str,
  516. {.type = rhs.type_id, .value = rhs_val});
  517. }
  518. return MakeIntResult(context, lhs.type_id, std::move(result_val));
  519. }
  520. // Performs a builtin integer comparison.
  521. static auto PerformBuiltinIntComparison(Context& context,
  522. SemIR::BuiltinFunctionKind builtin_kind,
  523. SemIR::InstId lhs_id,
  524. SemIR::InstId rhs_id,
  525. SemIR::TypeId bool_type_id)
  526. -> SemIR::ConstantId {
  527. auto lhs = context.insts().GetAs<SemIR::IntLiteral>(lhs_id);
  528. const auto& lhs_val = context.ints().Get(lhs.int_id);
  529. const auto& rhs_val = context.ints().Get(
  530. context.insts().GetAs<SemIR::IntLiteral>(rhs_id).int_id);
  531. bool is_signed = context.types().IsSignedInt(lhs.type_id);
  532. bool result;
  533. switch (builtin_kind) {
  534. case SemIR::BuiltinFunctionKind::IntEq:
  535. result = (lhs_val == rhs_val);
  536. break;
  537. case SemIR::BuiltinFunctionKind::IntNeq:
  538. result = (lhs_val != rhs_val);
  539. break;
  540. case SemIR::BuiltinFunctionKind::IntLess:
  541. result = is_signed ? lhs_val.slt(rhs_val) : lhs_val.ult(rhs_val);
  542. break;
  543. case SemIR::BuiltinFunctionKind::IntLessEq:
  544. result = is_signed ? lhs_val.sle(rhs_val) : lhs_val.ule(rhs_val);
  545. break;
  546. case SemIR::BuiltinFunctionKind::IntGreater:
  547. result = is_signed ? lhs_val.sgt(rhs_val) : lhs_val.sgt(rhs_val);
  548. break;
  549. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  550. result = is_signed ? lhs_val.sge(rhs_val) : lhs_val.sge(rhs_val);
  551. break;
  552. default:
  553. CARBON_FATAL() << "Unexpected operation kind.";
  554. }
  555. return MakeBoolResult(context, bool_type_id, result);
  556. }
  557. // Performs a builtin unary float -> float operation.
  558. static auto PerformBuiltinUnaryFloatOp(Context& context,
  559. SemIR::BuiltinFunctionKind builtin_kind,
  560. SemIR::InstId arg_id)
  561. -> SemIR::ConstantId {
  562. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  563. auto op_val = context.floats().Get(op.float_id);
  564. switch (builtin_kind) {
  565. case SemIR::BuiltinFunctionKind::FloatNegate:
  566. op_val.changeSign();
  567. break;
  568. default:
  569. CARBON_FATAL() << "Unexpected builtin kind";
  570. }
  571. return MakeFloatResult(context, op.type_id, std::move(op_val));
  572. }
  573. // Performs a builtin binary float -> float operation.
  574. static auto PerformBuiltinBinaryFloatOp(Context& context,
  575. SemIR::BuiltinFunctionKind builtin_kind,
  576. SemIR::InstId lhs_id,
  577. SemIR::InstId rhs_id)
  578. -> SemIR::ConstantId {
  579. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  580. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  581. auto lhs_val = context.floats().Get(lhs.float_id);
  582. auto rhs_val = context.floats().Get(rhs.float_id);
  583. llvm::APFloat result_val(lhs_val.getSemantics());
  584. switch (builtin_kind) {
  585. case SemIR::BuiltinFunctionKind::FloatAdd:
  586. result_val = lhs_val + rhs_val;
  587. break;
  588. case SemIR::BuiltinFunctionKind::FloatSub:
  589. result_val = lhs_val - rhs_val;
  590. break;
  591. case SemIR::BuiltinFunctionKind::FloatMul:
  592. result_val = lhs_val * rhs_val;
  593. break;
  594. case SemIR::BuiltinFunctionKind::FloatDiv:
  595. result_val = lhs_val / rhs_val;
  596. break;
  597. default:
  598. CARBON_FATAL() << "Unexpected operation kind.";
  599. }
  600. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  601. }
  602. // Performs a builtin float comparison.
  603. static auto PerformBuiltinFloatComparison(
  604. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  605. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  606. -> SemIR::ConstantId {
  607. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  608. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  609. const auto& lhs_val = context.floats().Get(lhs.float_id);
  610. const auto& rhs_val = context.floats().Get(rhs.float_id);
  611. bool result;
  612. switch (builtin_kind) {
  613. case SemIR::BuiltinFunctionKind::FloatEq:
  614. result = (lhs_val == rhs_val);
  615. break;
  616. case SemIR::BuiltinFunctionKind::FloatNeq:
  617. result = (lhs_val != rhs_val);
  618. break;
  619. case SemIR::BuiltinFunctionKind::FloatLess:
  620. result = lhs_val < rhs_val;
  621. break;
  622. case SemIR::BuiltinFunctionKind::FloatLessEq:
  623. result = lhs_val <= rhs_val;
  624. break;
  625. case SemIR::BuiltinFunctionKind::FloatGreater:
  626. result = lhs_val > rhs_val;
  627. break;
  628. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  629. result = lhs_val >= rhs_val;
  630. break;
  631. default:
  632. CARBON_FATAL() << "Unexpected operation kind.";
  633. }
  634. return MakeBoolResult(context, bool_type_id, result);
  635. }
  636. // Returns a constant for a call to a builtin function.
  637. static auto MakeConstantForBuiltinCall(Context& context, SemIRLoc loc,
  638. SemIR::Call call,
  639. SemIR::BuiltinFunctionKind builtin_kind,
  640. llvm::ArrayRef<SemIR::InstId> arg_ids,
  641. Phase phase) -> SemIR::ConstantId {
  642. switch (builtin_kind) {
  643. case SemIR::BuiltinFunctionKind::None:
  644. CARBON_FATAL() << "Not a builtin function.";
  645. case SemIR::BuiltinFunctionKind::IntMakeType32: {
  646. return context.constant_values().Get(SemIR::InstId::BuiltinIntType);
  647. }
  648. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  649. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  650. phase);
  651. }
  652. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  653. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  654. arg_ids[0], phase);
  655. }
  656. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  657. // TODO: Support a symbolic constant width.
  658. if (phase != Phase::Template) {
  659. break;
  660. }
  661. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  662. return SemIR::ConstantId::Error;
  663. }
  664. return context.constant_values().Get(SemIR::InstId::BuiltinFloatType);
  665. }
  666. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  667. return context.constant_values().Get(SemIR::InstId::BuiltinBoolType);
  668. }
  669. // Unary integer -> integer operations.
  670. case SemIR::BuiltinFunctionKind::IntSNegate:
  671. case SemIR::BuiltinFunctionKind::IntUNegate:
  672. case SemIR::BuiltinFunctionKind::IntComplement: {
  673. if (phase != Phase::Template) {
  674. break;
  675. }
  676. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  677. }
  678. // Binary integer -> integer operations.
  679. case SemIR::BuiltinFunctionKind::IntSAdd:
  680. case SemIR::BuiltinFunctionKind::IntSSub:
  681. case SemIR::BuiltinFunctionKind::IntSMul:
  682. case SemIR::BuiltinFunctionKind::IntSDiv:
  683. case SemIR::BuiltinFunctionKind::IntSMod:
  684. case SemIR::BuiltinFunctionKind::IntUAdd:
  685. case SemIR::BuiltinFunctionKind::IntUSub:
  686. case SemIR::BuiltinFunctionKind::IntUMul:
  687. case SemIR::BuiltinFunctionKind::IntUDiv:
  688. case SemIR::BuiltinFunctionKind::IntUMod:
  689. case SemIR::BuiltinFunctionKind::IntAnd:
  690. case SemIR::BuiltinFunctionKind::IntOr:
  691. case SemIR::BuiltinFunctionKind::IntXor:
  692. case SemIR::BuiltinFunctionKind::IntLeftShift:
  693. case SemIR::BuiltinFunctionKind::IntRightShift: {
  694. if (phase != Phase::Template) {
  695. break;
  696. }
  697. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  698. arg_ids[1]);
  699. }
  700. // Integer comparisons.
  701. case SemIR::BuiltinFunctionKind::IntEq:
  702. case SemIR::BuiltinFunctionKind::IntNeq:
  703. case SemIR::BuiltinFunctionKind::IntLess:
  704. case SemIR::BuiltinFunctionKind::IntLessEq:
  705. case SemIR::BuiltinFunctionKind::IntGreater:
  706. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  707. if (phase != Phase::Template) {
  708. break;
  709. }
  710. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  711. arg_ids[1], call.type_id);
  712. }
  713. // Unary float -> float operations.
  714. case SemIR::BuiltinFunctionKind::FloatNegate: {
  715. if (phase != Phase::Template) {
  716. break;
  717. }
  718. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  719. }
  720. // Binary float -> float operations.
  721. case SemIR::BuiltinFunctionKind::FloatAdd:
  722. case SemIR::BuiltinFunctionKind::FloatSub:
  723. case SemIR::BuiltinFunctionKind::FloatMul:
  724. case SemIR::BuiltinFunctionKind::FloatDiv: {
  725. if (phase != Phase::Template) {
  726. break;
  727. }
  728. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  729. arg_ids[1]);
  730. }
  731. // Float comparisons.
  732. case SemIR::BuiltinFunctionKind::FloatEq:
  733. case SemIR::BuiltinFunctionKind::FloatNeq:
  734. case SemIR::BuiltinFunctionKind::FloatLess:
  735. case SemIR::BuiltinFunctionKind::FloatLessEq:
  736. case SemIR::BuiltinFunctionKind::FloatGreater:
  737. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  738. if (phase != Phase::Template) {
  739. break;
  740. }
  741. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  742. arg_ids[1], call.type_id);
  743. }
  744. }
  745. return SemIR::ConstantId::NotConstant;
  746. }
  747. // Makes a constant for a call instruction.
  748. static auto MakeConstantForCall(Context& context, SemIRLoc loc,
  749. SemIR::Call call) -> SemIR::ConstantId {
  750. Phase phase = Phase::Template;
  751. // A call with an invalid argument list is used to represent an erroneous
  752. // call.
  753. //
  754. // TODO: Use a better representation for this.
  755. if (call.args_id == SemIR::InstBlockId::Invalid) {
  756. return SemIR::ConstantId::Error;
  757. }
  758. // If the callee isn't constant, this is not a constant call.
  759. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::callee_id,
  760. &phase)) {
  761. return SemIR::ConstantId::NotConstant;
  762. }
  763. auto callee_function =
  764. SemIR::GetCalleeFunction(context.sem_ir(), call.callee_id);
  765. if (!callee_function.function_id.is_valid()) {
  766. return SemIR::ConstantId::Error;
  767. }
  768. const auto& function = context.functions().Get(callee_function.function_id);
  769. // Handle calls to builtins.
  770. if (function.builtin_kind != SemIR::BuiltinFunctionKind::None) {
  771. if (!ReplaceFieldWithConstantValue(context, &call, &SemIR::Call::args_id,
  772. &phase)) {
  773. return SemIR::ConstantId::NotConstant;
  774. }
  775. if (phase == Phase::UnknownDueToError) {
  776. return SemIR::ConstantId::Error;
  777. }
  778. return MakeConstantForBuiltinCall(context, loc, call, function.builtin_kind,
  779. context.inst_blocks().Get(call.args_id),
  780. phase);
  781. }
  782. return SemIR::ConstantId::NotConstant;
  783. }
  784. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  785. -> SemIR::ConstantId {
  786. // TODO: Ensure we have test coverage for each of these cases that can result
  787. // in a constant, once those situations are all reachable.
  788. CARBON_KIND_SWITCH(inst) {
  789. // These cases are constants if their operands are.
  790. case SemIR::AddrOf::Kind:
  791. return RebuildIfFieldsAreConstant(context, inst,
  792. &SemIR::AddrOf::lvalue_id);
  793. case CARBON_KIND(SemIR::ArrayType array_type): {
  794. return RebuildAndValidateIfFieldsAreConstant(
  795. context, inst,
  796. [&](SemIR::ArrayType result) {
  797. auto bound_id = array_type.bound_id;
  798. auto int_bound =
  799. context.insts().TryGetAs<SemIR::IntLiteral>(result.bound_id);
  800. if (!int_bound) {
  801. // TODO: Permit symbolic array bounds. This will require fixing
  802. // callers of `GetArrayBoundValue`.
  803. context.TODO(bound_id, "symbolic array bound");
  804. return false;
  805. }
  806. // TODO: We should check that the size of the resulting array type
  807. // fits in 64 bits, not just that the bound does. Should we use a
  808. // 32-bit limit for 32-bit targets?
  809. const auto& bound_val = context.ints().Get(int_bound->int_id);
  810. if (context.types().IsSignedInt(int_bound->type_id) &&
  811. bound_val.isNegative()) {
  812. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  813. "Array bound of {0} is negative.", TypedInt);
  814. context.emitter().Emit(
  815. bound_id, ArrayBoundNegative,
  816. {.type = int_bound->type_id, .value = bound_val});
  817. return false;
  818. }
  819. if (bound_val.getActiveBits() > 64) {
  820. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  821. "Array bound of {0} is too large.", TypedInt);
  822. context.emitter().Emit(
  823. bound_id, ArrayBoundTooLarge,
  824. {.type = int_bound->type_id, .value = bound_val});
  825. return false;
  826. }
  827. return true;
  828. },
  829. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  830. }
  831. case SemIR::AssociatedEntityType::Kind:
  832. return RebuildIfFieldsAreConstant(
  833. context, inst, &SemIR::AssociatedEntityType::entity_type_id);
  834. case SemIR::BoundMethod::Kind:
  835. return RebuildIfFieldsAreConstant(context, inst,
  836. &SemIR::BoundMethod::object_id,
  837. &SemIR::BoundMethod::function_id);
  838. case SemIR::ClassType::Kind:
  839. // TODO: Look at generic arguments once they're modeled.
  840. return MakeConstantResult(context, inst, Phase::Template);
  841. case SemIR::InterfaceType::Kind:
  842. // TODO: Look at generic arguments once they're modeled.
  843. return MakeConstantResult(context, inst, Phase::Template);
  844. case SemIR::InterfaceWitness::Kind:
  845. return RebuildIfFieldsAreConstant(context, inst,
  846. &SemIR::InterfaceWitness::elements_id);
  847. case CARBON_KIND(SemIR::IntType int_type): {
  848. return RebuildAndValidateIfFieldsAreConstant(
  849. context, inst,
  850. [&](SemIR::IntType result) {
  851. return ValidateIntType(context, int_type.bit_width_id, result);
  852. },
  853. &SemIR::IntType::bit_width_id);
  854. }
  855. case SemIR::PointerType::Kind:
  856. return RebuildIfFieldsAreConstant(context, inst,
  857. &SemIR::PointerType::pointee_id);
  858. case CARBON_KIND(SemIR::FloatType float_type): {
  859. return RebuildAndValidateIfFieldsAreConstant(
  860. context, inst,
  861. [&](SemIR::FloatType result) {
  862. return ValidateFloatType(context, float_type.bit_width_id, result);
  863. },
  864. &SemIR::FloatType::bit_width_id);
  865. }
  866. case SemIR::StructType::Kind:
  867. return RebuildIfFieldsAreConstant(context, inst,
  868. &SemIR::StructType::fields_id);
  869. case SemIR::StructTypeField::Kind:
  870. return RebuildIfFieldsAreConstant(context, inst,
  871. &SemIR::StructTypeField::field_type_id);
  872. case SemIR::StructValue::Kind:
  873. return RebuildIfFieldsAreConstant(context, inst,
  874. &SemIR::StructValue::elements_id);
  875. case SemIR::TupleType::Kind:
  876. return RebuildIfFieldsAreConstant(context, inst,
  877. &SemIR::TupleType::elements_id);
  878. case SemIR::TupleValue::Kind:
  879. return RebuildIfFieldsAreConstant(context, inst,
  880. &SemIR::TupleValue::elements_id);
  881. case SemIR::UnboundElementType::Kind:
  882. return RebuildIfFieldsAreConstant(
  883. context, inst, &SemIR::UnboundElementType::class_type_id,
  884. &SemIR::UnboundElementType::element_type_id);
  885. // Initializers evaluate to a value of the object representation.
  886. case SemIR::ArrayInit::Kind:
  887. // TODO: Add an `ArrayValue` to represent a constant array object
  888. // representation instead of using a `TupleValue`.
  889. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  890. case SemIR::ClassInit::Kind:
  891. // TODO: Add a `ClassValue` to represent a constant class object
  892. // representation instead of using a `StructValue`.
  893. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  894. case SemIR::StructInit::Kind:
  895. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  896. case SemIR::TupleInit::Kind:
  897. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  898. case SemIR::AssociatedEntity::Kind:
  899. case SemIR::Builtin::Kind:
  900. case SemIR::FunctionType::Kind:
  901. case SemIR::GenericClassType::Kind:
  902. // Builtins are always template constants.
  903. return MakeConstantResult(context, inst, Phase::Template);
  904. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  905. return MakeConstantResult(
  906. context,
  907. SemIR::StructValue{.type_id = fn_decl.type_id,
  908. .elements_id = SemIR::InstBlockId::Empty},
  909. Phase::Template);
  910. }
  911. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  912. // If the class has generic arguments, we don't produce a class type, but
  913. // a callable whose return value is a class type.
  914. if (context.classes().Get(class_decl.class_id).is_generic()) {
  915. return MakeConstantResult(
  916. context,
  917. SemIR::StructValue{.type_id = class_decl.type_id,
  918. .elements_id = SemIR::InstBlockId::Empty},
  919. Phase::Template);
  920. }
  921. // A non-generic class declaration evaluates to the class type.
  922. return MakeConstantResult(
  923. context,
  924. SemIR::ClassType{.type_id = SemIR::TypeId::TypeType,
  925. .class_id = class_decl.class_id},
  926. Phase::Template);
  927. }
  928. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  929. // TODO: Once interfaces have generic arguments, handle them.
  930. return MakeConstantResult(
  931. context,
  932. SemIR::InterfaceType{.type_id = SemIR::TypeId::TypeType,
  933. .interface_id = interface_decl.interface_id},
  934. Phase::Template);
  935. }
  936. // These cases are treated as being the unique canonical definition of the
  937. // corresponding constant value.
  938. // TODO: This doesn't properly handle redeclarations. Consider adding a
  939. // corresponding `Value` inst for each of these cases.
  940. case SemIR::AssociatedConstantDecl::Kind:
  941. case SemIR::BaseDecl::Kind:
  942. case SemIR::FieldDecl::Kind:
  943. case SemIR::Namespace::Kind:
  944. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  945. case SemIR::BoolLiteral::Kind:
  946. case SemIR::FloatLiteral::Kind:
  947. case SemIR::IntLiteral::Kind:
  948. case SemIR::RealLiteral::Kind:
  949. case SemIR::StringLiteral::Kind:
  950. // Promote literals to the constant block.
  951. // TODO: Convert literals into a canonical form. Currently we can form two
  952. // different `i32` constants with the same value if they are represented
  953. // by `APInt`s with different bit widths.
  954. return MakeConstantResult(context, inst, Phase::Template);
  955. // The elements of a constant aggregate can be accessed.
  956. case SemIR::ClassElementAccess::Kind:
  957. case SemIR::InterfaceWitnessAccess::Kind:
  958. case SemIR::StructAccess::Kind:
  959. case SemIR::TupleAccess::Kind:
  960. return PerformAggregateAccess(context, inst);
  961. case SemIR::ArrayIndex::Kind:
  962. case SemIR::TupleIndex::Kind:
  963. return PerformAggregateIndex(context, inst);
  964. case CARBON_KIND(SemIR::Call call): {
  965. return MakeConstantForCall(context, inst_id, call);
  966. }
  967. // TODO: These need special handling.
  968. case SemIR::BindValue::Kind:
  969. case SemIR::Deref::Kind:
  970. case SemIR::ImportRefLoaded::Kind:
  971. case SemIR::Temporary::Kind:
  972. case SemIR::TemporaryStorage::Kind:
  973. case SemIR::ValueAsRef::Kind:
  974. break;
  975. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  976. // The constant form of a symbolic binding is an idealized form of the
  977. // original, with no equivalent value.
  978. bind.bind_name_id = context.bind_names().MakeCanonical(bind.bind_name_id);
  979. bind.value_id = SemIR::InstId::Invalid;
  980. return MakeConstantResult(context, bind, Phase::Symbolic);
  981. }
  982. // These semantic wrappers don't change the constant value.
  983. case CARBON_KIND(SemIR::AsCompatible inst): {
  984. return context.constant_values().Get(inst.source_id);
  985. }
  986. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  987. return context.constant_values().Get(typed_inst.value_id);
  988. }
  989. case CARBON_KIND(SemIR::ExportDecl typed_inst): {
  990. return context.constant_values().Get(typed_inst.value_id);
  991. }
  992. case CARBON_KIND(SemIR::NameRef typed_inst): {
  993. return context.constant_values().Get(typed_inst.value_id);
  994. }
  995. case CARBON_KIND(SemIR::Converted typed_inst): {
  996. return context.constant_values().Get(typed_inst.result_id);
  997. }
  998. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  999. return context.constant_values().Get(typed_inst.src_id);
  1000. }
  1001. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  1002. return context.constant_values().Get(typed_inst.result_id);
  1003. }
  1004. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  1005. return context.constant_values().Get(typed_inst.init_id);
  1006. }
  1007. case CARBON_KIND(SemIR::FacetTypeAccess typed_inst): {
  1008. // TODO: Once we start tracking the witness in the facet value, remove it
  1009. // here. For now, we model a facet value as just a type.
  1010. return context.constant_values().Get(typed_inst.facet_id);
  1011. }
  1012. // `not true` -> `false`, `not false` -> `true`.
  1013. // All other uses of unary `not` are non-constant.
  1014. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  1015. auto const_id = context.constant_values().Get(typed_inst.operand_id);
  1016. auto phase = GetPhase(const_id);
  1017. if (phase == Phase::Template) {
  1018. auto value =
  1019. context.insts().GetAs<SemIR::BoolLiteral>(const_id.inst_id());
  1020. return MakeBoolResult(context, value.type_id, !value.value.ToBool());
  1021. }
  1022. if (phase == Phase::UnknownDueToError) {
  1023. return SemIR::ConstantId::Error;
  1024. }
  1025. break;
  1026. }
  1027. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1028. // to itself.
  1029. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1030. auto inner_id = context.constant_values().Get(
  1031. context.types().GetInstId(typed_inst.inner_id));
  1032. if (inner_id.is_constant() &&
  1033. context.insts().Get(inner_id.inst_id()).Is<SemIR::ConstType>()) {
  1034. return inner_id;
  1035. }
  1036. return MakeConstantResult(context, inst, GetPhase(inner_id));
  1037. }
  1038. // These cases are either not expressions or not constant.
  1039. case SemIR::AdaptDecl::Kind:
  1040. case SemIR::AddrPattern::Kind:
  1041. case SemIR::Assign::Kind:
  1042. case SemIR::BindName::Kind:
  1043. case SemIR::BlockArg::Kind:
  1044. case SemIR::Branch::Kind:
  1045. case SemIR::BranchIf::Kind:
  1046. case SemIR::BranchWithArg::Kind:
  1047. case SemIR::ImplDecl::Kind:
  1048. case SemIR::Param::Kind:
  1049. case SemIR::ReturnExpr::Kind:
  1050. case SemIR::Return::Kind:
  1051. case SemIR::StructLiteral::Kind:
  1052. case SemIR::TupleLiteral::Kind:
  1053. case SemIR::VarStorage::Kind:
  1054. break;
  1055. case SemIR::ImportRefUnloaded::Kind:
  1056. CARBON_FATAL()
  1057. << "ImportRefUnloaded should be loaded before TryEvalInst.";
  1058. }
  1059. return SemIR::ConstantId::NotConstant;
  1060. }
  1061. } // namespace Carbon::Check