eval.cpp 59 KB

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