eval.cpp 33 KB

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