eval.cpp 74 KB

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