eval.cpp 37 KB

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