eval.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  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, return the
  128. // original ID.
  129. return context.inst_blocks().Add(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::InterfaceWitness::Kind:
  832. return RebuildIfFieldsAreConstant(context, inst,
  833. &SemIR::InterfaceWitness::elements_id);
  834. case CARBON_KIND(SemIR::IntType int_type): {
  835. return RebuildAndValidateIfFieldsAreConstant(
  836. context, inst,
  837. [&](SemIR::IntType result) {
  838. return ValidateIntType(context, int_type.bit_width_id, result);
  839. },
  840. &SemIR::IntType::bit_width_id);
  841. }
  842. case SemIR::PointerType::Kind:
  843. return RebuildIfFieldsAreConstant(context, inst,
  844. &SemIR::PointerType::pointee_id);
  845. case CARBON_KIND(SemIR::FloatType float_type): {
  846. return RebuildAndValidateIfFieldsAreConstant(
  847. context, inst,
  848. [&](SemIR::FloatType result) {
  849. return ValidateFloatType(context, float_type.bit_width_id, result);
  850. },
  851. &SemIR::FloatType::bit_width_id);
  852. }
  853. case SemIR::StructType::Kind:
  854. return RebuildIfFieldsAreConstant(context, inst,
  855. &SemIR::StructType::fields_id);
  856. case SemIR::StructTypeField::Kind:
  857. return RebuildIfFieldsAreConstant(context, inst,
  858. &SemIR::StructTypeField::field_type_id);
  859. case SemIR::StructValue::Kind:
  860. return RebuildIfFieldsAreConstant(context, inst,
  861. &SemIR::StructValue::elements_id);
  862. case SemIR::TupleType::Kind:
  863. return RebuildIfFieldsAreConstant(context, inst,
  864. &SemIR::TupleType::elements_id);
  865. case SemIR::TupleValue::Kind:
  866. return RebuildIfFieldsAreConstant(context, inst,
  867. &SemIR::TupleValue::elements_id);
  868. case SemIR::UnboundElementType::Kind:
  869. return RebuildIfFieldsAreConstant(
  870. context, inst, &SemIR::UnboundElementType::class_type_id,
  871. &SemIR::UnboundElementType::element_type_id);
  872. // Initializers evaluate to a value of the object representation.
  873. case SemIR::ArrayInit::Kind:
  874. // TODO: Add an `ArrayValue` to represent a constant array object
  875. // representation instead of using a `TupleValue`.
  876. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  877. case SemIR::ClassInit::Kind:
  878. // TODO: Add a `ClassValue` to represent a constant class object
  879. // representation instead of using a `StructValue`.
  880. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  881. case SemIR::StructInit::Kind:
  882. return RebuildInitAsValue(context, inst, SemIR::StructValue::Kind);
  883. case SemIR::TupleInit::Kind:
  884. return RebuildInitAsValue(context, inst, SemIR::TupleValue::Kind);
  885. case SemIR::AssociatedEntity::Kind:
  886. case SemIR::Builtin::Kind:
  887. case SemIR::FunctionType::Kind:
  888. // Builtins are always template constants.
  889. return MakeConstantResult(context, inst, Phase::Template);
  890. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  891. return MakeConstantResult(
  892. context,
  893. SemIR::StructValue{fn_decl.type_id, SemIR::InstBlockId::Empty},
  894. Phase::Template);
  895. }
  896. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  897. // TODO: Once classes have generic arguments, handle them.
  898. return MakeConstantResult(
  899. context,
  900. SemIR::ClassType{SemIR::TypeId::TypeType, class_decl.class_id},
  901. Phase::Template);
  902. }
  903. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  904. // TODO: Once interfaces have generic arguments, handle them.
  905. return MakeConstantResult(
  906. context,
  907. SemIR::InterfaceType{SemIR::TypeId::TypeType,
  908. interface_decl.interface_id},
  909. Phase::Template);
  910. }
  911. case SemIR::ClassType::Kind:
  912. case SemIR::InterfaceType::Kind:
  913. CARBON_FATAL() << inst.kind()
  914. << " is only created during corresponding Decl handling.";
  915. // These cases are treated as being the unique canonical definition of the
  916. // corresponding constant value.
  917. // TODO: This doesn't properly handle redeclarations. Consider adding a
  918. // corresponding `Value` inst for each of these cases.
  919. case SemIR::AssociatedConstantDecl::Kind:
  920. case SemIR::BaseDecl::Kind:
  921. case SemIR::FieldDecl::Kind:
  922. case SemIR::Namespace::Kind:
  923. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  924. case SemIR::BoolLiteral::Kind:
  925. case SemIR::FloatLiteral::Kind:
  926. case SemIR::IntLiteral::Kind:
  927. case SemIR::RealLiteral::Kind:
  928. case SemIR::StringLiteral::Kind:
  929. // Promote literals to the constant block.
  930. // TODO: Convert literals into a canonical form. Currently we can form two
  931. // different `i32` constants with the same value if they are represented
  932. // by `APInt`s with different bit widths.
  933. return MakeConstantResult(context, inst, Phase::Template);
  934. // The elements of a constant aggregate can be accessed.
  935. case SemIR::ClassElementAccess::Kind:
  936. case SemIR::InterfaceWitnessAccess::Kind:
  937. case SemIR::StructAccess::Kind:
  938. case SemIR::TupleAccess::Kind:
  939. return PerformAggregateAccess(context, inst);
  940. case SemIR::ArrayIndex::Kind:
  941. case SemIR::TupleIndex::Kind:
  942. return PerformAggregateIndex(context, inst);
  943. case CARBON_KIND(SemIR::Call call): {
  944. return MakeConstantForCall(context, inst_id, call);
  945. }
  946. // TODO: These need special handling.
  947. case SemIR::BindValue::Kind:
  948. case SemIR::Deref::Kind:
  949. case SemIR::ImportRefLoaded::Kind:
  950. case SemIR::ImportRefUsed::Kind:
  951. case SemIR::Temporary::Kind:
  952. case SemIR::TemporaryStorage::Kind:
  953. case SemIR::ValueAsRef::Kind:
  954. break;
  955. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  956. // The constant form of a symbolic binding is an idealized form of the
  957. // original, with no equivalent value.
  958. bind.value_id = SemIR::InstId::Invalid;
  959. return MakeConstantResult(context, bind, Phase::Symbolic);
  960. }
  961. // These semantic wrappers don't change the constant value.
  962. case CARBON_KIND(SemIR::AsCompatible inst): {
  963. return context.constant_values().Get(inst.source_id);
  964. }
  965. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  966. return context.constant_values().Get(typed_inst.value_id);
  967. }
  968. case CARBON_KIND(SemIR::NameRef typed_inst): {
  969. return context.constant_values().Get(typed_inst.value_id);
  970. }
  971. case CARBON_KIND(SemIR::Converted typed_inst): {
  972. return context.constant_values().Get(typed_inst.result_id);
  973. }
  974. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  975. return context.constant_values().Get(typed_inst.src_id);
  976. }
  977. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  978. return context.constant_values().Get(typed_inst.result_id);
  979. }
  980. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  981. return context.constant_values().Get(typed_inst.init_id);
  982. }
  983. case CARBON_KIND(SemIR::FacetTypeAccess typed_inst): {
  984. // TODO: Once we start tracking the witness in the facet value, remove it
  985. // here. For now, we model a facet value as just a type.
  986. return context.constant_values().Get(typed_inst.facet_id);
  987. }
  988. // `not true` -> `false`, `not false` -> `true`.
  989. // All other uses of unary `not` are non-constant.
  990. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  991. auto const_id = context.constant_values().Get(typed_inst.operand_id);
  992. auto phase = GetPhase(const_id);
  993. if (phase == Phase::Template) {
  994. auto value =
  995. context.insts().GetAs<SemIR::BoolLiteral>(const_id.inst_id());
  996. return MakeBoolResult(context, value.type_id, !value.value.ToBool());
  997. }
  998. if (phase == Phase::UnknownDueToError) {
  999. return SemIR::ConstantId::Error;
  1000. }
  1001. break;
  1002. }
  1003. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1004. // to itself.
  1005. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1006. auto inner_id = context.constant_values().Get(
  1007. context.types().GetInstId(typed_inst.inner_id));
  1008. if (inner_id.is_constant() &&
  1009. context.insts().Get(inner_id.inst_id()).Is<SemIR::ConstType>()) {
  1010. return inner_id;
  1011. }
  1012. return MakeConstantResult(context, inst, GetPhase(inner_id));
  1013. }
  1014. // These cases are either not expressions or not constant.
  1015. case SemIR::AdaptDecl::Kind:
  1016. case SemIR::AddrPattern::Kind:
  1017. case SemIR::Assign::Kind:
  1018. case SemIR::BindName::Kind:
  1019. case SemIR::BlockArg::Kind:
  1020. case SemIR::Branch::Kind:
  1021. case SemIR::BranchIf::Kind:
  1022. case SemIR::BranchWithArg::Kind:
  1023. case SemIR::ImplDecl::Kind:
  1024. case SemIR::Param::Kind:
  1025. case SemIR::ReturnExpr::Kind:
  1026. case SemIR::Return::Kind:
  1027. case SemIR::StructLiteral::Kind:
  1028. case SemIR::TupleLiteral::Kind:
  1029. case SemIR::VarStorage::Kind:
  1030. break;
  1031. case SemIR::ImportRefUnloaded::Kind:
  1032. CARBON_FATAL()
  1033. << "ImportRefUnloaded should be loaded before TryEvalInst.";
  1034. }
  1035. return SemIR::ConstantId::NotConstant;
  1036. }
  1037. } // namespace Carbon::Check