eval.cpp 71 KB

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