eval.cpp 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002
  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 <algorithm>
  6. #include <array>
  7. #include <optional>
  8. #include <utility>
  9. #include "toolchain/base/kind_switch.h"
  10. #include "toolchain/check/action.h"
  11. #include "toolchain/check/diagnostic_helpers.h"
  12. #include "toolchain/check/eval_inst.h"
  13. #include "toolchain/check/facet_type.h"
  14. #include "toolchain/check/generic.h"
  15. #include "toolchain/check/import_ref.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/diagnostics/diagnostic_emitter.h"
  19. #include "toolchain/diagnostics/format_providers.h"
  20. #include "toolchain/sem_ir/builtin_function_kind.h"
  21. #include "toolchain/sem_ir/function.h"
  22. #include "toolchain/sem_ir/generic.h"
  23. #include "toolchain/sem_ir/id_kind.h"
  24. #include "toolchain/sem_ir/ids.h"
  25. #include "toolchain/sem_ir/inst_kind.h"
  26. #include "toolchain/sem_ir/typed_insts.h"
  27. namespace Carbon::Check {
  28. namespace {
  29. // Information about an eval block of a specific that we are currently building.
  30. struct SpecificEvalInfo {
  31. // The region within the specific whose eval block we are building.
  32. SemIR::GenericInstIndex::Region region;
  33. // The work-in-progress contents of the eval block.
  34. llvm::ArrayRef<SemIR::InstId> values;
  35. };
  36. // Information about the context within which we are performing evaluation.
  37. // `context` must not be null.
  38. class EvalContext {
  39. public:
  40. explicit EvalContext(
  41. Context* context, SemIR::LocId fallback_loc_id,
  42. SemIR::SpecificId specific_id = SemIR::SpecificId::None,
  43. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  44. : context_(context),
  45. fallback_loc_id_(fallback_loc_id),
  46. specific_id_(specific_id),
  47. specific_eval_info_(specific_eval_info) {}
  48. // Gets the location to use for diagnostics if a better location is
  49. // unavailable.
  50. // TODO: This is also sometimes unavailable.
  51. auto fallback_loc_id() const -> SemIR::LocId { return fallback_loc_id_; }
  52. // Returns a location to use to point at an instruction in a diagnostic, given
  53. // a list of instructions that might have an attached location. This is the
  54. // location of the first instruction in the list that has a location if there
  55. // is one, and otherwise the fallback location.
  56. auto GetDiagnosticLoc(llvm::ArrayRef<SemIR::InstId> inst_ids)
  57. -> SemIR::LocId {
  58. for (auto inst_id : inst_ids) {
  59. if (inst_id.has_value() &&
  60. context_->insts().GetLocId(inst_id).has_value()) {
  61. return inst_id;
  62. }
  63. }
  64. return fallback_loc_id_;
  65. }
  66. // Gets the value of the specified compile-time binding in this context.
  67. // Returns `None` if the value is not fixed in this context.
  68. auto GetCompileTimeBindValue(SemIR::CompileTimeBindIndex bind_index)
  69. -> SemIR::ConstantId {
  70. if (!bind_index.has_value() || !specific_id_.has_value()) {
  71. return SemIR::ConstantId::None;
  72. }
  73. const auto& specific = specifics().Get(specific_id_);
  74. auto args = inst_blocks().Get(specific.args_id);
  75. // Bindings past the ones with known arguments can appear as local
  76. // bindings of entities declared within this generic.
  77. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  78. return SemIR::ConstantId::None;
  79. }
  80. return constant_values().Get(args[bind_index.index]);
  81. }
  82. // Given a constant value from the SemIR we're evaluating, finds the
  83. // corresponding constant value to use in the context of this evaluation.
  84. // This can be different if the original SemIR is for a generic and we are
  85. // evaluating with specific arguments for the generic parameters.
  86. auto GetInContext(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  87. if (!const_id.is_symbolic()) {
  88. return const_id;
  89. }
  90. // While resolving a specific, map from previous instructions in the eval
  91. // block into their evaluated values. These values won't be present on the
  92. // specific itself yet, so `GetConstantValueInSpecific` won't be able to
  93. // find them.
  94. const auto& symbolic_info = constant_values().GetSymbolicConstant(const_id);
  95. if (specific_eval_info_ && symbolic_info.index.has_value()) {
  96. CARBON_CHECK(
  97. symbolic_info.generic_id == specifics().Get(specific_id_).generic_id,
  98. "Instruction has constant operand in wrong generic");
  99. if (symbolic_info.index.region() == specific_eval_info_->region) {
  100. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  101. CARBON_CHECK(inst_id.has_value(),
  102. "Forward reference in eval block: index {0} referenced "
  103. "before evaluation",
  104. symbolic_info.index.index());
  105. return constant_values().Get(inst_id);
  106. } else {
  107. // TODO: Eliminate this call. This is the only place where we get a
  108. // value from a specific without using an InstId. There are three ways
  109. // we can get here:
  110. // 1) From GetConstantValue(InstId): these can use
  111. // GetConstantValueInSpecific.
  112. // 2) From GetConstantValue(TypeId): for these, we could change
  113. // instructions so they store InstIds instead of TypeIds.
  114. return GetConstantInSpecific(sem_ir(), specific_id_, const_id);
  115. }
  116. }
  117. // Map from a specific constant value to the canonical value.
  118. return constant_values().Get(symbolic_info.inst_id);
  119. }
  120. // Gets the constant value of the specified instruction in this context.
  121. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  122. return GetInContext(constant_values().Get(inst_id));
  123. }
  124. // Gets the constant value of the specified type in this context.
  125. auto GetConstantValue(SemIR::TypeId type_id) -> SemIR::ConstantId {
  126. return GetInContext(types().GetConstantId(type_id));
  127. }
  128. // Gets the constant value of the specified type in this context.
  129. auto GetConstantValueAsType(SemIR::TypeId id) -> SemIR::TypeId {
  130. return context().types().GetTypeIdForTypeConstantId(GetConstantValue(id));
  131. }
  132. // Gets the instruction describing the constant value of the specified type in
  133. // this context.
  134. auto GetConstantValueAsInst(SemIR::TypeId id) -> SemIR::Inst {
  135. return insts().Get(
  136. context().constant_values().GetInstId(GetConstantValue(id)));
  137. }
  138. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  139. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  140. auto entity_names() -> SemIR::EntityNameStore& {
  141. return sem_ir().entity_names();
  142. }
  143. auto functions() -> const ValueStore<SemIR::FunctionId>& {
  144. return sem_ir().functions();
  145. }
  146. auto classes() -> const ValueStore<SemIR::ClassId>& {
  147. return sem_ir().classes();
  148. }
  149. auto interfaces() -> const ValueStore<SemIR::InterfaceId>& {
  150. return sem_ir().interfaces();
  151. }
  152. auto specific_interfaces()
  153. -> CanonicalValueStore<SemIR::SpecificInterfaceId>& {
  154. return sem_ir().specific_interfaces();
  155. }
  156. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  157. return sem_ir().facet_types();
  158. }
  159. auto specifics() -> const SemIR::SpecificStore& {
  160. return sem_ir().specifics();
  161. }
  162. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  163. auto inst_blocks() -> SemIR::InstBlockStore& {
  164. return sem_ir().inst_blocks();
  165. }
  166. // Gets the constant value store. Note that this does not provide the constant
  167. // values that should be used from this evaluation context, and so should be
  168. // used with caution.
  169. auto constant_values() -> const SemIR::ConstantValueStore& {
  170. return sem_ir().constant_values();
  171. }
  172. // Gets the types store. Note that this does not provide the type values that
  173. // should be used from this evaluation context, and so should be used with
  174. // caution.
  175. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  176. auto context() -> Context& { return *context_; }
  177. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  178. auto emitter() -> DiagnosticEmitterBase& { return context().emitter(); }
  179. private:
  180. // The type-checking context in which we're performing evaluation.
  181. Context* context_;
  182. // The location to use for diagnostics when a better location isn't available.
  183. SemIR::LocId fallback_loc_id_;
  184. // The specific that we are evaluating within.
  185. SemIR::SpecificId specific_id_;
  186. // If we are currently evaluating an eval block for `specific_id_`,
  187. // information about that evaluation.
  188. std::optional<SpecificEvalInfo> specific_eval_info_;
  189. };
  190. } // namespace
  191. namespace {
  192. // The evaluation phase for an expression, computed by evaluation. These are
  193. // ordered so that the phase of an expression is the numerically highest phase
  194. // of its constituent evaluations. Note that an expression with any runtime
  195. // component is known to have Runtime phase even if it involves an evaluation
  196. // with UnknownDueToError phase.
  197. enum class Phase : uint8_t {
  198. // Value could be entirely and concretely computed.
  199. Concrete,
  200. // Evaluation phase is symbolic because the expression involves specifically a
  201. // reference to `.Self`.
  202. PeriodSelfSymbolic,
  203. // Evaluation phase is symbolic because the expression involves a reference to
  204. // a non-template symbolic binding other than `.Self`.
  205. CheckedSymbolic,
  206. // Evaluation phase is symbolic because the expression involves a reference to
  207. // a template parameter, or otherwise depends on something template dependent.
  208. // The expression might also reference non-template symbolic bindings.
  209. TemplateSymbolic,
  210. // The evaluation phase is unknown because evaluation encountered an
  211. // already-diagnosed semantic or syntax error. This is treated as being
  212. // potentially constant, but with an unknown phase.
  213. UnknownDueToError,
  214. // The expression has runtime phase because of a non-constant subexpression.
  215. Runtime,
  216. };
  217. } // namespace
  218. // Returns whether the specified phase is a constant phase.
  219. static auto IsConstant(Phase phase) -> bool {
  220. return phase < Phase::UnknownDueToError;
  221. }
  222. // Gets the phase in which the value of a constant will become available.
  223. static auto GetPhase(const SemIR::ConstantValueStore& constant_values,
  224. SemIR::ConstantId constant_id) -> Phase {
  225. if (!constant_id.is_constant()) {
  226. return Phase::Runtime;
  227. } else if (constant_id == SemIR::ErrorInst::ConstantId) {
  228. return Phase::UnknownDueToError;
  229. }
  230. switch (constant_values.GetDependence(constant_id)) {
  231. case SemIR::ConstantDependence::None:
  232. return Phase::Concrete;
  233. case SemIR::ConstantDependence::PeriodSelf:
  234. return Phase::PeriodSelfSymbolic;
  235. case SemIR::ConstantDependence::Checked:
  236. return Phase::CheckedSymbolic;
  237. case SemIR::ConstantDependence::Template:
  238. return Phase::TemplateSymbolic;
  239. }
  240. }
  241. // Returns the later of two phases.
  242. static auto LatestPhase(Phase a, Phase b) -> Phase {
  243. return static_cast<Phase>(
  244. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  245. }
  246. // Forms a `constant_id` describing a given evaluation result.
  247. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  248. -> SemIR::ConstantId {
  249. switch (phase) {
  250. case Phase::Concrete:
  251. return context.constants().GetOrAdd(inst,
  252. SemIR::ConstantDependence::None);
  253. case Phase::PeriodSelfSymbolic:
  254. return context.constants().GetOrAdd(
  255. inst, SemIR::ConstantDependence::PeriodSelf);
  256. case Phase::CheckedSymbolic:
  257. return context.constants().GetOrAdd(inst,
  258. SemIR::ConstantDependence::Checked);
  259. case Phase::TemplateSymbolic:
  260. return context.constants().GetOrAdd(inst,
  261. SemIR::ConstantDependence::Template);
  262. case Phase::UnknownDueToError:
  263. return SemIR::ErrorInst::ConstantId;
  264. case Phase::Runtime:
  265. return SemIR::ConstantId::NotConstant;
  266. }
  267. }
  268. // Forms a `constant_id` describing why an evaluation was not constant.
  269. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  270. return phase == Phase::UnknownDueToError ? SemIR::ErrorInst::ConstantId
  271. : SemIR::ConstantId::NotConstant;
  272. }
  273. // Converts a bool value into a ConstantId.
  274. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  275. bool result) -> SemIR::ConstantId {
  276. return MakeConstantResult(
  277. context,
  278. SemIR::BoolLiteral{.type_id = bool_type_id,
  279. .value = SemIR::BoolValue::From(result)},
  280. Phase::Concrete);
  281. }
  282. // Converts an APInt value into a ConstantId.
  283. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  284. bool is_signed, llvm::APInt value)
  285. -> SemIR::ConstantId {
  286. CARBON_CHECK(is_signed == context.types().IsSignedInt(type_id));
  287. auto result = is_signed ? context.ints().AddSigned(std::move(value))
  288. : context.ints().AddUnsigned(std::move(value));
  289. return MakeConstantResult(
  290. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  291. Phase::Concrete);
  292. }
  293. // Converts an APFloat value into a ConstantId.
  294. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  295. llvm::APFloat value) -> SemIR::ConstantId {
  296. auto result = context.floats().Add(std::move(value));
  297. return MakeConstantResult(
  298. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  299. Phase::Concrete);
  300. }
  301. // Creates a FacetType constant.
  302. static auto MakeFacetTypeResult(Context& context,
  303. const SemIR::FacetTypeInfo& info, Phase phase)
  304. -> SemIR::ConstantId {
  305. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  306. return MakeConstantResult(context,
  307. SemIR::FacetType{.type_id = SemIR::TypeType::TypeId,
  308. .facet_type_id = facet_type_id},
  309. phase);
  310. }
  311. // `GetConstantValue` checks to see whether the provided ID describes a value
  312. // with constant phase, and if so, returns the corresponding constant value.
  313. // Overloads are provided for different kinds of ID.
  314. // AbsoluteInstId can not have its values substituted, so this overload is
  315. // deleted. This prevents conversion to InstId.
  316. static auto GetConstantValue(EvalContext& eval_context,
  317. SemIR::AbsoluteInstId inst_id, Phase* phase)
  318. -> SemIR::InstId = delete;
  319. // If the given instruction is constant, returns its constant value.
  320. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  321. Phase* phase) -> SemIR::InstId {
  322. if (!inst_id.has_value()) {
  323. return SemIR::InstId::None;
  324. }
  325. auto const_id = eval_context.GetConstantValue(inst_id);
  326. *phase =
  327. LatestPhase(*phase, GetPhase(eval_context.constant_values(), const_id));
  328. return eval_context.constant_values().GetInstId(const_id);
  329. }
  330. // If the given instruction is constant, returns its constant value. When
  331. // determining the phase of the result, ignore any dependence on `.Self`.
  332. //
  333. // This is used when evaluating facet types, for which `where` expressions using
  334. // `.Self` should not be considered symbolic
  335. // - `Interface where .Self impls I and .A = bool` -> concrete
  336. // - `T:! type` ... `Interface where .A = T` -> symbolic, since uses `T` which
  337. // is symbolic and not due to `.Self`.
  338. static auto GetConstantValueIgnoringPeriodSelf(EvalContext& eval_context,
  339. SemIR::InstId inst_id,
  340. Phase* phase) -> SemIR::InstId {
  341. if (!inst_id.has_value()) {
  342. return SemIR::InstId::None;
  343. }
  344. auto const_id = eval_context.GetConstantValue(inst_id);
  345. Phase constant_phase = GetPhase(eval_context.constant_values(), const_id);
  346. // Since LatestPhase(x, Phase::Concrete) == x, this is equivalent to replacing
  347. // Phase::PeriodSelfSymbolic with Phase::Concrete.
  348. if (constant_phase != Phase::PeriodSelfSymbolic) {
  349. *phase = LatestPhase(*phase, constant_phase);
  350. }
  351. return eval_context.constant_values().GetInstId(const_id);
  352. }
  353. // Find the instruction that the given instruction instantiates to, and return
  354. // that.
  355. static auto GetConstantValue(EvalContext& eval_context,
  356. SemIR::MetaInstId inst_id, Phase* phase)
  357. -> SemIR::MetaInstId {
  358. Phase inner_phase = Phase::Concrete;
  359. if (auto const_inst_id =
  360. GetConstantValue(eval_context, SemIR::InstId(inst_id), &inner_phase);
  361. const_inst_id.has_value()) {
  362. // The instruction has a constant value. Use that as the operand of the
  363. // action.
  364. *phase = LatestPhase(*phase, inner_phase);
  365. return const_inst_id;
  366. }
  367. // If this instruction is splicing in an action result, that action result is
  368. // our operand.
  369. if (auto splice = eval_context.insts().TryGetAs<SemIR::SpliceInst>(inst_id)) {
  370. if (auto spliced_inst_id =
  371. GetConstantValue(eval_context, splice->inst_id, phase);
  372. spliced_inst_id.has_value()) {
  373. if (auto inst_value_id = eval_context.insts().TryGetAs<SemIR::InstValue>(
  374. spliced_inst_id)) {
  375. return inst_value_id->inst_id;
  376. }
  377. }
  378. }
  379. // Otherwise, this is a normal instruction.
  380. if (OperandIsDependent(eval_context.context(), inst_id)) {
  381. *phase = LatestPhase(*phase, Phase::TemplateSymbolic);
  382. }
  383. return inst_id;
  384. }
  385. static auto GetConstantValue(EvalContext& eval_context,
  386. SemIR::TypeInstId inst_id, Phase* phase)
  387. -> SemIR::TypeInstId {
  388. // The input instruction is a TypeInstId, and eval does not change concrete
  389. // types (like TypeType which TypeInstId implies), so the result is also a
  390. // valid TypeInstId.
  391. return SemIR::TypeInstId::UnsafeMake(GetConstantValue(
  392. eval_context, static_cast<SemIR::InstId>(inst_id), phase));
  393. }
  394. // Explicitly discard a `DestInstId`, because we should not be using the
  395. // destination as part of evaluation.
  396. static auto GetConstantValue(EvalContext& /*eval_context*/,
  397. SemIR::DestInstId /*inst_id*/, Phase* /*phase*/)
  398. -> SemIR::DestInstId {
  399. return SemIR::InstId::None;
  400. }
  401. // Given a type which may refer to a generic parameter, returns the
  402. // corresponding type in the evaluation context.
  403. static auto GetConstantValue(EvalContext& eval_context, SemIR::TypeId type_id,
  404. Phase* phase) -> SemIR::TypeId {
  405. auto const_id = eval_context.GetConstantValue(type_id);
  406. *phase =
  407. LatestPhase(*phase, GetPhase(eval_context.constant_values(), const_id));
  408. return eval_context.context().types().GetTypeIdForTypeConstantId(const_id);
  409. }
  410. // AbsoluteInstBlockId can not have its values substituted, so this overload is
  411. // deleted. This prevents conversion to InstBlockId.
  412. static auto GetConstantValue(EvalContext& eval_context,
  413. SemIR::AbsoluteInstBlockId inst_block_id,
  414. Phase* phase) -> SemIR::InstBlockId = delete;
  415. // If the given instruction block contains only constants, returns a
  416. // corresponding block of those values.
  417. static auto GetConstantValue(EvalContext& eval_context,
  418. SemIR::InstBlockId inst_block_id, Phase* phase)
  419. -> SemIR::InstBlockId {
  420. if (!inst_block_id.has_value()) {
  421. return SemIR::InstBlockId::None;
  422. }
  423. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  424. llvm::SmallVector<SemIR::InstId> const_insts;
  425. for (auto inst_id : insts) {
  426. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  427. if (!const_inst_id.has_value()) {
  428. return SemIR::InstBlockId::None;
  429. }
  430. // Once we leave the small buffer, we know the first few elements are all
  431. // constant, so it's likely that the entire block is constant. Resize to the
  432. // target size given that we're going to allocate memory now anyway.
  433. if (const_insts.size() == const_insts.capacity()) {
  434. const_insts.reserve(insts.size());
  435. }
  436. const_insts.push_back(const_inst_id);
  437. }
  438. // TODO: If the new block is identical to the original block, and we know the
  439. // old ID was canonical, return the original ID.
  440. return eval_context.inst_blocks().AddCanonical(const_insts);
  441. }
  442. // Compute the constant value of a type block. This may be different from the
  443. // input type block if we have known generic arguments.
  444. static auto GetConstantValue(EvalContext& eval_context,
  445. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  446. -> SemIR::StructTypeFieldsId {
  447. if (!fields_id.has_value()) {
  448. return SemIR::StructTypeFieldsId::None;
  449. }
  450. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  451. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  452. for (auto field : fields) {
  453. auto new_type_inst_id =
  454. GetConstantValue(eval_context, field.type_inst_id, phase);
  455. if (!new_type_inst_id.has_value()) {
  456. return SemIR::StructTypeFieldsId::None;
  457. }
  458. // Once we leave the small buffer, we know the first few elements are all
  459. // constant, so it's likely that the entire block is constant. Resize to the
  460. // target size given that we're going to allocate memory now anyway.
  461. if (new_fields.size() == new_fields.capacity()) {
  462. new_fields.reserve(fields.size());
  463. }
  464. new_fields.push_back(
  465. {.name_id = field.name_id, .type_inst_id = new_type_inst_id});
  466. }
  467. // TODO: If the new block is identical to the original block, and we know the
  468. // old ID was canonical, return the original ID.
  469. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  470. }
  471. // The constant value of a specific is the specific with the corresponding
  472. // constant values for its arguments.
  473. static auto GetConstantValue(EvalContext& eval_context,
  474. SemIR::SpecificId specific_id, Phase* phase)
  475. -> SemIR::SpecificId {
  476. if (!specific_id.has_value()) {
  477. return SemIR::SpecificId::None;
  478. }
  479. const auto& specific = eval_context.specifics().Get(specific_id);
  480. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  481. if (!args_id.has_value()) {
  482. return SemIR::SpecificId::None;
  483. }
  484. if (args_id == specific.args_id) {
  485. const auto& specific = eval_context.specifics().Get(specific_id);
  486. // A constant specific_id should always have a resolved declaration. The
  487. // specific_id from the instruction may coincidentally be canonical, and so
  488. // constant evaluation gives the same value. In that case, we still need to
  489. // ensure its declaration is resolved.
  490. //
  491. // However, don't resolve the declaration if the generic's eval block hasn't
  492. // been set yet. This happens when building the eval block during import.
  493. //
  494. // TODO: Change importing of generic eval blocks to be less fragile and
  495. // remove this `if` so we unconditionally call `ResolveSpecificDeclaration`.
  496. if (!specific.decl_block_id.has_value() && eval_context.context()
  497. .generics()
  498. .Get(specific.generic_id)
  499. .decl_block_id.has_value()) {
  500. ResolveSpecificDeclaration(eval_context.context(),
  501. eval_context.fallback_loc_id(), specific_id);
  502. }
  503. return specific_id;
  504. }
  505. return MakeSpecific(eval_context.context(), eval_context.fallback_loc_id(),
  506. specific.generic_id, args_id);
  507. }
  508. static auto GetConstantValue(EvalContext& eval_context,
  509. SemIR::SpecificInterfaceId specific_interface_id,
  510. Phase* phase) -> SemIR::SpecificInterfaceId {
  511. const auto& interface =
  512. eval_context.specific_interfaces().Get(specific_interface_id);
  513. if (!interface.specific_id.has_value()) {
  514. return specific_interface_id;
  515. }
  516. return eval_context.specific_interfaces().Add(
  517. {.interface_id = interface.interface_id,
  518. .specific_id =
  519. GetConstantValue(eval_context, interface.specific_id, phase)});
  520. }
  521. // Like `GetConstantValue` but does a `FacetTypeId` -> `FacetTypeInfo`
  522. // conversion. Does not perform canonicalization.
  523. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  524. SemIR::FacetTypeId facet_type_id,
  525. Phase* phase) -> SemIR::FacetTypeInfo {
  526. const auto& orig = eval_context.facet_types().Get(facet_type_id);
  527. SemIR::FacetTypeInfo info;
  528. info.extend_constraints.reserve(orig.extend_constraints.size());
  529. for (const auto& interface : orig.extend_constraints) {
  530. info.extend_constraints.push_back(
  531. {.interface_id = interface.interface_id,
  532. .specific_id =
  533. GetConstantValue(eval_context, interface.specific_id, phase)});
  534. }
  535. info.self_impls_constraints.reserve(orig.self_impls_constraints.size());
  536. for (const auto& interface : orig.self_impls_constraints) {
  537. info.self_impls_constraints.push_back(
  538. {.interface_id = interface.interface_id,
  539. .specific_id =
  540. GetConstantValue(eval_context, interface.specific_id, phase)});
  541. }
  542. info.rewrite_constraints.reserve(orig.rewrite_constraints.size());
  543. for (const auto& rewrite : orig.rewrite_constraints) {
  544. // `where` requirements using `.Self` should not be considered symbolic.
  545. auto lhs_id =
  546. GetConstantValueIgnoringPeriodSelf(eval_context, rewrite.lhs_id, phase);
  547. auto rhs_id =
  548. GetConstantValueIgnoringPeriodSelf(eval_context, rewrite.rhs_id, phase);
  549. info.rewrite_constraints.push_back({.lhs_id = lhs_id, .rhs_id = rhs_id});
  550. }
  551. // TODO: Process other requirements.
  552. info.other_requirements = orig.other_requirements;
  553. return info;
  554. }
  555. static auto GetConstantValue(EvalContext& eval_context,
  556. SemIR::FacetTypeId facet_type_id, Phase* phase)
  557. -> SemIR::FacetTypeId {
  558. SemIR::FacetTypeInfo info =
  559. GetConstantFacetTypeInfo(eval_context, facet_type_id, phase);
  560. info.Canonicalize();
  561. // TODO: Return `facet_type_id` if we can detect nothing has changed.
  562. return eval_context.facet_types().Add(info);
  563. }
  564. static auto GetConstantValue(EvalContext& eval_context,
  565. SemIR::EntityNameId entity_name_id, Phase* phase)
  566. -> SemIR::EntityNameId {
  567. const auto& bind_name = eval_context.entity_names().Get(entity_name_id);
  568. Phase name_phase;
  569. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  570. name_phase = Phase::PeriodSelfSymbolic;
  571. } else if (!bind_name.bind_index().has_value()) {
  572. name_phase = Phase::Concrete;
  573. } else if (bind_name.is_template) {
  574. name_phase = Phase::TemplateSymbolic;
  575. } else {
  576. name_phase = Phase::CheckedSymbolic;
  577. }
  578. *phase = LatestPhase(*phase, name_phase);
  579. return eval_context.entity_names().MakeCanonical(entity_name_id);
  580. }
  581. // Replaces the specified field of the given typed instruction with its constant
  582. // value, if it has constant phase. Returns true on success, false if the value
  583. // has runtime phase.
  584. template <typename InstT, typename FieldIdT>
  585. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  586. InstT* inst, FieldIdT InstT::*field,
  587. Phase* phase) -> bool {
  588. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  589. if (!unwrapped.has_value() && (inst->*field).has_value()) {
  590. return false;
  591. }
  592. inst->*field = unwrapped;
  593. return true;
  594. }
  595. // Function template that can be called with an argument of type `T`. Used below
  596. // to detect which overloads of `GetConstantValue` exist.
  597. template <typename T>
  598. static void Accept(T /*arg*/) {}
  599. // Determines whether a `GetConstantValue` overload exists for a given ID type.
  600. // Note that we do not check whether `GetConstantValue` is *callable* with a
  601. // given ID type, because that would use the `InstId` overload for
  602. // `AbsoluteInstId` and similar wrapper types, which should be left alone.
  603. template <typename IdT>
  604. static constexpr bool HasGetConstantValueOverload = requires {
  605. Accept<auto (*)(EvalContext&, IdT, Phase*)->IdT>(GetConstantValue);
  606. };
  607. using ArgHandlerFnT = auto(EvalContext& context, int32_t arg, Phase* phase)
  608. -> int32_t;
  609. // Returns a lookup table to get constants by Id::Kind. Requires a null IdKind
  610. // as a parameter in order to get the type pack.
  611. template <typename... Types>
  612. static constexpr auto MakeArgHandlerTable(
  613. SemIR::TypeEnum<Types...>* /*id_kind*/)
  614. -> std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> {
  615. std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> table = {};
  616. ((table[SemIR::IdKind::template For<Types>.ToIndex()] =
  617. [](EvalContext& eval_context, int32_t arg, Phase* phase) -> int32_t {
  618. auto id = SemIR::Inst::FromRaw<Types>(arg);
  619. if constexpr (HasGetConstantValueOverload<Types>) {
  620. // If we have a custom `GetConstantValue` overload, call it.
  621. return SemIR::Inst::ToRaw(GetConstantValue(eval_context, id, phase));
  622. } else {
  623. // Otherwise, we assume the value is already constant.
  624. return arg;
  625. }
  626. }),
  627. ...);
  628. table[SemIR::IdKind::Invalid.ToIndex()] = [](EvalContext& /*context*/,
  629. int32_t /*arg*/,
  630. Phase* /*phase*/) -> int32_t {
  631. CARBON_FATAL("Instruction has argument with invalid IdKind");
  632. };
  633. table[SemIR::IdKind::None.ToIndex()] =
  634. [](EvalContext& /*context*/, int32_t arg, Phase* /*phase*/) -> int32_t {
  635. return arg;
  636. };
  637. return table;
  638. }
  639. // Given the stored value `arg` of an instruction field and its corresponding
  640. // kind `kind`, returns the constant value to use for that field, if it has a
  641. // constant phase. `*phase` is updated to include the new constant value. If
  642. // the resulting phase is not constant, the returned value is not useful and
  643. // will typically be `NoneIndex`.
  644. static auto GetConstantValueForArg(EvalContext& eval_context,
  645. SemIR::Inst::ArgAndKind arg_and_kind,
  646. Phase* phase) -> int32_t {
  647. static constexpr auto Table =
  648. MakeArgHandlerTable(static_cast<SemIR::IdKind*>(nullptr));
  649. return Table[arg_and_kind.kind().ToIndex()](eval_context,
  650. arg_and_kind.value(), phase);
  651. }
  652. // Given an instruction, replaces its type and operands with their constant
  653. // values from the specified evaluation context. `*phase` is updated to describe
  654. // the constant phase of the result. Returns whether `*phase` is a constant
  655. // phase; if not, `inst` may not be fully updated and should not be used.
  656. static auto ReplaceAllFieldsWithConstantValues(EvalContext& eval_context,
  657. SemIR::Inst* inst, Phase* phase)
  658. -> bool {
  659. auto type_id = GetConstantValue(eval_context, inst->type_id(), phase);
  660. inst->SetType(type_id);
  661. if (!IsConstant(*phase)) {
  662. return false;
  663. }
  664. auto arg0 =
  665. GetConstantValueForArg(eval_context, inst->arg0_and_kind(), phase);
  666. if (!IsConstant(*phase)) {
  667. return false;
  668. }
  669. auto arg1 =
  670. GetConstantValueForArg(eval_context, inst->arg1_and_kind(), phase);
  671. if (!IsConstant(*phase)) {
  672. return false;
  673. }
  674. inst->SetArgs(arg0, arg1);
  675. return true;
  676. }
  677. auto AddImportedConstant(Context& context, SemIR::Inst inst)
  678. -> SemIR::ConstantId {
  679. EvalContext eval_context(&context, SemIR::InstId::None);
  680. Phase phase = Phase::Concrete;
  681. switch (inst.kind().value_kind()) {
  682. case SemIR::InstValueKind::Typed:
  683. // TODO: Can we avoid doing this replacement? It may do things that are
  684. // undesirable during importing, such as resolving specifics.
  685. if (!ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  686. return SemIR::ConstantId::NotConstant;
  687. }
  688. break;
  689. case SemIR::InstValueKind::None:
  690. // Instructions without a type_id are not evaluated.
  691. break;
  692. }
  693. return MakeConstantResult(context, inst, phase);
  694. }
  695. // Performs an index into a homogeneous aggregate, retrieving the specified
  696. // element.
  697. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  698. -> SemIR::ConstantId {
  699. Phase phase = Phase::Concrete;
  700. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  701. if (!index_id.has_value()) {
  702. return MakeNonConstantResult(phase);
  703. }
  704. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  705. if (!index) {
  706. CARBON_CHECK(phase != Phase::Concrete,
  707. "Concrete constant integer should be a literal");
  708. return MakeNonConstantResult(phase);
  709. }
  710. // Array indexing is invalid if the index is constant and out of range,
  711. // regardless of whether the array itself is constant.
  712. const auto& index_val = eval_context.ints().Get(index->int_id);
  713. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  714. eval_context.insts().Get(inst.array_id).type_id());
  715. if (auto array_type =
  716. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  717. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  718. array_type->bound_id)) {
  719. // This awkward call to `getZExtValue` is a workaround for APInt not
  720. // supporting comparisons between integers of different bit widths.
  721. if (index_val.getActiveBits() > 64 ||
  722. eval_context.ints()
  723. .Get(bound->int_id)
  724. .ule(index_val.getZExtValue())) {
  725. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  726. "array index `{0}` is past the end of type {1}",
  727. TypedInt, SemIR::TypeId);
  728. eval_context.emitter().Emit(
  729. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  730. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  731. return SemIR::ErrorInst::ConstantId;
  732. }
  733. }
  734. }
  735. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  736. if (!aggregate_id.has_value()) {
  737. return MakeNonConstantResult(phase);
  738. }
  739. auto aggregate =
  740. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  741. if (!aggregate) {
  742. CARBON_CHECK(phase != Phase::Concrete,
  743. "Unexpected representation for template constant aggregate");
  744. return MakeNonConstantResult(phase);
  745. }
  746. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  747. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  748. }
  749. // Forms a constant int type as an evaluation result. Requires that width_id is
  750. // constant.
  751. static auto MakeIntTypeResult(Context& context, SemIR::LocId loc_id,
  752. SemIR::IntKind int_kind, SemIR::InstId width_id,
  753. Phase phase) -> SemIR::ConstantId {
  754. auto result = SemIR::IntType{
  755. .type_id = GetSingletonType(context, SemIR::TypeType::InstId),
  756. .int_kind = int_kind,
  757. .bit_width_id = width_id};
  758. if (!ValidateIntType(context, loc_id, result)) {
  759. return SemIR::ErrorInst::ConstantId;
  760. }
  761. return MakeConstantResult(context, result, phase);
  762. }
  763. // Performs a conversion between integer types, truncating if the value doesn't
  764. // fit in the destination type.
  765. static auto PerformIntConvert(Context& context, SemIR::InstId arg_id,
  766. SemIR::TypeId dest_type_id) -> SemIR::ConstantId {
  767. auto arg_val =
  768. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(arg_id).int_id);
  769. auto [dest_is_signed, bit_width_id] =
  770. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  771. if (bit_width_id.has_value()) {
  772. // TODO: If the value fits in the destination type, reuse the existing
  773. // int_id rather than recomputing it. This is probably the most common case.
  774. bool src_is_signed = context.sem_ir().types().IsSignedInt(
  775. context.insts().Get(arg_id).type_id());
  776. unsigned width = context.ints().Get(bit_width_id).getZExtValue();
  777. arg_val =
  778. src_is_signed ? arg_val.sextOrTrunc(width) : arg_val.zextOrTrunc(width);
  779. }
  780. return MakeIntResult(context, dest_type_id, dest_is_signed, arg_val);
  781. }
  782. // Performs a conversion between integer types, diagnosing if the value doesn't
  783. // fit in the destination type.
  784. static auto PerformCheckedIntConvert(Context& context, SemIR::LocId loc_id,
  785. SemIR::InstId arg_id,
  786. SemIR::TypeId dest_type_id)
  787. -> SemIR::ConstantId {
  788. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  789. auto arg_val = context.ints().Get(arg.int_id);
  790. auto [is_signed, bit_width_id] =
  791. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  792. auto width = bit_width_id.has_value()
  793. ? context.ints().Get(bit_width_id).getZExtValue()
  794. : arg_val.getBitWidth();
  795. if (!is_signed && arg_val.isNegative()) {
  796. CARBON_DIAGNOSTIC(
  797. NegativeIntInUnsignedType, Error,
  798. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  799. SemIR::TypeId);
  800. context.emitter().Emit(loc_id, NegativeIntInUnsignedType,
  801. {.type = arg.type_id, .value = arg_val},
  802. dest_type_id);
  803. }
  804. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  805. if (arg_non_sign_bits + is_signed > width) {
  806. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  807. "integer value {0} too large for type {1}", TypedInt,
  808. SemIR::TypeId);
  809. context.emitter().Emit(loc_id, IntTooLargeForType,
  810. {.type = arg.type_id, .value = arg_val},
  811. dest_type_id);
  812. }
  813. return MakeConstantResult(
  814. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  815. Phase::Concrete);
  816. }
  817. // Issues a diagnostic for a compile-time division by zero.
  818. static auto DiagnoseDivisionByZero(Context& context, SemIR::LocId loc_id)
  819. -> void {
  820. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  821. context.emitter().Emit(loc_id, CompileTimeDivisionByZero);
  822. }
  823. // Get an integer at a suitable bit-width: either `bit_width_id` if it has a
  824. // value, or the canonical width from the value store if not.
  825. static auto GetIntAtSuitableWidth(Context& context, IntId int_id,
  826. IntId bit_width_id) -> llvm::APInt {
  827. return bit_width_id.has_value()
  828. ? context.ints().GetAtWidth(int_id, bit_width_id)
  829. : context.ints().Get(int_id);
  830. }
  831. // Performs a builtin unary integer -> integer operation.
  832. static auto PerformBuiltinUnaryIntOp(Context& context, SemIR::LocId loc_id,
  833. SemIR::BuiltinFunctionKind builtin_kind,
  834. SemIR::InstId arg_id)
  835. -> SemIR::ConstantId {
  836. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  837. auto [is_signed, bit_width_id] =
  838. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  839. llvm::APInt op_val = GetIntAtSuitableWidth(context, op.int_id, bit_width_id);
  840. switch (builtin_kind) {
  841. case SemIR::BuiltinFunctionKind::IntSNegate:
  842. if (op_val.isMinSignedValue()) {
  843. if (bit_width_id.has_value()) {
  844. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  845. "integer overflow in negation of {0}", TypedInt);
  846. context.emitter().Emit(loc_id, CompileTimeIntegerNegateOverflow,
  847. {.type = op.type_id, .value = op_val});
  848. } else {
  849. // Widen the integer so we don't overflow into the sign bit.
  850. op_val = op_val.sext(op_val.getBitWidth() +
  851. llvm::APInt::APINT_BITS_PER_WORD);
  852. }
  853. }
  854. op_val.negate();
  855. break;
  856. case SemIR::BuiltinFunctionKind::IntUNegate:
  857. CARBON_CHECK(bit_width_id.has_value(), "Unsigned negate on unsized int");
  858. op_val.negate();
  859. break;
  860. case SemIR::BuiltinFunctionKind::IntComplement:
  861. // TODO: Should we have separate builtins for signed and unsigned
  862. // complement? Like with signed/unsigned negate, these operations do
  863. // different things to the integer value, even though they do the same
  864. // thing to the bits. We treat IntLiteral complement as signed complement,
  865. // given that the result of unsigned complement depends on the bit width.
  866. op_val.flipAllBits();
  867. break;
  868. default:
  869. CARBON_FATAL("Unexpected builtin kind");
  870. }
  871. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  872. }
  873. namespace {
  874. // A pair of APInts that are the operands of a binary operator. We use an
  875. // aggregate rather than `std::pair` to allow RVO of the individual ints.
  876. struct APIntBinaryOperands {
  877. llvm::APInt lhs;
  878. llvm::APInt rhs;
  879. };
  880. } // namespace
  881. // Get a pair of integers at the same suitable bit-width: either their actual
  882. // width if they have a fixed width, or the smallest canonical width in which
  883. // they both fit otherwise.
  884. static auto GetIntsAtSuitableWidth(Context& context, IntId lhs_id, IntId rhs_id,
  885. IntId bit_width_id) -> APIntBinaryOperands {
  886. // Unsized operands: take the wider of the bit widths.
  887. if (!bit_width_id.has_value()) {
  888. APIntBinaryOperands result = {.lhs = context.ints().Get(lhs_id),
  889. .rhs = context.ints().Get(rhs_id)};
  890. if (result.lhs.getBitWidth() != result.rhs.getBitWidth()) {
  891. if (result.lhs.getBitWidth() > result.rhs.getBitWidth()) {
  892. result.rhs = result.rhs.sext(result.lhs.getBitWidth());
  893. } else {
  894. result.lhs = result.lhs.sext(result.rhs.getBitWidth());
  895. }
  896. }
  897. return result;
  898. }
  899. return {.lhs = context.ints().GetAtWidth(lhs_id, bit_width_id),
  900. .rhs = context.ints().GetAtWidth(rhs_id, bit_width_id)};
  901. }
  902. namespace {
  903. // The result of performing a binary int operation.
  904. struct BinaryIntOpResult {
  905. llvm::APInt result_val;
  906. bool overflow;
  907. Lex::TokenKind op_token;
  908. };
  909. } // namespace
  910. // Computes the result of a homogeneous binary (int, int) -> int operation.
  911. static auto ComputeBinaryIntOpResult(SemIR::BuiltinFunctionKind builtin_kind,
  912. const llvm::APInt& lhs_val,
  913. const llvm::APInt& rhs_val)
  914. -> BinaryIntOpResult {
  915. llvm::APInt result_val;
  916. bool overflow = false;
  917. Lex::TokenKind op_token = Lex::TokenKind::Not;
  918. switch (builtin_kind) {
  919. // Arithmetic.
  920. case SemIR::BuiltinFunctionKind::IntSAdd:
  921. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  922. op_token = Lex::TokenKind::Plus;
  923. break;
  924. case SemIR::BuiltinFunctionKind::IntSSub:
  925. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  926. op_token = Lex::TokenKind::Minus;
  927. break;
  928. case SemIR::BuiltinFunctionKind::IntSMul:
  929. result_val = lhs_val.smul_ov(rhs_val, overflow);
  930. op_token = Lex::TokenKind::Star;
  931. break;
  932. case SemIR::BuiltinFunctionKind::IntSDiv:
  933. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  934. op_token = Lex::TokenKind::Slash;
  935. break;
  936. case SemIR::BuiltinFunctionKind::IntSMod:
  937. result_val = lhs_val.srem(rhs_val);
  938. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  939. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  940. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  941. op_token = Lex::TokenKind::Percent;
  942. break;
  943. case SemIR::BuiltinFunctionKind::IntUAdd:
  944. result_val = lhs_val + rhs_val;
  945. op_token = Lex::TokenKind::Plus;
  946. break;
  947. case SemIR::BuiltinFunctionKind::IntUSub:
  948. result_val = lhs_val - rhs_val;
  949. op_token = Lex::TokenKind::Minus;
  950. break;
  951. case SemIR::BuiltinFunctionKind::IntUMul:
  952. result_val = lhs_val * rhs_val;
  953. op_token = Lex::TokenKind::Star;
  954. break;
  955. case SemIR::BuiltinFunctionKind::IntUDiv:
  956. result_val = lhs_val.udiv(rhs_val);
  957. op_token = Lex::TokenKind::Slash;
  958. break;
  959. case SemIR::BuiltinFunctionKind::IntUMod:
  960. result_val = lhs_val.urem(rhs_val);
  961. op_token = Lex::TokenKind::Percent;
  962. break;
  963. // Bitwise.
  964. case SemIR::BuiltinFunctionKind::IntAnd:
  965. result_val = lhs_val & rhs_val;
  966. op_token = Lex::TokenKind::And;
  967. break;
  968. case SemIR::BuiltinFunctionKind::IntOr:
  969. result_val = lhs_val | rhs_val;
  970. op_token = Lex::TokenKind::Pipe;
  971. break;
  972. case SemIR::BuiltinFunctionKind::IntXor:
  973. result_val = lhs_val ^ rhs_val;
  974. op_token = Lex::TokenKind::Caret;
  975. break;
  976. case SemIR::BuiltinFunctionKind::IntLeftShift:
  977. case SemIR::BuiltinFunctionKind::IntRightShift:
  978. CARBON_FATAL("Non-homogeneous operation handled separately.");
  979. default:
  980. CARBON_FATAL("Unexpected operation kind.");
  981. }
  982. return {.result_val = std::move(result_val),
  983. .overflow = overflow,
  984. .op_token = op_token};
  985. }
  986. // Performs a builtin integer bit shift operation.
  987. static auto PerformBuiltinIntShiftOp(Context& context, SemIR::LocId loc_id,
  988. SemIR::BuiltinFunctionKind builtin_kind,
  989. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  990. -> SemIR::ConstantId {
  991. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  992. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  993. auto [lhs_is_signed, lhs_bit_width_id] =
  994. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  995. llvm::APInt lhs_val =
  996. GetIntAtSuitableWidth(context, lhs.int_id, lhs_bit_width_id);
  997. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  998. if (lhs_bit_width_id.has_value() && rhs_orig_val.uge(lhs_val.getBitWidth())) {
  999. CARBON_DIAGNOSTIC(
  1000. CompileTimeShiftOutOfRange, Error,
  1001. "shift distance >= type width of {0} in `{1} {2:<<|>>} {3}`", unsigned,
  1002. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1003. context.emitter().Emit(
  1004. loc_id, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  1005. {.type = lhs.type_id, .value = lhs_val},
  1006. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1007. {.type = rhs.type_id, .value = rhs_orig_val});
  1008. // TODO: Is it useful to recover by returning 0 or -1?
  1009. return SemIR::ErrorInst::ConstantId;
  1010. }
  1011. if (rhs_orig_val.isNegative() &&
  1012. context.sem_ir().types().IsSignedInt(rhs.type_id)) {
  1013. CARBON_DIAGNOSTIC(CompileTimeShiftNegative, Error,
  1014. "shift distance negative in `{0} {1:<<|>>} {2}`",
  1015. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1016. context.emitter().Emit(
  1017. loc_id, CompileTimeShiftNegative,
  1018. {.type = lhs.type_id, .value = lhs_val},
  1019. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1020. {.type = rhs.type_id, .value = rhs_orig_val});
  1021. // TODO: Is it useful to recover by returning 0 or -1?
  1022. return SemIR::ErrorInst::ConstantId;
  1023. }
  1024. llvm::APInt result_val;
  1025. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  1026. if (!lhs_bit_width_id.has_value() && !lhs_val.isZero()) {
  1027. // Ensure we don't generate a ridiculously large integer through a bit
  1028. // shift.
  1029. auto width = rhs_orig_val.trySExtValue();
  1030. if (!width ||
  1031. *width > IntStore::MaxIntWidth - lhs_val.getSignificantBits()) {
  1032. CARBON_DIAGNOSTIC(CompileTimeUnsizedShiftOutOfRange, Error,
  1033. "shift distance of {0} would result in an "
  1034. "integer whose width is greater than the "
  1035. "maximum supported width of {1}",
  1036. TypedInt, int);
  1037. context.emitter().Emit(loc_id, CompileTimeUnsizedShiftOutOfRange,
  1038. {.type = rhs.type_id, .value = rhs_orig_val},
  1039. IntStore::MaxIntWidth);
  1040. return SemIR::ErrorInst::ConstantId;
  1041. }
  1042. lhs_val = lhs_val.sext(
  1043. IntStore::CanonicalBitWidth(lhs_val.getSignificantBits() + *width));
  1044. }
  1045. result_val =
  1046. lhs_val.shl(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1047. } else if (lhs_is_signed) {
  1048. result_val =
  1049. lhs_val.ashr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1050. } else {
  1051. CARBON_CHECK(lhs_bit_width_id.has_value(), "Logical shift on unsized int");
  1052. result_val =
  1053. lhs_val.lshr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1054. }
  1055. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  1056. std::move(result_val));
  1057. }
  1058. // Performs a homogeneous builtin binary integer -> integer operation.
  1059. static auto PerformBuiltinBinaryIntOp(Context& context, SemIR::LocId loc_id,
  1060. SemIR::BuiltinFunctionKind builtin_kind,
  1061. SemIR::InstId lhs_id,
  1062. SemIR::InstId rhs_id)
  1063. -> SemIR::ConstantId {
  1064. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1065. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1066. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  1067. auto type_id = lhs.type_id;
  1068. auto [is_signed, bit_width_id] =
  1069. context.sem_ir().types().GetIntTypeInfo(type_id);
  1070. auto [lhs_val, rhs_val] =
  1071. GetIntsAtSuitableWidth(context, lhs.int_id, rhs.int_id, bit_width_id);
  1072. // Check for division by zero.
  1073. switch (builtin_kind) {
  1074. case SemIR::BuiltinFunctionKind::IntSDiv:
  1075. case SemIR::BuiltinFunctionKind::IntSMod:
  1076. case SemIR::BuiltinFunctionKind::IntUDiv:
  1077. case SemIR::BuiltinFunctionKind::IntUMod:
  1078. if (rhs_val.isZero()) {
  1079. DiagnoseDivisionByZero(context, loc_id);
  1080. return SemIR::ErrorInst::ConstantId;
  1081. }
  1082. break;
  1083. default:
  1084. break;
  1085. }
  1086. BinaryIntOpResult result =
  1087. ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1088. if (result.overflow && !bit_width_id.has_value()) {
  1089. // Retry with a larger bit width. Most operations can only overflow by one
  1090. // bit, but signed n-bit multiplication can overflow to 2n-1 bits. We don't
  1091. // need to handle unsigned multiplication here because it's not permitted
  1092. // for unsized integers.
  1093. //
  1094. // Note that we speculatively first perform the calculation in the width of
  1095. // the wider operand: smaller operations are faster and overflow to a wider
  1096. // integer is unlikely to be needed, especially given that the width will
  1097. // have been rounded up to a multiple of 64 bits by the int store.
  1098. CARBON_CHECK(builtin_kind != SemIR::BuiltinFunctionKind::IntUMul,
  1099. "Unsigned arithmetic requires a fixed bitwidth");
  1100. int new_width =
  1101. builtin_kind == SemIR::BuiltinFunctionKind::IntSMul
  1102. ? lhs_val.getBitWidth() * 2
  1103. : IntStore::CanonicalBitWidth(lhs_val.getBitWidth() + 1);
  1104. new_width = std::min(new_width, IntStore::MaxIntWidth);
  1105. lhs_val = context.ints().GetAtWidth(lhs.int_id, new_width);
  1106. rhs_val = context.ints().GetAtWidth(rhs.int_id, new_width);
  1107. // Note that this can in theory still overflow if we limited `new_width` to
  1108. // `MaxIntWidth`. In that case we fall through to the signed overflow
  1109. // diagnostic below.
  1110. result = ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1111. CARBON_CHECK(!result.overflow || new_width == IntStore::MaxIntWidth);
  1112. }
  1113. if (result.overflow) {
  1114. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  1115. "integer overflow in calculation `{0} {1} {2}`", TypedInt,
  1116. Lex::TokenKind, TypedInt);
  1117. context.emitter().Emit(loc_id, CompileTimeIntegerOverflow,
  1118. {.type = type_id, .value = lhs_val}, result.op_token,
  1119. {.type = type_id, .value = rhs_val});
  1120. }
  1121. return MakeIntResult(context, type_id, is_signed,
  1122. std::move(result.result_val));
  1123. }
  1124. // Performs a builtin integer comparison.
  1125. static auto PerformBuiltinIntComparison(Context& context,
  1126. SemIR::BuiltinFunctionKind builtin_kind,
  1127. SemIR::InstId lhs_id,
  1128. SemIR::InstId rhs_id,
  1129. SemIR::TypeId bool_type_id)
  1130. -> SemIR::ConstantId {
  1131. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1132. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1133. llvm::APInt lhs_val = context.ints().Get(lhs.int_id);
  1134. llvm::APInt rhs_val = context.ints().Get(rhs.int_id);
  1135. bool result;
  1136. switch (builtin_kind) {
  1137. case SemIR::BuiltinFunctionKind::IntEq:
  1138. result = (lhs_val == rhs_val);
  1139. break;
  1140. case SemIR::BuiltinFunctionKind::IntNeq:
  1141. result = (lhs_val != rhs_val);
  1142. break;
  1143. case SemIR::BuiltinFunctionKind::IntLess:
  1144. result = lhs_val.slt(rhs_val);
  1145. break;
  1146. case SemIR::BuiltinFunctionKind::IntLessEq:
  1147. result = lhs_val.sle(rhs_val);
  1148. break;
  1149. case SemIR::BuiltinFunctionKind::IntGreater:
  1150. result = lhs_val.sgt(rhs_val);
  1151. break;
  1152. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  1153. result = lhs_val.sge(rhs_val);
  1154. break;
  1155. default:
  1156. CARBON_FATAL("Unexpected operation kind.");
  1157. }
  1158. return MakeBoolResult(context, bool_type_id, result);
  1159. }
  1160. // Performs a builtin unary float -> float operation.
  1161. static auto PerformBuiltinUnaryFloatOp(Context& context,
  1162. SemIR::BuiltinFunctionKind builtin_kind,
  1163. SemIR::InstId arg_id)
  1164. -> SemIR::ConstantId {
  1165. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  1166. auto op_val = context.floats().Get(op.float_id);
  1167. switch (builtin_kind) {
  1168. case SemIR::BuiltinFunctionKind::FloatNegate:
  1169. op_val.changeSign();
  1170. break;
  1171. default:
  1172. CARBON_FATAL("Unexpected builtin kind");
  1173. }
  1174. return MakeFloatResult(context, op.type_id, std::move(op_val));
  1175. }
  1176. // Performs a builtin binary float -> float operation.
  1177. static auto PerformBuiltinBinaryFloatOp(Context& context,
  1178. SemIR::BuiltinFunctionKind builtin_kind,
  1179. SemIR::InstId lhs_id,
  1180. SemIR::InstId rhs_id)
  1181. -> SemIR::ConstantId {
  1182. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1183. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1184. auto lhs_val = context.floats().Get(lhs.float_id);
  1185. auto rhs_val = context.floats().Get(rhs.float_id);
  1186. llvm::APFloat result_val(lhs_val.getSemantics());
  1187. switch (builtin_kind) {
  1188. case SemIR::BuiltinFunctionKind::FloatAdd:
  1189. result_val = lhs_val + rhs_val;
  1190. break;
  1191. case SemIR::BuiltinFunctionKind::FloatSub:
  1192. result_val = lhs_val - rhs_val;
  1193. break;
  1194. case SemIR::BuiltinFunctionKind::FloatMul:
  1195. result_val = lhs_val * rhs_val;
  1196. break;
  1197. case SemIR::BuiltinFunctionKind::FloatDiv:
  1198. result_val = lhs_val / rhs_val;
  1199. break;
  1200. default:
  1201. CARBON_FATAL("Unexpected operation kind.");
  1202. }
  1203. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  1204. }
  1205. // Performs a builtin float comparison.
  1206. static auto PerformBuiltinFloatComparison(
  1207. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1208. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  1209. -> SemIR::ConstantId {
  1210. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1211. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1212. const auto& lhs_val = context.floats().Get(lhs.float_id);
  1213. const auto& rhs_val = context.floats().Get(rhs.float_id);
  1214. bool result;
  1215. switch (builtin_kind) {
  1216. case SemIR::BuiltinFunctionKind::FloatEq:
  1217. result = (lhs_val == rhs_val);
  1218. break;
  1219. case SemIR::BuiltinFunctionKind::FloatNeq:
  1220. result = (lhs_val != rhs_val);
  1221. break;
  1222. case SemIR::BuiltinFunctionKind::FloatLess:
  1223. result = lhs_val < rhs_val;
  1224. break;
  1225. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1226. result = lhs_val <= rhs_val;
  1227. break;
  1228. case SemIR::BuiltinFunctionKind::FloatGreater:
  1229. result = lhs_val > rhs_val;
  1230. break;
  1231. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  1232. result = lhs_val >= rhs_val;
  1233. break;
  1234. default:
  1235. CARBON_FATAL("Unexpected operation kind.");
  1236. }
  1237. return MakeBoolResult(context, bool_type_id, result);
  1238. }
  1239. // Performs a builtin boolean comparison.
  1240. static auto PerformBuiltinBoolComparison(
  1241. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1242. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  1243. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1244. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1245. return MakeBoolResult(context, bool_type_id,
  1246. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1247. ? lhs == rhs
  1248. : lhs != rhs);
  1249. }
  1250. // Returns a constant for a call to a builtin function.
  1251. static auto MakeConstantForBuiltinCall(EvalContext& eval_context,
  1252. SemIR::LocId loc_id, SemIR::Call call,
  1253. SemIR::BuiltinFunctionKind builtin_kind,
  1254. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1255. Phase phase) -> SemIR::ConstantId {
  1256. auto& context = eval_context.context();
  1257. switch (builtin_kind) {
  1258. case SemIR::BuiltinFunctionKind::None:
  1259. CARBON_FATAL("Not a builtin function.");
  1260. case SemIR::BuiltinFunctionKind::NoOp: {
  1261. // Return an empty tuple value.
  1262. auto type_id = GetTupleType(eval_context.context(), {});
  1263. return MakeConstantResult(
  1264. eval_context.context(),
  1265. SemIR::TupleValue{.type_id = type_id,
  1266. .elements_id = SemIR::InstBlockId::Empty},
  1267. phase);
  1268. }
  1269. case SemIR::BuiltinFunctionKind::PrintChar:
  1270. case SemIR::BuiltinFunctionKind::PrintInt:
  1271. case SemIR::BuiltinFunctionKind::ReadChar: {
  1272. // These are runtime-only builtins.
  1273. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1274. return SemIR::ConstantId::NotConstant;
  1275. }
  1276. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1277. CARBON_CHECK(arg_ids.size() == 2);
  1278. auto lhs_facet_type_id = SemIR::FacetTypeId::None;
  1279. auto rhs_facet_type_id = SemIR::FacetTypeId::None;
  1280. for (auto [facet_type_id, type_arg_id] :
  1281. llvm::zip(std::to_array({&lhs_facet_type_id, &rhs_facet_type_id}),
  1282. context.types().GetBlockAsTypeInstIds(arg_ids))) {
  1283. if (auto facet_type =
  1284. context.insts().TryGetAs<SemIR::FacetType>(type_arg_id)) {
  1285. *facet_type_id = facet_type->facet_type_id;
  1286. } else {
  1287. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1288. "non-facet type {0} combined with `&` operator",
  1289. SemIR::TypeId);
  1290. // TODO: Find a location for the lhs or rhs specifically, instead of
  1291. // the whole thing. If that's not possible we can change the text to
  1292. // say if it's referring to the left or the right side for the error.
  1293. // The `arg_id` instruction has no location in it for some reason.
  1294. context.emitter().Emit(
  1295. loc_id, FacetTypeRequiredForTypeAndOperator,
  1296. context.types().GetTypeIdForTypeInstId(type_arg_id));
  1297. }
  1298. }
  1299. // Allow errors to be diagnosed for both sides of the operator before
  1300. // returning here if any error occurred on either side.
  1301. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1302. return SemIR::ErrorInst::ConstantId;
  1303. }
  1304. // Reuse one of the argument instructions if nothing has changed.
  1305. if (lhs_facet_type_id == rhs_facet_type_id) {
  1306. return context.types().GetConstantId(
  1307. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1308. }
  1309. auto info = SemIR::FacetTypeInfo::Combine(
  1310. context.facet_types().Get(lhs_facet_type_id),
  1311. context.facet_types().Get(rhs_facet_type_id));
  1312. info.Canonicalize();
  1313. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1314. }
  1315. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1316. return context.constant_values().Get(SemIR::IntLiteralType::InstId);
  1317. }
  1318. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1319. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Signed,
  1320. arg_ids[0], phase);
  1321. }
  1322. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1323. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Unsigned,
  1324. arg_ids[0], phase);
  1325. }
  1326. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1327. // TODO: Support a symbolic constant width.
  1328. if (phase != Phase::Concrete) {
  1329. break;
  1330. }
  1331. if (!ValidateFloatBitWidth(context, loc_id, arg_ids[0])) {
  1332. return SemIR::ErrorInst::ConstantId;
  1333. }
  1334. return context.constant_values().Get(SemIR::LegacyFloatType::InstId);
  1335. }
  1336. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1337. return context.constant_values().Get(SemIR::BoolType::InstId);
  1338. }
  1339. // Integer conversions.
  1340. case SemIR::BuiltinFunctionKind::IntConvert: {
  1341. if (phase != Phase::Concrete) {
  1342. return MakeConstantResult(context, call, phase);
  1343. }
  1344. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1345. }
  1346. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1347. if (phase != Phase::Concrete) {
  1348. return MakeConstantResult(context, call, phase);
  1349. }
  1350. return PerformCheckedIntConvert(context, loc_id, arg_ids[0],
  1351. call.type_id);
  1352. }
  1353. // Unary integer -> integer operations.
  1354. case SemIR::BuiltinFunctionKind::IntSNegate:
  1355. case SemIR::BuiltinFunctionKind::IntUNegate:
  1356. case SemIR::BuiltinFunctionKind::IntComplement: {
  1357. if (phase != Phase::Concrete) {
  1358. break;
  1359. }
  1360. return PerformBuiltinUnaryIntOp(context, loc_id, builtin_kind,
  1361. arg_ids[0]);
  1362. }
  1363. // Homogeneous binary integer -> integer operations.
  1364. case SemIR::BuiltinFunctionKind::IntSAdd:
  1365. case SemIR::BuiltinFunctionKind::IntSSub:
  1366. case SemIR::BuiltinFunctionKind::IntSMul:
  1367. case SemIR::BuiltinFunctionKind::IntSDiv:
  1368. case SemIR::BuiltinFunctionKind::IntSMod:
  1369. case SemIR::BuiltinFunctionKind::IntUAdd:
  1370. case SemIR::BuiltinFunctionKind::IntUSub:
  1371. case SemIR::BuiltinFunctionKind::IntUMul:
  1372. case SemIR::BuiltinFunctionKind::IntUDiv:
  1373. case SemIR::BuiltinFunctionKind::IntUMod:
  1374. case SemIR::BuiltinFunctionKind::IntAnd:
  1375. case SemIR::BuiltinFunctionKind::IntOr:
  1376. case SemIR::BuiltinFunctionKind::IntXor: {
  1377. if (phase != Phase::Concrete) {
  1378. break;
  1379. }
  1380. return PerformBuiltinBinaryIntOp(context, loc_id, builtin_kind,
  1381. arg_ids[0], arg_ids[1]);
  1382. }
  1383. // Bit shift operations.
  1384. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1385. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1386. if (phase != Phase::Concrete) {
  1387. break;
  1388. }
  1389. return PerformBuiltinIntShiftOp(context, loc_id, builtin_kind, arg_ids[0],
  1390. arg_ids[1]);
  1391. }
  1392. // Integer comparisons.
  1393. case SemIR::BuiltinFunctionKind::IntEq:
  1394. case SemIR::BuiltinFunctionKind::IntNeq:
  1395. case SemIR::BuiltinFunctionKind::IntLess:
  1396. case SemIR::BuiltinFunctionKind::IntLessEq:
  1397. case SemIR::BuiltinFunctionKind::IntGreater:
  1398. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1399. if (phase != Phase::Concrete) {
  1400. break;
  1401. }
  1402. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1403. arg_ids[1], call.type_id);
  1404. }
  1405. // Unary float -> float operations.
  1406. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1407. if (phase != Phase::Concrete) {
  1408. break;
  1409. }
  1410. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1411. }
  1412. // Binary float -> float operations.
  1413. case SemIR::BuiltinFunctionKind::FloatAdd:
  1414. case SemIR::BuiltinFunctionKind::FloatSub:
  1415. case SemIR::BuiltinFunctionKind::FloatMul:
  1416. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1417. if (phase != Phase::Concrete) {
  1418. break;
  1419. }
  1420. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1421. arg_ids[1]);
  1422. }
  1423. // Float comparisons.
  1424. case SemIR::BuiltinFunctionKind::FloatEq:
  1425. case SemIR::BuiltinFunctionKind::FloatNeq:
  1426. case SemIR::BuiltinFunctionKind::FloatLess:
  1427. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1428. case SemIR::BuiltinFunctionKind::FloatGreater:
  1429. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1430. if (phase != Phase::Concrete) {
  1431. break;
  1432. }
  1433. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1434. arg_ids[1], call.type_id);
  1435. }
  1436. // Bool comparisons.
  1437. case SemIR::BuiltinFunctionKind::BoolEq:
  1438. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1439. if (phase != Phase::Concrete) {
  1440. break;
  1441. }
  1442. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1443. arg_ids[1], call.type_id);
  1444. }
  1445. }
  1446. return SemIR::ConstantId::NotConstant;
  1447. }
  1448. // Makes a constant for a call instruction.
  1449. static auto MakeConstantForCall(EvalContext& eval_context, SemIR::LocId loc_id,
  1450. SemIR::Call call) -> SemIR::ConstantId {
  1451. Phase phase = Phase::Concrete;
  1452. // A call with an invalid argument list is used to represent an erroneous
  1453. // call.
  1454. //
  1455. // TODO: Use a better representation for this.
  1456. if (call.args_id == SemIR::InstBlockId::None) {
  1457. return SemIR::ErrorInst::ConstantId;
  1458. }
  1459. // Find the constant value of the callee.
  1460. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1461. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1462. auto callee_function =
  1463. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1464. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1465. if (callee_function.function_id.has_value()) {
  1466. // Calls to builtins might be constant.
  1467. builtin_kind = eval_context.functions()
  1468. .Get(callee_function.function_id)
  1469. .builtin_function_kind;
  1470. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1471. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1472. // functions as producing constants.
  1473. return SemIR::ConstantId::NotConstant;
  1474. }
  1475. } else {
  1476. // Calls to non-functions, such as calls to generic entity names, might be
  1477. // constant.
  1478. }
  1479. // Find the argument values and the return type.
  1480. bool has_constant_operands =
  1481. has_constant_callee &&
  1482. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  1483. &phase) &&
  1484. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1485. &phase);
  1486. if (phase == Phase::UnknownDueToError) {
  1487. return SemIR::ErrorInst::ConstantId;
  1488. }
  1489. // If any operand of the call is non-constant, the call is non-constant.
  1490. // TODO: Some builtin calls might allow some operands to be non-constant.
  1491. if (!has_constant_operands) {
  1492. if (builtin_kind.IsCompTimeOnly(
  1493. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1494. call.type_id)) {
  1495. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1496. "non-constant call to compile-time-only function");
  1497. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1498. "compile-time-only function declared here");
  1499. eval_context.emitter()
  1500. .Build(loc_id, NonConstantCallToCompTimeOnlyFunction)
  1501. .Note(eval_context.functions()
  1502. .Get(callee_function.function_id)
  1503. .latest_decl_id(),
  1504. CompTimeOnlyFunctionHere)
  1505. .Emit();
  1506. }
  1507. return SemIR::ConstantId::NotConstant;
  1508. }
  1509. // Handle calls to builtins.
  1510. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1511. return MakeConstantForBuiltinCall(
  1512. eval_context, loc_id, call, builtin_kind,
  1513. eval_context.inst_blocks().Get(call.args_id), phase);
  1514. }
  1515. return SemIR::ConstantId::NotConstant;
  1516. }
  1517. // Given an instruction, compute its phase based on its operands.
  1518. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1519. EvalContext eval_context(&context, SemIR::InstId::None);
  1520. auto phase = GetPhase(context.constant_values(),
  1521. context.types().GetConstantId(inst.type_id()));
  1522. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  1523. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  1524. CARBON_CHECK(IsConstant(phase));
  1525. return phase;
  1526. }
  1527. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1528. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1529. static auto ConvertEvalResultToConstantId(Context& context,
  1530. ConstantEvalResult result,
  1531. Phase orig_phase)
  1532. -> SemIR::ConstantId {
  1533. if (result.is_new()) {
  1534. return MakeConstantResult(
  1535. context, result.new_inst(),
  1536. result.same_phase_as_inst()
  1537. ? orig_phase
  1538. : ComputeInstPhase(context, result.new_inst()));
  1539. }
  1540. return result.existing();
  1541. }
  1542. // Evaluates an instruction of a known type in an evaluation context. The
  1543. // default behavior of this function depends on the constant kind of the
  1544. // instruction:
  1545. //
  1546. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  1547. // - InstConstantKind::Indirect, SymbolicOnly, Conditional: evaluates all the
  1548. // operands of the instruction, and calls `EvalConstantInst` to evaluate the
  1549. // resulting constant instruction.
  1550. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  1551. // the instruction, and produces the resulting constant instruction as the
  1552. // result.
  1553. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  1554. // constant.
  1555. //
  1556. // Returns an error constant ID if any of the nested evaluations fail, and
  1557. // returns NotConstant if any of the nested evaluations is non-constant.
  1558. //
  1559. // This template is explicitly specialized for instructions that need special
  1560. // handling.
  1561. template <typename InstT>
  1562. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  1563. SemIR::Inst inst) -> SemIR::ConstantId {
  1564. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  1565. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  1566. return SemIR::ConstantId::NotConstant;
  1567. } else if constexpr (ConstantKind == SemIR::InstConstantKind::Unique) {
  1568. CARBON_CHECK(inst_id.has_value());
  1569. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  1570. } else {
  1571. // Build a constant instruction by replacing each non-constant operand with
  1572. // its constant value.
  1573. Phase phase = Phase::Concrete;
  1574. if (!ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  1575. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  1576. CARBON_CHECK(phase == Phase::UnknownDueToError,
  1577. "{0} should always be constant", InstT::Kind);
  1578. }
  1579. return MakeNonConstantResult(phase);
  1580. }
  1581. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  1582. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  1583. return MakeConstantResult(eval_context.context(), inst, phase);
  1584. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  1585. auto result_inst_id = PerformDelayedAction(
  1586. eval_context.context(), eval_context.insts().GetLocId(inst_id),
  1587. inst.As<InstT>());
  1588. if (result_inst_id.has_value()) {
  1589. // The result is an instruction.
  1590. return MakeConstantResult(
  1591. eval_context.context(),
  1592. SemIR::InstValue{.type_id = SemIR::InstType::TypeId,
  1593. .inst_id = result_inst_id},
  1594. Phase::Concrete);
  1595. }
  1596. // Couldn't perform the action because it's still dependent.
  1597. return MakeConstantResult(eval_context.context(), inst,
  1598. Phase::TemplateSymbolic);
  1599. } else if constexpr (InstT::Kind.constant_needs_inst_id() !=
  1600. SemIR::InstConstantNeedsInstIdKind::No) {
  1601. CARBON_CHECK(inst_id.has_value());
  1602. return ConvertEvalResultToConstantId(
  1603. eval_context.context(),
  1604. EvalConstantInst(eval_context.context(), inst_id, inst.As<InstT>()),
  1605. phase);
  1606. } else {
  1607. return ConvertEvalResultToConstantId(
  1608. eval_context.context(),
  1609. EvalConstantInst(eval_context.context(), inst.As<InstT>()), phase);
  1610. }
  1611. }
  1612. }
  1613. // Specialize evaluation for array indexing because we want to check the index
  1614. // expression even if the array expression is non-constant.
  1615. template <>
  1616. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  1617. SemIR::InstId /*inst_id*/,
  1618. SemIR::Inst inst)
  1619. -> SemIR::ConstantId {
  1620. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  1621. }
  1622. // Specialize evaluation for function calls because we want to check the callee
  1623. // expression even if an argument expression is non-constant, and because we
  1624. // will eventually want to perform control flow handling here.
  1625. template <>
  1626. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  1627. SemIR::InstId inst_id, SemIR::Inst inst)
  1628. -> SemIR::ConstantId {
  1629. return MakeConstantForCall(eval_context,
  1630. eval_context.GetDiagnosticLoc(inst_id),
  1631. inst.As<SemIR::Call>());
  1632. }
  1633. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  1634. // `import_ref.cpp`, not by us.
  1635. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  1636. // call this.
  1637. template <>
  1638. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  1639. SemIR::InstId /*inst_id*/,
  1640. SemIR::Inst /*inst*/)
  1641. -> SemIR::ConstantId {
  1642. return SemIR::ConstantId::NotConstant;
  1643. }
  1644. // Symbolic bindings are a special case because they can reach into the eval
  1645. // context and produce a context-specific value.
  1646. template <>
  1647. auto TryEvalTypedInst<SemIR::BindSymbolicName>(EvalContext& eval_context,
  1648. SemIR::InstId /*inst_id*/,
  1649. SemIR::Inst inst)
  1650. -> SemIR::ConstantId {
  1651. auto bind = inst.As<SemIR::BindSymbolicName>();
  1652. // If we know which specific we're evaluating within and this is an argument
  1653. // of that specific, its constant value is the corresponding argument value.
  1654. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  1655. if (bind_name.bind_index().has_value()) {
  1656. if (auto value =
  1657. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  1658. value.has_value()) {
  1659. return value;
  1660. }
  1661. }
  1662. // The constant form of a symbolic binding is an idealized form of the
  1663. // original, with no equivalent value.
  1664. Phase phase = Phase::Concrete;
  1665. bind.value_id = SemIR::InstId::None;
  1666. if (!ReplaceFieldWithConstantValue(
  1667. eval_context, &bind, &SemIR::BindSymbolicName::type_id, &phase) ||
  1668. !ReplaceFieldWithConstantValue(eval_context, &bind,
  1669. &SemIR::BindSymbolicName::entity_name_id,
  1670. &phase)) {
  1671. return MakeNonConstantResult(phase);
  1672. }
  1673. return MakeConstantResult(eval_context.context(), bind, phase);
  1674. }
  1675. static auto IsPeriodSelf(EvalContext& eval_context, SemIR::ConstantId const_id)
  1676. -> bool {
  1677. // This also rejects the singleton Error value as it's concrete.
  1678. if (!const_id.is_symbolic()) {
  1679. return false;
  1680. }
  1681. const auto& symbolic =
  1682. eval_context.constant_values().GetSymbolicConstant(const_id);
  1683. // Fast early reject before doing more expensive operations.
  1684. if (symbolic.dependence != SemIR::ConstantDependence::PeriodSelf) {
  1685. return false;
  1686. }
  1687. auto inst_id = symbolic.inst_id;
  1688. // Unwrap the `FacetAccessType` instruction, which we get when the `.Self` is
  1689. // converted to `type`.
  1690. if (auto facet_access_type =
  1691. eval_context.insts().TryGetAs<SemIR::FacetAccessType>(inst_id)) {
  1692. inst_id = facet_access_type->facet_value_inst_id;
  1693. }
  1694. if (auto bind_symbolic_name =
  1695. eval_context.insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  1696. const auto& bind_name =
  1697. eval_context.entity_names().Get(bind_symbolic_name->entity_name_id);
  1698. return bind_name.name_id == SemIR::NameId::PeriodSelf;
  1699. }
  1700. return false;
  1701. }
  1702. // TODO: Convert this to an EvalConstantInst instruction. This will require
  1703. // providing a `GetConstantValue` overload for a requirement block.
  1704. template <>
  1705. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  1706. SemIR::InstId /*inst_id*/,
  1707. SemIR::Inst inst) -> SemIR::ConstantId {
  1708. auto typed_inst = inst.As<SemIR::WhereExpr>();
  1709. Phase phase = Phase::Concrete;
  1710. SemIR::TypeId base_facet_type_id =
  1711. eval_context.insts().Get(typed_inst.period_self_id).type_id();
  1712. SemIR::Inst base_facet_inst =
  1713. eval_context.GetConstantValueAsInst(base_facet_type_id);
  1714. SemIR::FacetTypeInfo info = {.other_requirements = false};
  1715. // `where` provides that the base facet is an error, `type`, or a facet
  1716. // type.
  1717. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1718. info = GetConstantFacetTypeInfo(eval_context, facet_type->facet_type_id,
  1719. &phase);
  1720. } else if (base_facet_type_id == SemIR::ErrorInst::TypeId) {
  1721. return SemIR::ErrorInst::ConstantId;
  1722. } else {
  1723. CARBON_CHECK(base_facet_type_id == SemIR::TypeType::TypeId,
  1724. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1725. base_facet_inst);
  1726. }
  1727. if (typed_inst.requirements_id.has_value()) {
  1728. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  1729. for (auto inst_id : insts) {
  1730. if (auto rewrite =
  1731. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  1732. inst_id)) {
  1733. // `where` requirements using `.Self` should not be considered
  1734. // symbolic.
  1735. auto lhs_id = GetConstantValueIgnoringPeriodSelf(
  1736. eval_context, rewrite->lhs_id, &phase);
  1737. auto rhs_id = GetConstantValueIgnoringPeriodSelf(
  1738. eval_context, rewrite->rhs_id, &phase);
  1739. info.rewrite_constraints.push_back(
  1740. {.lhs_id = lhs_id, .rhs_id = rhs_id});
  1741. } else if (auto impls =
  1742. eval_context.insts().TryGetAs<SemIR::RequirementImpls>(
  1743. inst_id)) {
  1744. SemIR::ConstantId lhs = eval_context.GetConstantValue(impls->lhs_id);
  1745. SemIR::ConstantId rhs = eval_context.GetConstantValue(impls->rhs_id);
  1746. if (rhs != SemIR::ErrorInst::ConstantId &&
  1747. IsPeriodSelf(eval_context, lhs)) {
  1748. auto rhs_inst_id = eval_context.constant_values().GetInstId(rhs);
  1749. if (rhs_inst_id == SemIR::TypeType::InstId) {
  1750. // `.Self impls type` -> nothing to do.
  1751. } else {
  1752. auto facet_type =
  1753. eval_context.insts().GetAs<SemIR::FacetType>(rhs_inst_id);
  1754. SemIR::FacetTypeInfo more_info = GetConstantFacetTypeInfo(
  1755. eval_context, facet_type.facet_type_id, &phase);
  1756. // The way to prevent lookup into the interface requirements of a
  1757. // facet type is to put it to the right of a `.Self impls`, which we
  1758. // accomplish by putting them into `self_impls_constraints`.
  1759. llvm::append_range(info.self_impls_constraints,
  1760. more_info.extend_constraints);
  1761. llvm::append_range(info.self_impls_constraints,
  1762. more_info.self_impls_constraints);
  1763. // Other requirements are copied in.
  1764. llvm::append_range(info.rewrite_constraints,
  1765. more_info.rewrite_constraints);
  1766. info.other_requirements |= more_info.other_requirements;
  1767. }
  1768. } else {
  1769. // TODO: Handle `impls` constraints beyond `.Self impls`.
  1770. info.other_requirements = true;
  1771. }
  1772. } else {
  1773. // TODO: Handle other requirements
  1774. info.other_requirements = true;
  1775. }
  1776. }
  1777. }
  1778. info.Canonicalize();
  1779. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1780. }
  1781. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1782. static auto TryEvalInstInContext(EvalContext& eval_context,
  1783. SemIR::InstId inst_id, SemIR::Inst inst)
  1784. -> SemIR::ConstantId {
  1785. using EvalInstFn =
  1786. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  1787. ->SemIR::ConstantId;
  1788. static constexpr EvalInstFn* EvalInstFns[] = {
  1789. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  1790. #include "toolchain/sem_ir/inst_kind.def"
  1791. };
  1792. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  1793. inst_id, inst);
  1794. }
  1795. auto TryEvalInstUnsafe(Context& context, SemIR::InstId inst_id,
  1796. SemIR::Inst inst) -> SemIR::ConstantId {
  1797. EvalContext eval_context(&context, inst_id);
  1798. return TryEvalInstInContext(eval_context, inst_id, inst);
  1799. }
  1800. auto TryEvalBlockForSpecific(Context& context, SemIR::LocId loc_id,
  1801. SemIR::SpecificId specific_id,
  1802. SemIR::GenericInstIndex::Region region)
  1803. -> SemIR::InstBlockId {
  1804. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1805. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1806. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1807. llvm::SmallVector<SemIR::InstId> result;
  1808. result.resize(eval_block.size(), SemIR::InstId::None);
  1809. EvalContext eval_context(&context, loc_id, specific_id,
  1810. SpecificEvalInfo{
  1811. .region = region,
  1812. .values = result,
  1813. });
  1814. Diagnostics::AnnotationScope annotate_diagnostics(
  1815. &context.emitter(), [&](auto& builder) {
  1816. CARBON_DIAGNOSTIC(ResolvingSpecificHere, Note, "in {0} used here",
  1817. SemIR::SpecificId);
  1818. builder.Note(loc_id, ResolvingSpecificHere, specific_id);
  1819. });
  1820. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1821. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1822. context.insts().Get(inst_id));
  1823. result[i] = context.constant_values().GetInstId(const_id);
  1824. CARBON_CHECK(result[i].has_value(), "Failed to evaluate {0} in eval block",
  1825. context.insts().Get(inst_id));
  1826. }
  1827. return context.inst_blocks().Add(result);
  1828. }
  1829. } // namespace Carbon::Check