eval.cpp 59 KB

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