eval.cpp 45 KB

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