eval.cpp 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458
  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 "common/raw_string_ostream.h"
  10. #include "llvm/Support/ConvertUTF.h"
  11. #include "toolchain/base/canonical_value_store.h"
  12. #include "toolchain/base/kind_switch.h"
  13. #include "toolchain/check/action.h"
  14. #include "toolchain/check/diagnostic_helpers.h"
  15. #include "toolchain/check/eval_inst.h"
  16. #include "toolchain/check/facet_type.h"
  17. #include "toolchain/check/generic.h"
  18. #include "toolchain/check/import_ref.h"
  19. #include "toolchain/check/name_lookup.h"
  20. #include "toolchain/check/type.h"
  21. #include "toolchain/check/type_completion.h"
  22. #include "toolchain/diagnostics/diagnostic.h"
  23. #include "toolchain/diagnostics/diagnostic_emitter.h"
  24. #include "toolchain/diagnostics/format_providers.h"
  25. #include "toolchain/sem_ir/builtin_function_kind.h"
  26. #include "toolchain/sem_ir/constant.h"
  27. #include "toolchain/sem_ir/facet_type_info.h"
  28. #include "toolchain/sem_ir/function.h"
  29. #include "toolchain/sem_ir/generic.h"
  30. #include "toolchain/sem_ir/id_kind.h"
  31. #include "toolchain/sem_ir/ids.h"
  32. #include "toolchain/sem_ir/impl.h"
  33. #include "toolchain/sem_ir/inst_categories.h"
  34. #include "toolchain/sem_ir/inst_kind.h"
  35. #include "toolchain/sem_ir/typed_insts.h"
  36. namespace Carbon::Check {
  37. namespace {
  38. // Information about an eval block of a specific that we are currently building.
  39. struct SpecificEvalInfo {
  40. // The region within the specific whose eval block we are building.
  41. SemIR::GenericInstIndex::Region region;
  42. // The work-in-progress contents of the eval block.
  43. llvm::ArrayRef<SemIR::InstId> values;
  44. };
  45. // Information about the context within which we are performing evaluation.
  46. // `context` must not be null.
  47. class EvalContext {
  48. public:
  49. explicit EvalContext(
  50. Context* context, SemIR::LocId fallback_loc_id,
  51. SemIR::SpecificId specific_id = SemIR::SpecificId::None,
  52. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  53. : context_(context),
  54. fallback_loc_id_(fallback_loc_id),
  55. specific_id_(specific_id),
  56. specific_eval_info_(specific_eval_info) {}
  57. // Gets the location to use for diagnostics if a better location is
  58. // unavailable.
  59. // TODO: This is also sometimes unavailable.
  60. auto fallback_loc_id() const -> SemIR::LocId { return fallback_loc_id_; }
  61. // Returns a location to use to point at an instruction in a diagnostic, given
  62. // a list of instructions that might have an attached location. This is the
  63. // location of the first instruction in the list that has a location if there
  64. // is one, and otherwise the fallback location.
  65. auto GetDiagnosticLoc(llvm::ArrayRef<SemIR::InstId> inst_ids)
  66. -> SemIR::LocId {
  67. for (auto inst_id : inst_ids) {
  68. if (inst_id.has_value()) {
  69. auto loc_id = context_->insts().GetCanonicalLocId(inst_id);
  70. if (loc_id.has_value()) {
  71. return loc_id;
  72. }
  73. }
  74. }
  75. return fallback_loc_id_;
  76. }
  77. // Gets the value of the specified compile-time binding in this context.
  78. // Returns `None` if the value is not fixed in this context.
  79. auto GetCompileTimeAcquireValue(SemIR::CompileTimeBindIndex bind_index)
  80. -> SemIR::ConstantId {
  81. if (!bind_index.has_value() || !specific_id_.has_value()) {
  82. return SemIR::ConstantId::None;
  83. }
  84. const auto& specific = specifics().Get(specific_id_);
  85. auto args = inst_blocks().Get(specific.args_id);
  86. // Bindings past the ones with known arguments can appear as local
  87. // bindings of entities declared within this generic.
  88. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  89. return SemIR::ConstantId::None;
  90. }
  91. return constant_values().Get(args[bind_index.index]);
  92. }
  93. // Given information about a symbolic constant, determine its value in the
  94. // currently-being-evaluated eval block, if it refers to that eval block. If
  95. // we can't find a value in this way, returns `None`.
  96. auto GetInEvaluatedSpecific(const SemIR::SymbolicConstant& symbolic_info)
  97. -> SemIR::ConstantId {
  98. if (!specific_eval_info_ || !symbolic_info.index.has_value()) {
  99. return SemIR::ConstantId::None;
  100. }
  101. CARBON_CHECK(
  102. symbolic_info.generic_id == specifics().Get(specific_id_).generic_id,
  103. "Instruction has constant operand in wrong generic");
  104. if (symbolic_info.index.region() != specific_eval_info_->region) {
  105. return SemIR::ConstantId::None;
  106. }
  107. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  108. CARBON_CHECK(inst_id.has_value(),
  109. "Forward reference in eval block: index {0} referenced "
  110. "before evaluation",
  111. symbolic_info.index.index());
  112. return constant_values().Get(inst_id);
  113. }
  114. // Gets the constant value of the specified instruction in this context.
  115. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  116. auto const_id = constant_values().GetAttached(inst_id);
  117. if (!const_id.is_symbolic()) {
  118. return const_id;
  119. }
  120. // While resolving a specific, map from previous instructions in the eval
  121. // block into their evaluated values. These values won't be present on the
  122. // specific itself yet, so `GetConstantValueInSpecific` won't be able to
  123. // find them.
  124. const auto& symbolic_info = constant_values().GetSymbolicConstant(const_id);
  125. if (auto eval_block_const_id = GetInEvaluatedSpecific(symbolic_info);
  126. eval_block_const_id.has_value()) {
  127. return eval_block_const_id;
  128. }
  129. return GetConstantValueInSpecific(sem_ir(), specific_id_, inst_id);
  130. }
  131. // Gets the type of the specified instruction in this context.
  132. auto GetTypeOfInst(SemIR::InstId inst_id) -> SemIR::TypeId {
  133. auto type_id = insts().GetAttachedType(inst_id);
  134. if (!type_id.is_symbolic()) {
  135. return type_id;
  136. }
  137. // While resolving a specific, map from previous instructions in the eval
  138. // block into their evaluated values. These values won't be present on the
  139. // specific itself yet, so `GetTypeOfInstInSpecific` won't be able to
  140. // find them.
  141. const auto& symbolic_info =
  142. constant_values().GetSymbolicConstant(types().GetConstantId(type_id));
  143. if (auto eval_block_const_id = GetInEvaluatedSpecific(symbolic_info);
  144. eval_block_const_id.has_value()) {
  145. return types().GetTypeIdForTypeConstantId(eval_block_const_id);
  146. }
  147. return GetTypeOfInstInSpecific(sem_ir(), specific_id_, inst_id);
  148. }
  149. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  150. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  151. auto entity_names() -> SemIR::EntityNameStore& {
  152. return sem_ir().entity_names();
  153. }
  154. auto functions() -> const SemIR::FunctionStore& {
  155. return sem_ir().functions();
  156. }
  157. auto classes() -> const SemIR::ClassStore& { return sem_ir().classes(); }
  158. auto interfaces() -> const SemIR::InterfaceStore& {
  159. return sem_ir().interfaces();
  160. }
  161. auto specific_interfaces() -> SemIR::SpecificInterfaceStore& {
  162. return sem_ir().specific_interfaces();
  163. }
  164. auto facet_types() -> SemIR::FacetTypeInfoStore& {
  165. return sem_ir().facet_types();
  166. }
  167. auto generics() -> const SemIR::GenericStore& { return sem_ir().generics(); }
  168. auto specifics() -> const SemIR::SpecificStore& {
  169. return sem_ir().specifics();
  170. }
  171. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  172. auto inst_blocks() -> SemIR::InstBlockStore& {
  173. return sem_ir().inst_blocks();
  174. }
  175. // Gets the constant value store. Note that this does not provide the constant
  176. // values that should be used from this evaluation context, and so should be
  177. // used with caution.
  178. auto constant_values() -> const SemIR::ConstantValueStore& {
  179. return sem_ir().constant_values();
  180. }
  181. // Gets the types store. Note that this does not provide the type values that
  182. // should be used from this evaluation context, and so should be used with
  183. // caution.
  184. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  185. auto context() -> Context& { return *context_; }
  186. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  187. auto emitter() -> DiagnosticEmitterBase& { return context().emitter(); }
  188. private:
  189. // The type-checking context in which we're performing evaluation.
  190. Context* context_;
  191. // The location to use for diagnostics when a better location isn't available.
  192. SemIR::LocId fallback_loc_id_;
  193. // The specific that we are evaluating within.
  194. SemIR::SpecificId specific_id_;
  195. // If we are currently evaluating an eval block for `specific_id_`,
  196. // information about that evaluation.
  197. std::optional<SpecificEvalInfo> specific_eval_info_;
  198. };
  199. } // namespace
  200. namespace {
  201. // The evaluation phase for an expression, computed by evaluation. These are
  202. // ordered so that the phase of an expression is the numerically highest phase
  203. // of its constituent evaluations. Note that an expression with any runtime
  204. // component is known to have Runtime phase even if it involves an evaluation
  205. // with UnknownDueToError phase.
  206. enum class Phase : uint8_t {
  207. // Value could be entirely and concretely computed.
  208. Concrete,
  209. // Evaluation phase is symbolic because the expression involves specifically a
  210. // reference to `.Self`.
  211. PeriodSelfSymbolic,
  212. // Evaluation phase is symbolic because the expression involves a reference to
  213. // a non-template symbolic binding other than `.Self`.
  214. CheckedSymbolic,
  215. // Evaluation phase is symbolic because the expression involves a reference to
  216. // a template parameter, or otherwise depends on something template dependent.
  217. // The expression might also reference non-template symbolic bindings.
  218. TemplateSymbolic,
  219. // The evaluation phase is unknown because evaluation encountered an
  220. // already-diagnosed semantic or syntax error. This is treated as being
  221. // potentially constant, but with an unknown phase.
  222. UnknownDueToError,
  223. // The expression has runtime phase because of a non-constant subexpression.
  224. Runtime,
  225. };
  226. } // namespace
  227. static auto IsConstantOrError(Phase phase) -> bool {
  228. return phase != Phase::Runtime;
  229. }
  230. // Gets the phase in which the value of a constant will become available.
  231. static auto GetPhase(const SemIR::ConstantValueStore& constant_values,
  232. SemIR::ConstantId constant_id) -> Phase {
  233. if (!constant_id.is_constant()) {
  234. return Phase::Runtime;
  235. } else if (constant_id == SemIR::ErrorInst::ConstantId) {
  236. return Phase::UnknownDueToError;
  237. }
  238. switch (constant_values.GetDependence(constant_id)) {
  239. case SemIR::ConstantDependence::None:
  240. return Phase::Concrete;
  241. case SemIR::ConstantDependence::PeriodSelf:
  242. return Phase::PeriodSelfSymbolic;
  243. case SemIR::ConstantDependence::Checked:
  244. return Phase::CheckedSymbolic;
  245. case SemIR::ConstantDependence::Template:
  246. return Phase::TemplateSymbolic;
  247. }
  248. }
  249. // Returns the later of two phases.
  250. static auto LatestPhase(Phase a, Phase b) -> Phase {
  251. return static_cast<Phase>(
  252. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  253. }
  254. // Forms a `constant_id` describing a given evaluation result.
  255. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  256. -> SemIR::ConstantId {
  257. switch (phase) {
  258. case Phase::Concrete:
  259. return context.constants().GetOrAdd(inst,
  260. SemIR::ConstantDependence::None);
  261. case Phase::PeriodSelfSymbolic:
  262. return context.constants().GetOrAdd(
  263. inst, SemIR::ConstantDependence::PeriodSelf);
  264. case Phase::CheckedSymbolic:
  265. return context.constants().GetOrAdd(inst,
  266. SemIR::ConstantDependence::Checked);
  267. case Phase::TemplateSymbolic:
  268. return context.constants().GetOrAdd(inst,
  269. SemIR::ConstantDependence::Template);
  270. case Phase::UnknownDueToError:
  271. return SemIR::ErrorInst::ConstantId;
  272. case Phase::Runtime:
  273. return SemIR::ConstantId::NotConstant;
  274. }
  275. }
  276. // Forms a `constant_id` describing why an evaluation was not constant.
  277. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  278. return phase == Phase::UnknownDueToError ? SemIR::ErrorInst::ConstantId
  279. : SemIR::ConstantId::NotConstant;
  280. }
  281. // Converts a bool value into a ConstantId.
  282. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  283. bool result) -> SemIR::ConstantId {
  284. return MakeConstantResult(
  285. context,
  286. SemIR::BoolLiteral{.type_id = bool_type_id,
  287. .value = SemIR::BoolValue::From(result)},
  288. Phase::Concrete);
  289. }
  290. // Converts an APInt value into a ConstantId.
  291. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  292. bool is_signed, llvm::APInt value)
  293. -> SemIR::ConstantId {
  294. CARBON_CHECK(is_signed == context.types().IsSignedInt(type_id));
  295. auto result = is_signed ? context.ints().AddSigned(std::move(value))
  296. : context.ints().AddUnsigned(std::move(value));
  297. return MakeConstantResult(
  298. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  299. Phase::Concrete);
  300. }
  301. // Converts an APFloat value into a ConstantId.
  302. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  303. llvm::APFloat value) -> SemIR::ConstantId {
  304. auto result = context.floats().Add(std::move(value));
  305. return MakeConstantResult(
  306. context, SemIR::FloatValue{.type_id = type_id, .float_id = result},
  307. Phase::Concrete);
  308. }
  309. // Creates a FacetType constant.
  310. static auto MakeFacetTypeResult(Context& context,
  311. const SemIR::FacetTypeInfo& info, Phase phase)
  312. -> SemIR::ConstantId {
  313. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  314. return MakeConstantResult(context,
  315. SemIR::FacetType{.type_id = SemIR::TypeType::TypeId,
  316. .facet_type_id = facet_type_id},
  317. phase);
  318. }
  319. // `GetConstantValue` checks to see whether the provided ID describes a value
  320. // with constant phase, and if so, returns the corresponding constant value.
  321. // Overloads are provided for different kinds of ID. `RequireConstantValue` does
  322. // the same, but produces an error diagnostic if the input is not constant.
  323. // AbsoluteInstId can not have its values substituted, so this overload is
  324. // deleted. This prevents conversion to InstId.
  325. static auto GetConstantValue(EvalContext& eval_context,
  326. SemIR::AbsoluteInstId inst_id, Phase* phase)
  327. -> SemIR::InstId = delete;
  328. // If the given instruction is constant, returns its constant value.
  329. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  330. Phase* phase) -> SemIR::InstId {
  331. if (!inst_id.has_value()) {
  332. return SemIR::InstId::None;
  333. }
  334. auto const_id = eval_context.GetConstantValue(inst_id);
  335. *phase =
  336. LatestPhase(*phase, GetPhase(eval_context.constant_values(), const_id));
  337. return eval_context.constant_values().GetInstId(const_id);
  338. }
  339. // Gets a constant value for an `inst_id`, diagnosing when the input is not a
  340. // constant value.
  341. static auto RequireConstantValue(EvalContext& eval_context,
  342. SemIR::InstId inst_id, Phase* phase)
  343. -> SemIR::InstId {
  344. if (!inst_id.has_value()) {
  345. return SemIR::InstId::None;
  346. }
  347. auto const_id = eval_context.GetConstantValue(inst_id);
  348. *phase =
  349. LatestPhase(*phase, GetPhase(eval_context.constant_values(), const_id));
  350. if (const_id.is_constant()) {
  351. return eval_context.constant_values().GetInstId(const_id);
  352. }
  353. if (inst_id != SemIR::ErrorInst::InstId) {
  354. CARBON_DIAGNOSTIC(EvalRequiresConstantValue, Error,
  355. "expression is runtime; expected constant");
  356. eval_context.emitter().Emit(eval_context.GetDiagnosticLoc({inst_id}),
  357. EvalRequiresConstantValue);
  358. }
  359. *phase = Phase::UnknownDueToError;
  360. return SemIR::ErrorInst::InstId;
  361. }
  362. // If the given instruction is constant, returns its constant value. Otherwise,
  363. // produces an error diagnostic. When determining the phase of the result,
  364. // ignore any dependence on `.Self`.
  365. //
  366. // This is used when evaluating facet types, for which `where` expressions using
  367. // `.Self` should not be considered symbolic
  368. // - `Interface where .Self impls I and .A = bool` -> concrete
  369. // - `T:! type` ... `Interface where .A = T` -> symbolic, since uses `T` which
  370. // is symbolic and not due to `.Self`.
  371. static auto RequireConstantValueIgnoringPeriodSelf(EvalContext& eval_context,
  372. SemIR::InstId inst_id,
  373. Phase* phase)
  374. -> SemIR::InstId {
  375. if (!inst_id.has_value()) {
  376. return SemIR::InstId::None;
  377. }
  378. Phase constant_phase = *phase;
  379. auto const_inst_id =
  380. RequireConstantValue(eval_context, inst_id, &constant_phase);
  381. // Since LatestPhase(x, Phase::Concrete) == x, this is equivalent to replacing
  382. // Phase::PeriodSelfSymbolic with Phase::Concrete.
  383. if (constant_phase != Phase::PeriodSelfSymbolic) {
  384. *phase = LatestPhase(*phase, constant_phase);
  385. }
  386. return const_inst_id;
  387. }
  388. // Find the instruction that the given instruction instantiates to, and return
  389. // that.
  390. static auto GetConstantValue(EvalContext& eval_context,
  391. SemIR::MetaInstId inst_id, Phase* phase)
  392. -> SemIR::MetaInstId {
  393. Phase inner_phase = Phase::Concrete;
  394. if (auto const_inst_id =
  395. GetConstantValue(eval_context, SemIR::InstId(inst_id), &inner_phase);
  396. const_inst_id.has_value()) {
  397. // The instruction has a constant value. Use that as the operand of the
  398. // action.
  399. *phase = LatestPhase(*phase, inner_phase);
  400. return const_inst_id;
  401. }
  402. // If this instruction is splicing in an action result, that action result is
  403. // our operand.
  404. if (auto splice = eval_context.insts().TryGetAs<SemIR::SpliceInst>(inst_id)) {
  405. if (auto spliced_inst_id =
  406. GetConstantValue(eval_context, splice->inst_id, phase);
  407. spliced_inst_id.has_value()) {
  408. if (auto inst_value_id = eval_context.insts().TryGetAs<SemIR::InstValue>(
  409. spliced_inst_id)) {
  410. return inst_value_id->inst_id;
  411. }
  412. }
  413. }
  414. // Otherwise, this is a normal instruction.
  415. if (OperandIsDependent(eval_context.context(), inst_id)) {
  416. *phase = LatestPhase(*phase, Phase::TemplateSymbolic);
  417. }
  418. return inst_id;
  419. }
  420. static auto GetConstantValue(EvalContext& eval_context,
  421. SemIR::TypeInstId inst_id, Phase* phase)
  422. -> SemIR::TypeInstId {
  423. // The input instruction is a TypeInstId, and eval does not change concrete
  424. // types (like TypeType which TypeInstId implies), so the result is also a
  425. // valid TypeInstId.
  426. return SemIR::TypeInstId::UnsafeMake(GetConstantValue(
  427. eval_context, static_cast<SemIR::InstId>(inst_id), phase));
  428. }
  429. // Explicitly discard a `DestInstId`, because we should not be using the
  430. // destination as part of evaluation.
  431. static auto GetConstantValue(EvalContext& /*eval_context*/,
  432. SemIR::DestInstId /*inst_id*/, Phase* /*phase*/)
  433. -> SemIR::DestInstId {
  434. return SemIR::InstId::None;
  435. }
  436. // Given an instruction whose type may refer to a generic parameter, returns the
  437. // corresponding type in the evaluation context.
  438. //
  439. // If the `InstId` is not provided, the instruction is assumed to be new and
  440. // therefore unattached, and the type of the given instruction is returned
  441. // unchanged, but the phase is still updated.
  442. static auto GetTypeOfInst(EvalContext& eval_context, SemIR::InstId inst_id,
  443. SemIR::Inst inst, Phase* phase) -> SemIR::TypeId {
  444. auto type_id = inst_id.has_value() ? eval_context.GetTypeOfInst(inst_id)
  445. : inst.type_id();
  446. *phase = LatestPhase(*phase,
  447. GetPhase(eval_context.constant_values(),
  448. eval_context.types().GetConstantId(type_id)));
  449. return type_id;
  450. }
  451. // AbsoluteInstBlockId can not have its values substituted, so this overload is
  452. // deleted. This prevents conversion to InstBlockId.
  453. static auto GetConstantValue(EvalContext& eval_context,
  454. SemIR::AbsoluteInstBlockId inst_block_id,
  455. Phase* phase) -> SemIR::InstBlockId = delete;
  456. // If the given instruction block contains only constants, returns a
  457. // corresponding block of those values.
  458. static auto GetConstantValue(EvalContext& eval_context,
  459. SemIR::InstBlockId inst_block_id, Phase* phase)
  460. -> SemIR::InstBlockId {
  461. if (!inst_block_id.has_value()) {
  462. return SemIR::InstBlockId::None;
  463. }
  464. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  465. llvm::SmallVector<SemIR::InstId> const_insts;
  466. for (auto inst_id : insts) {
  467. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  468. if (!const_inst_id.has_value()) {
  469. return SemIR::InstBlockId::None;
  470. }
  471. // Once we leave the small buffer, we know the first few elements are all
  472. // constant, so it's likely that the entire block is constant. Resize to the
  473. // target size given that we're going to allocate memory now anyway.
  474. if (const_insts.size() == const_insts.capacity()) {
  475. const_insts.reserve(insts.size());
  476. }
  477. const_insts.push_back(const_inst_id);
  478. }
  479. // TODO: If the new block is identical to the original block, and we know the
  480. // old ID was canonical, return the original ID.
  481. return eval_context.inst_blocks().AddCanonical(const_insts);
  482. }
  483. // Compute the constant value of a type block. This may be different from the
  484. // input type block if we have known generic arguments.
  485. static auto GetConstantValue(EvalContext& eval_context,
  486. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  487. -> SemIR::StructTypeFieldsId {
  488. if (!fields_id.has_value()) {
  489. return SemIR::StructTypeFieldsId::None;
  490. }
  491. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  492. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  493. for (auto field : fields) {
  494. auto new_type_inst_id =
  495. GetConstantValue(eval_context, field.type_inst_id, phase);
  496. if (!new_type_inst_id.has_value()) {
  497. return SemIR::StructTypeFieldsId::None;
  498. }
  499. // Once we leave the small buffer, we know the first few elements are all
  500. // constant, so it's likely that the entire block is constant. Resize to the
  501. // target size given that we're going to allocate memory now anyway.
  502. if (new_fields.size() == new_fields.capacity()) {
  503. new_fields.reserve(fields.size());
  504. }
  505. new_fields.push_back(
  506. {.name_id = field.name_id, .type_inst_id = new_type_inst_id});
  507. }
  508. // TODO: If the new block is identical to the original block, and we know the
  509. // old ID was canonical, return the original ID.
  510. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  511. }
  512. // The constant value of a specific is the specific with the corresponding
  513. // constant values for its arguments.
  514. static auto GetConstantValue(EvalContext& eval_context,
  515. SemIR::SpecificId specific_id, Phase* phase)
  516. -> SemIR::SpecificId {
  517. if (!specific_id.has_value()) {
  518. return SemIR::SpecificId::None;
  519. }
  520. const auto& specific = eval_context.specifics().Get(specific_id);
  521. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  522. if (!args_id.has_value()) {
  523. return SemIR::SpecificId::None;
  524. }
  525. // Generally, when making a new specific, it's done through MakeSpecific(),
  526. // which will ensure the declaration is resolved.
  527. //
  528. // However, the SpecificId returned here is intentionally left without its
  529. // declaration resolved. Imported instructions with SpecificIds should not
  530. // have the specific's declaration resolved, but other instructions which
  531. // include a new SpecificId should.
  532. //
  533. // The resolving of the specific's declaration will be ensured later when
  534. // evaluating the instruction containing the SpecificId.
  535. if (args_id == specific.args_id) {
  536. return specific_id;
  537. }
  538. return eval_context.context().specifics().GetOrAdd(specific.generic_id,
  539. args_id);
  540. }
  541. static auto GetConstantValue(EvalContext& eval_context,
  542. SemIR::SpecificInterfaceId specific_interface_id,
  543. Phase* phase) -> SemIR::SpecificInterfaceId {
  544. const auto& interface =
  545. eval_context.specific_interfaces().Get(specific_interface_id);
  546. if (!interface.specific_id.has_value()) {
  547. return specific_interface_id;
  548. }
  549. return eval_context.specific_interfaces().Add(
  550. {.interface_id = interface.interface_id,
  551. .specific_id =
  552. GetConstantValue(eval_context, interface.specific_id, phase)});
  553. }
  554. // Like `GetConstantValue` but for a `FacetTypeInfo`.
  555. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  556. SemIR::LocId loc_id,
  557. const SemIR::FacetTypeInfo& orig,
  558. Phase* phase) -> SemIR::FacetTypeInfo {
  559. SemIR::FacetTypeInfo info = {};
  560. info.extend_constraints.reserve(orig.extend_constraints.size());
  561. for (const auto& extend : orig.extend_constraints) {
  562. info.extend_constraints.push_back(
  563. {.interface_id = extend.interface_id,
  564. .specific_id =
  565. GetConstantValue(eval_context, extend.specific_id, phase)});
  566. }
  567. info.self_impls_constraints.reserve(orig.self_impls_constraints.size());
  568. for (const auto& self_impls : orig.self_impls_constraints) {
  569. info.self_impls_constraints.push_back(
  570. {.interface_id = self_impls.interface_id,
  571. .specific_id =
  572. GetConstantValue(eval_context, self_impls.specific_id, phase)});
  573. }
  574. info.extend_named_constraints.reserve(orig.extend_named_constraints.size());
  575. for (const auto& extend : orig.extend_named_constraints) {
  576. info.extend_named_constraints.push_back(
  577. {.named_constraint_id = extend.named_constraint_id,
  578. .specific_id =
  579. GetConstantValue(eval_context, extend.specific_id, phase)});
  580. }
  581. info.self_impls_named_constraints.reserve(
  582. orig.self_impls_named_constraints.size());
  583. for (const auto& self_impls : orig.self_impls_named_constraints) {
  584. info.self_impls_named_constraints.push_back(
  585. {.named_constraint_id = self_impls.named_constraint_id,
  586. .specific_id =
  587. GetConstantValue(eval_context, self_impls.specific_id, phase)});
  588. }
  589. // Rewrite constraints are resolved first before replacing them with their
  590. // canonical instruction, so that in a `WhereExpr` we can work with the
  591. // `ImplWitnessAccess` references to `.Self` on the LHS of the constraints
  592. // rather than the value of the associated constant they reference.
  593. //
  594. // This also implies that we may find `ImplWitnessAccessSubstituted`
  595. // instructions in the LHS and RHS of these constraints, which are preserved
  596. // to maintain them as an unresolved reference to an associated constant, but
  597. // which must be handled gracefully during resolution. They will be replaced
  598. // with the constant value of the `ImplWitnessAccess` below when they are
  599. // substituted with a constant value.
  600. info.rewrite_constraints = orig.rewrite_constraints;
  601. if (!ResolveFacetTypeRewriteConstraints(eval_context.context(), loc_id,
  602. info.rewrite_constraints)) {
  603. *phase = Phase::UnknownDueToError;
  604. }
  605. for (auto& rewrite : info.rewrite_constraints) {
  606. // `where` requirements using `.Self` should not be considered symbolic.
  607. auto lhs_id = RequireConstantValueIgnoringPeriodSelf(eval_context,
  608. rewrite.lhs_id, phase);
  609. auto rhs_id = RequireConstantValueIgnoringPeriodSelf(eval_context,
  610. rewrite.rhs_id, phase);
  611. rewrite = {.lhs_id = lhs_id, .rhs_id = rhs_id};
  612. }
  613. // TODO: Process other requirements.
  614. info.other_requirements = orig.other_requirements;
  615. info.Canonicalize();
  616. return info;
  617. }
  618. static auto GetConstantValue(EvalContext& eval_context,
  619. SemIR::FacetTypeId facet_type_id, Phase* phase)
  620. -> SemIR::FacetTypeId {
  621. SemIR::FacetTypeInfo info = GetConstantFacetTypeInfo(
  622. eval_context, SemIR::LocId::None,
  623. eval_context.facet_types().Get(facet_type_id), phase);
  624. return eval_context.facet_types().Add(info);
  625. }
  626. static auto GetConstantValue(EvalContext& eval_context,
  627. SemIR::EntityNameId entity_name_id, Phase* phase)
  628. -> SemIR::EntityNameId {
  629. const auto& bind_name = eval_context.entity_names().Get(entity_name_id);
  630. Phase name_phase;
  631. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  632. name_phase = Phase::PeriodSelfSymbolic;
  633. } else if (!bind_name.bind_index().has_value()) {
  634. name_phase = Phase::Concrete;
  635. } else if (bind_name.is_template) {
  636. name_phase = Phase::TemplateSymbolic;
  637. } else {
  638. name_phase = Phase::CheckedSymbolic;
  639. }
  640. *phase = LatestPhase(*phase, name_phase);
  641. return eval_context.entity_names().MakeCanonical(entity_name_id);
  642. }
  643. // Replaces the specified field of the given typed instruction with its constant
  644. // value, if it has constant phase. Returns true on success, false if the value
  645. // has runtime phase.
  646. template <typename InstT, typename FieldIdT>
  647. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  648. InstT* inst, FieldIdT InstT::* field,
  649. Phase* phase) -> bool {
  650. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  651. if (!unwrapped.has_value() && (inst->*field).has_value()) {
  652. return false;
  653. }
  654. inst->*field = unwrapped;
  655. return IsConstantOrError(*phase);
  656. }
  657. // Function template that can be called with an argument of type `T`. Used below
  658. // to detect which overloads of `GetConstantValue` exist.
  659. template <typename T>
  660. static void Accept(T /*arg*/) {}
  661. // Determines whether a `GetConstantValue` overload exists for a given ID type.
  662. // Note that we do not check whether `GetConstantValue` is *callable* with a
  663. // given ID type, because that would use the `InstId` overload for
  664. // `AbsoluteInstId` and similar wrapper types, which should be left alone.
  665. template <typename IdT>
  666. static constexpr bool HasGetConstantValueOverload = requires {
  667. Accept<auto (*)(EvalContext&, IdT, Phase*)->IdT>(GetConstantValue);
  668. };
  669. using ArgHandlerFnT = auto(EvalContext& context, int32_t arg, Phase* phase)
  670. -> int32_t;
  671. // Returns the arg handler for an `IdKind`.
  672. template <typename... Types>
  673. static auto GetArgHandlerFn(TypeEnum<Types...> id_kind) -> ArgHandlerFnT* {
  674. static constexpr std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> Table =
  675. {
  676. [](EvalContext& eval_context, int32_t arg, Phase* phase) -> int32_t {
  677. auto id = SemIR::Inst::FromRaw<Types>(arg);
  678. if constexpr (HasGetConstantValueOverload<Types>) {
  679. // If we have a custom `GetConstantValue` overload, call it.
  680. return SemIR::Inst::ToRaw(
  681. GetConstantValue(eval_context, id, phase));
  682. } else {
  683. // Otherwise, we assume the value is already constant.
  684. return arg;
  685. }
  686. }...,
  687. // Invalid and None handling (ordering-sensitive).
  688. [](auto...) -> int32_t { CARBON_FATAL("Unexpected invalid IdKind"); },
  689. [](EvalContext& /*context*/, int32_t arg,
  690. Phase* /*phase*/) -> int32_t { return arg; },
  691. };
  692. return Table[id_kind.ToIndex()];
  693. }
  694. // Given the stored value `arg` of an instruction field and its corresponding
  695. // kind `kind`, returns the constant value to use for that field, if it has a
  696. // constant phase. `*phase` is updated to include the new constant value. If
  697. // the resulting phase is not constant, the returned value is not useful and
  698. // will typically be `NoneIndex`.
  699. static auto GetConstantValueForArg(EvalContext& eval_context,
  700. SemIR::Inst::ArgAndKind arg_and_kind,
  701. Phase* phase) -> int32_t {
  702. return GetArgHandlerFn(arg_and_kind.kind())(eval_context,
  703. arg_and_kind.value(), phase);
  704. }
  705. // Given an instruction, replaces its operands with their constant values from
  706. // the specified evaluation context. `*phase` is updated to describe the
  707. // constant phase of the result. Returns whether `*phase` is a constant phase;
  708. // if not, `inst` may not be fully updated and should not be used.
  709. static auto ReplaceAllFieldsWithConstantValues(EvalContext& eval_context,
  710. SemIR::Inst* inst, Phase* phase)
  711. -> bool {
  712. auto arg0 =
  713. GetConstantValueForArg(eval_context, inst->arg0_and_kind(), phase);
  714. if (!IsConstantOrError(*phase)) {
  715. return false;
  716. }
  717. auto arg1 =
  718. GetConstantValueForArg(eval_context, inst->arg1_and_kind(), phase);
  719. if (!IsConstantOrError(*phase)) {
  720. return false;
  721. }
  722. inst->SetArgs(arg0, arg1);
  723. return true;
  724. }
  725. // Given an instruction and its ID, replaces its type with the corresponding
  726. // value in this evaluation context. Updates `*phase` to describe the phase of
  727. // the result, and returns whether `*phase` is a constant phase.
  728. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  729. SemIR::InstId inst_id,
  730. SemIR::Inst* inst, Phase* phase)
  731. -> bool {
  732. inst->SetType(GetTypeOfInst(eval_context, inst_id, *inst, phase));
  733. return IsConstantOrError(*phase);
  734. }
  735. template <typename InstT>
  736. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  737. SemIR::InstId inst_id, InstT* inst,
  738. Phase* phase) -> bool {
  739. inst->type_id = GetTypeOfInst(eval_context, inst_id, *inst, phase);
  740. return IsConstantOrError(*phase);
  741. }
  742. template <typename... Types>
  743. static auto KindHasGetConstantValueOverload(TypeEnum<Types...> e) -> bool {
  744. static constexpr std::array<bool, SemIR::IdKind::NumTypes> Values = {
  745. (HasGetConstantValueOverload<Types>)...};
  746. return Values[e.ToIndex()];
  747. }
  748. static auto ResolveSpecificDeclForSpecificId(EvalContext& eval_context,
  749. SemIR::SpecificId specific_id)
  750. -> void {
  751. if (!specific_id.has_value()) {
  752. return;
  753. }
  754. const auto& specific = eval_context.specifics().Get(specific_id);
  755. const auto& generic = eval_context.generics().Get(specific.generic_id);
  756. if (specific_id == generic.self_specific_id) {
  757. // Impl witness table construction happens before its generic decl is
  758. // finish, in order to make the table's instructions dependent
  759. // instructions of the Impl's generic. But those instructions can refer to
  760. // the generic's self specific. We can not resolve the specific
  761. // declaration for the self specific until the generic is finished, but it
  762. // is explicitly resolved at that time in `FinishGenericDecl()`.
  763. return;
  764. }
  765. ResolveSpecificDecl(eval_context.context(), eval_context.fallback_loc_id(),
  766. specific_id);
  767. }
  768. // Resolves the specific declarations for a specific id in any field of the
  769. // `inst` instruction.
  770. static auto ResolveSpecificDeclForInst(EvalContext& eval_context,
  771. const SemIR::Inst& inst) -> void {
  772. for (auto arg_and_kind : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  773. // This switch must handle any field type that has a GetConstantValue()
  774. // overload which canonicalizes a specific (and thus potentially forms a new
  775. // specific) as part of forming its constant value.
  776. CARBON_KIND_SWITCH(arg_and_kind) {
  777. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  778. const auto& info =
  779. eval_context.context().facet_types().Get(facet_type_id);
  780. for (const auto& interface : info.extend_constraints) {
  781. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  782. }
  783. for (const auto& interface : info.self_impls_constraints) {
  784. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  785. }
  786. for (const auto& constraint : info.extend_named_constraints) {
  787. ResolveSpecificDeclForSpecificId(eval_context,
  788. constraint.specific_id);
  789. }
  790. for (const auto& constraint : info.self_impls_named_constraints) {
  791. ResolveSpecificDeclForSpecificId(eval_context,
  792. constraint.specific_id);
  793. }
  794. break;
  795. }
  796. case CARBON_KIND(SemIR::SpecificId specific_id): {
  797. ResolveSpecificDeclForSpecificId(eval_context, specific_id);
  798. break;
  799. }
  800. case CARBON_KIND(SemIR::SpecificInterfaceId specific_interface_id): {
  801. ResolveSpecificDeclForSpecificId(eval_context,
  802. eval_context.specific_interfaces()
  803. .Get(specific_interface_id)
  804. .specific_id);
  805. break;
  806. }
  807. // These id types have a GetConstantValue() overload but that overload
  808. // does not canonicalize any SpecificId in the value type.
  809. case SemIR::IdKind::For<SemIR::DestInstId>:
  810. case SemIR::IdKind::For<SemIR::EntityNameId>:
  811. case SemIR::IdKind::For<SemIR::InstBlockId>:
  812. case SemIR::IdKind::For<SemIR::InstId>:
  813. case SemIR::IdKind::For<SemIR::MetaInstId>:
  814. case SemIR::IdKind::For<SemIR::StructTypeFieldsId>:
  815. case SemIR::IdKind::For<SemIR::TypeInstId>:
  816. break;
  817. case SemIR::IdKind::None:
  818. // No arg.
  819. break;
  820. default:
  821. CARBON_CHECK(
  822. !KindHasGetConstantValueOverload(arg_and_kind.kind()),
  823. "Missing case for {0} which has a GetConstantValue() overload",
  824. arg_and_kind.kind());
  825. break;
  826. }
  827. }
  828. }
  829. auto AddImportedConstant(Context& context, SemIR::Inst inst)
  830. -> SemIR::ConstantId {
  831. EvalContext eval_context(&context, SemIR::LocId::None);
  832. CARBON_CHECK(inst.kind().has_type(), "Can't import untyped instructions: {0}",
  833. inst.kind());
  834. Phase phase = GetPhase(context.constant_values(),
  835. context.types().GetConstantId(inst.type_id()));
  836. // We ignore the return value of ReplaceAllFieldsWithConstantValues and just
  837. // propagate runtime and error constant values into the resulting ConstantId.
  838. ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase);
  839. return MakeConstantResult(context, inst, phase);
  840. }
  841. // Performs an index into a homogeneous aggregate, retrieving the specified
  842. // element.
  843. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  844. -> SemIR::ConstantId {
  845. Phase phase = Phase::Concrete;
  846. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  847. if (!index_id.has_value()) {
  848. return MakeNonConstantResult(phase);
  849. }
  850. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  851. if (!index) {
  852. CARBON_CHECK(phase != Phase::Concrete,
  853. "Concrete constant integer should be a literal");
  854. return MakeNonConstantResult(phase);
  855. }
  856. // Array indexing is invalid if the index is constant and out of range,
  857. // regardless of whether the array itself is constant.
  858. const auto& index_val = eval_context.ints().Get(index->int_id);
  859. auto aggregate_type_id = eval_context.GetTypeOfInst(inst.array_id);
  860. if (auto array_type =
  861. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  862. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  863. array_type->bound_id)) {
  864. // This awkward call to `getZExtValue` is a workaround for APInt not
  865. // supporting comparisons between integers of different bit widths.
  866. if (index_val.getActiveBits() > 64 ||
  867. eval_context.ints()
  868. .Get(bound->int_id)
  869. .ule(index_val.getZExtValue())) {
  870. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  871. "array index `{0}` is past the end of type {1}",
  872. TypedInt, SemIR::TypeId);
  873. eval_context.emitter().Emit(
  874. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  875. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  876. return SemIR::ErrorInst::ConstantId;
  877. }
  878. }
  879. }
  880. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  881. if (!aggregate_id.has_value()) {
  882. return MakeNonConstantResult(phase);
  883. }
  884. auto aggregate =
  885. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  886. if (!aggregate) {
  887. // TODO: Consider forming a symbolic constant or reference constant array
  888. // index in this case.
  889. return MakeNonConstantResult(phase);
  890. }
  891. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  892. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  893. }
  894. // Performs a conversion between character types, diagnosing if the value
  895. // doesn't fit in the destination type.
  896. static auto PerformCheckedCharConvert(Context& context, SemIR::LocId loc_id,
  897. SemIR::InstId arg_id,
  898. SemIR::TypeId dest_type_id)
  899. -> SemIR::ConstantId {
  900. auto arg = context.insts().GetAs<SemIR::CharLiteralValue>(arg_id);
  901. // Values over 0x80 require multiple code units in UTF-8.
  902. if (arg.value.index >= 0x80) {
  903. CARBON_DIAGNOSTIC(CharTooLargeForType, Error,
  904. "character value {0} too large for type {1}",
  905. SemIR::CharId, SemIR::TypeId);
  906. context.emitter().Emit(loc_id, CharTooLargeForType, arg.value,
  907. dest_type_id);
  908. return SemIR::ErrorInst::ConstantId;
  909. }
  910. llvm::APInt int_val(8, arg.value.index, /*isSigned=*/false);
  911. return MakeIntResult(context, dest_type_id, /*is_signed=*/false, int_val);
  912. }
  913. // Forms a constant int type as an evaluation result. Requires that width_id is
  914. // constant.
  915. static auto MakeIntTypeResult(Context& context, SemIR::LocId loc_id,
  916. SemIR::IntKind int_kind, SemIR::InstId width_id,
  917. Phase phase) -> SemIR::ConstantId {
  918. auto result = SemIR::IntType{.type_id = SemIR::TypeType::TypeId,
  919. .int_kind = int_kind,
  920. .bit_width_id = width_id};
  921. if (!ValidateIntType(context, loc_id, result)) {
  922. return SemIR::ErrorInst::ConstantId;
  923. }
  924. return MakeConstantResult(context, result, phase);
  925. }
  926. // Forms a constant float type as an evaluation result. Requires that width_id
  927. // is constant.
  928. static auto MakeFloatTypeResult(Context& context, SemIR::LocId loc_id,
  929. SemIR::InstId width_id, Phase phase)
  930. -> SemIR::ConstantId {
  931. auto result = SemIR::FloatType{.type_id = SemIR::TypeType::TypeId,
  932. .bit_width_id = width_id,
  933. .float_kind = SemIR::FloatKind::None};
  934. if (!ValidateFloatTypeAndSetKind(context, loc_id, result)) {
  935. return SemIR::ErrorInst::ConstantId;
  936. }
  937. return MakeConstantResult(context, result, phase);
  938. }
  939. // Performs a conversion between integer types, truncating if the value doesn't
  940. // fit in the destination type.
  941. static auto PerformIntConvert(Context& context, SemIR::InstId arg_id,
  942. SemIR::TypeId dest_type_id) -> SemIR::ConstantId {
  943. auto arg_val =
  944. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(arg_id).int_id);
  945. auto [dest_is_signed, bit_width_id] =
  946. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  947. if (bit_width_id.has_value()) {
  948. // TODO: If the value fits in the destination type, reuse the existing
  949. // int_id rather than recomputing it. This is probably the most common case.
  950. bool src_is_signed = context.sem_ir().types().IsSignedInt(
  951. context.insts().Get(arg_id).type_id());
  952. unsigned width = context.ints().Get(bit_width_id).getZExtValue();
  953. arg_val =
  954. src_is_signed ? arg_val.sextOrTrunc(width) : arg_val.zextOrTrunc(width);
  955. }
  956. return MakeIntResult(context, dest_type_id, dest_is_signed, arg_val);
  957. }
  958. // Performs a conversion between integer types, diagnosing if the value doesn't
  959. // fit in the destination type.
  960. static auto PerformCheckedIntConvert(Context& context, SemIR::LocId loc_id,
  961. SemIR::InstId arg_id,
  962. SemIR::TypeId dest_type_id)
  963. -> SemIR::ConstantId {
  964. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  965. auto arg_val = context.ints().Get(arg.int_id);
  966. auto [is_signed, bit_width_id] =
  967. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  968. auto width = bit_width_id.has_value()
  969. ? context.ints().Get(bit_width_id).getZExtValue()
  970. : arg_val.getBitWidth();
  971. if (!is_signed && arg_val.isNegative()) {
  972. CARBON_DIAGNOSTIC(
  973. NegativeIntInUnsignedType, Error,
  974. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  975. SemIR::TypeId);
  976. context.emitter().Emit(loc_id, NegativeIntInUnsignedType,
  977. {.type = arg.type_id, .value = arg_val},
  978. dest_type_id);
  979. }
  980. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  981. if (arg_non_sign_bits + is_signed > width) {
  982. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  983. "integer value {0} too large for type {1}", TypedInt,
  984. SemIR::TypeId);
  985. context.emitter().Emit(loc_id, IntTooLargeForType,
  986. {.type = arg.type_id, .value = arg_val},
  987. dest_type_id);
  988. }
  989. return MakeConstantResult(
  990. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  991. Phase::Concrete);
  992. }
  993. // Performs a conversion between floating-point types, diagnosing if the value
  994. // doesn't fit in the destination type.
  995. static auto PerformCheckedFloatConvert(Context& context, SemIR::LocId loc_id,
  996. SemIR::InstId arg_id,
  997. SemIR::TypeId dest_type_id)
  998. -> SemIR::ConstantId {
  999. auto dest_type_object_rep_id = context.types().GetObjectRepr(dest_type_id);
  1000. CARBON_CHECK(dest_type_object_rep_id.has_value(),
  1001. "Conversion to incomplete type");
  1002. auto dest_float_type =
  1003. context.types().TryGetAs<SemIR::FloatType>(dest_type_object_rep_id);
  1004. CARBON_CHECK(dest_float_type || context.types().Is<SemIR::FloatLiteralType>(
  1005. dest_type_object_rep_id));
  1006. if (auto literal =
  1007. context.insts().TryGetAs<SemIR::FloatLiteralValue>(arg_id)) {
  1008. if (!dest_float_type) {
  1009. return MakeConstantResult(
  1010. context,
  1011. SemIR::FloatLiteralValue{.type_id = dest_type_id,
  1012. .real_id = literal->real_id},
  1013. Phase::Concrete);
  1014. }
  1015. // Convert the real literal to an llvm::APFloat and add it to the floats
  1016. // ValueStore. In the future this would use an arbitrary precision Rational
  1017. // type.
  1018. //
  1019. // TODO: Implement Carbon's actual implicit conversion rules for
  1020. // floating-point constants, as per the design
  1021. // docs/design/expressions/implicit_conversions.md
  1022. auto real_value = context.sem_ir().reals().Get(literal->real_id);
  1023. // Convert the real value to a string.
  1024. llvm::SmallString<64> str;
  1025. real_value.mantissa.toString(str, real_value.is_decimal ? 10 : 16,
  1026. /*signed=*/false, /*formatAsCLiteral=*/true);
  1027. str += real_value.is_decimal ? "e" : "p";
  1028. real_value.exponent.toStringSigned(str);
  1029. // Convert the string to an APFloat.
  1030. llvm::APFloat result(dest_float_type->float_kind.Semantics());
  1031. // TODO: The implementation of this conversion effectively converts back to
  1032. // APInts, but unfortunately the conversion from integer mantissa and
  1033. // exponent in IEEEFloat::roundSignificandWithExponent is not part of the
  1034. // public API.
  1035. auto status =
  1036. result.convertFromString(str, llvm::APFloat::rmNearestTiesToEven);
  1037. if (auto error = status.takeError()) {
  1038. // The literal we create should always successfully parse.
  1039. CARBON_FATAL("Float literal parsing failed: {0}",
  1040. toString(std::move(error)));
  1041. }
  1042. if (status.get() & llvm::APFloat::opOverflow) {
  1043. CARBON_DIAGNOSTIC(FloatLiteralTooLargeForType, Error,
  1044. "value {0} too large for floating-point type {1}",
  1045. RealId, SemIR::TypeId);
  1046. context.emitter().Emit(loc_id, FloatLiteralTooLargeForType,
  1047. literal->real_id, dest_type_id);
  1048. return SemIR::ErrorInst::ConstantId;
  1049. }
  1050. return MakeFloatResult(context, dest_type_id, std::move(result));
  1051. }
  1052. if (!dest_float_type) {
  1053. context.TODO(loc_id, "conversion from float to float literal");
  1054. return SemIR::ErrorInst::ConstantId;
  1055. }
  1056. // Convert to the destination float semantics.
  1057. auto arg = context.insts().GetAs<SemIR::FloatValue>(arg_id);
  1058. llvm::APFloat result = context.floats().Get(arg.float_id);
  1059. bool loses_info;
  1060. auto status = result.convert(dest_float_type->float_kind.Semantics(),
  1061. llvm::APFloat::rmNearestTiesToEven, &loses_info);
  1062. if (status & llvm::APFloat::opOverflow) {
  1063. CARBON_DIAGNOSTIC(FloatTooLargeForType, Error,
  1064. "value {0} too large for floating-point type {1}",
  1065. llvm::APFloat, SemIR::TypeId);
  1066. context.emitter().Emit(loc_id, FloatTooLargeForType,
  1067. context.floats().Get(arg.float_id), dest_type_id);
  1068. return SemIR::ErrorInst::ConstantId;
  1069. }
  1070. return MakeFloatResult(context, dest_type_id, std::move(result));
  1071. }
  1072. // Issues a diagnostic for a compile-time division by zero.
  1073. static auto DiagnoseDivisionByZero(Context& context, SemIR::LocId loc_id)
  1074. -> void {
  1075. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  1076. context.emitter().Emit(loc_id, CompileTimeDivisionByZero);
  1077. }
  1078. // Get an integer at a suitable bit-width: either `bit_width_id` if it has a
  1079. // value, or the canonical width from the value store if not.
  1080. static auto GetIntAtSuitableWidth(Context& context, IntId int_id,
  1081. IntId bit_width_id) -> llvm::APInt {
  1082. return bit_width_id.has_value()
  1083. ? context.ints().GetAtWidth(int_id, bit_width_id)
  1084. : context.ints().Get(int_id);
  1085. }
  1086. // Performs a builtin unary integer -> integer operation.
  1087. static auto PerformBuiltinUnaryIntOp(Context& context, SemIR::LocId loc_id,
  1088. SemIR::BuiltinFunctionKind builtin_kind,
  1089. SemIR::InstId arg_id)
  1090. -> SemIR::ConstantId {
  1091. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  1092. auto [is_signed, bit_width_id] =
  1093. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  1094. llvm::APInt op_val = GetIntAtSuitableWidth(context, op.int_id, bit_width_id);
  1095. switch (builtin_kind) {
  1096. case SemIR::BuiltinFunctionKind::IntSNegate:
  1097. if (op_val.isMinSignedValue()) {
  1098. if (bit_width_id.has_value()) {
  1099. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  1100. "integer overflow in negation of {0}", TypedInt);
  1101. context.emitter().Emit(loc_id, CompileTimeIntegerNegateOverflow,
  1102. {.type = op.type_id, .value = op_val});
  1103. } else {
  1104. // Widen the integer so we don't overflow into the sign bit.
  1105. op_val = op_val.sext(op_val.getBitWidth() +
  1106. llvm::APInt::APINT_BITS_PER_WORD);
  1107. }
  1108. }
  1109. op_val.negate();
  1110. break;
  1111. case SemIR::BuiltinFunctionKind::IntUNegate:
  1112. CARBON_CHECK(bit_width_id.has_value(), "Unsigned negate on unsized int");
  1113. op_val.negate();
  1114. break;
  1115. case SemIR::BuiltinFunctionKind::IntComplement:
  1116. // TODO: Should we have separate builtins for signed and unsigned
  1117. // complement? Like with signed/unsigned negate, these operations do
  1118. // different things to the integer value, even though they do the same
  1119. // thing to the bits. We treat IntLiteral complement as signed complement,
  1120. // given that the result of unsigned complement depends on the bit width.
  1121. op_val.flipAllBits();
  1122. break;
  1123. default:
  1124. CARBON_FATAL("Unexpected builtin kind");
  1125. }
  1126. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  1127. }
  1128. namespace {
  1129. // A pair of APInts that are the operands of a binary operator. We use an
  1130. // aggregate rather than `std::pair` to allow RVO of the individual ints.
  1131. struct APIntBinaryOperands {
  1132. llvm::APInt lhs;
  1133. llvm::APInt rhs;
  1134. };
  1135. } // namespace
  1136. // Get a pair of integers at the same suitable bit-width: either their actual
  1137. // width if they have a fixed width, or the smallest canonical width in which
  1138. // they both fit otherwise.
  1139. static auto GetIntsAtSuitableWidth(Context& context, IntId lhs_id, IntId rhs_id,
  1140. IntId bit_width_id) -> APIntBinaryOperands {
  1141. // Unsized operands: take the wider of the bit widths.
  1142. if (!bit_width_id.has_value()) {
  1143. APIntBinaryOperands result = {.lhs = context.ints().Get(lhs_id),
  1144. .rhs = context.ints().Get(rhs_id)};
  1145. if (result.lhs.getBitWidth() != result.rhs.getBitWidth()) {
  1146. if (result.lhs.getBitWidth() > result.rhs.getBitWidth()) {
  1147. result.rhs = result.rhs.sext(result.lhs.getBitWidth());
  1148. } else {
  1149. result.lhs = result.lhs.sext(result.rhs.getBitWidth());
  1150. }
  1151. }
  1152. return result;
  1153. }
  1154. return {.lhs = context.ints().GetAtWidth(lhs_id, bit_width_id),
  1155. .rhs = context.ints().GetAtWidth(rhs_id, bit_width_id)};
  1156. }
  1157. namespace {
  1158. // The result of performing a binary int operation.
  1159. struct BinaryIntOpResult {
  1160. llvm::APInt result_val;
  1161. bool overflow;
  1162. Lex::TokenKind op_token;
  1163. };
  1164. } // namespace
  1165. // Computes the result of a homogeneous binary (int, int) -> int operation.
  1166. static auto ComputeBinaryIntOpResult(SemIR::BuiltinFunctionKind builtin_kind,
  1167. const llvm::APInt& lhs_val,
  1168. const llvm::APInt& rhs_val)
  1169. -> BinaryIntOpResult {
  1170. llvm::APInt result_val;
  1171. bool overflow = false;
  1172. Lex::TokenKind op_token = Lex::TokenKind::Not;
  1173. switch (builtin_kind) {
  1174. // Arithmetic.
  1175. case SemIR::BuiltinFunctionKind::IntSAdd:
  1176. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  1177. op_token = Lex::TokenKind::Plus;
  1178. break;
  1179. case SemIR::BuiltinFunctionKind::IntSSub:
  1180. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  1181. op_token = Lex::TokenKind::Minus;
  1182. break;
  1183. case SemIR::BuiltinFunctionKind::IntSMul:
  1184. result_val = lhs_val.smul_ov(rhs_val, overflow);
  1185. op_token = Lex::TokenKind::Star;
  1186. break;
  1187. case SemIR::BuiltinFunctionKind::IntSDiv:
  1188. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  1189. op_token = Lex::TokenKind::Slash;
  1190. break;
  1191. case SemIR::BuiltinFunctionKind::IntSMod:
  1192. result_val = lhs_val.srem(rhs_val);
  1193. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  1194. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  1195. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  1196. op_token = Lex::TokenKind::Percent;
  1197. break;
  1198. case SemIR::BuiltinFunctionKind::IntUAdd:
  1199. result_val = lhs_val + rhs_val;
  1200. op_token = Lex::TokenKind::Plus;
  1201. break;
  1202. case SemIR::BuiltinFunctionKind::IntUSub:
  1203. result_val = lhs_val - rhs_val;
  1204. op_token = Lex::TokenKind::Minus;
  1205. break;
  1206. case SemIR::BuiltinFunctionKind::IntUMul:
  1207. result_val = lhs_val * rhs_val;
  1208. op_token = Lex::TokenKind::Star;
  1209. break;
  1210. case SemIR::BuiltinFunctionKind::IntUDiv:
  1211. result_val = lhs_val.udiv(rhs_val);
  1212. op_token = Lex::TokenKind::Slash;
  1213. break;
  1214. case SemIR::BuiltinFunctionKind::IntUMod:
  1215. result_val = lhs_val.urem(rhs_val);
  1216. op_token = Lex::TokenKind::Percent;
  1217. break;
  1218. // Bitwise.
  1219. case SemIR::BuiltinFunctionKind::IntAnd:
  1220. result_val = lhs_val & rhs_val;
  1221. op_token = Lex::TokenKind::And;
  1222. break;
  1223. case SemIR::BuiltinFunctionKind::IntOr:
  1224. result_val = lhs_val | rhs_val;
  1225. op_token = Lex::TokenKind::Pipe;
  1226. break;
  1227. case SemIR::BuiltinFunctionKind::IntXor:
  1228. result_val = lhs_val ^ rhs_val;
  1229. op_token = Lex::TokenKind::Caret;
  1230. break;
  1231. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1232. case SemIR::BuiltinFunctionKind::IntRightShift:
  1233. CARBON_FATAL("Non-homogeneous operation handled separately.");
  1234. default:
  1235. CARBON_FATAL("Unexpected operation kind.");
  1236. }
  1237. return {.result_val = std::move(result_val),
  1238. .overflow = overflow,
  1239. .op_token = op_token};
  1240. }
  1241. // Performs a builtin integer bit shift operation.
  1242. static auto PerformBuiltinIntShiftOp(Context& context, SemIR::LocId loc_id,
  1243. SemIR::BuiltinFunctionKind builtin_kind,
  1244. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  1245. -> SemIR::ConstantId {
  1246. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1247. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1248. auto [lhs_is_signed, lhs_bit_width_id] =
  1249. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  1250. llvm::APInt lhs_val =
  1251. GetIntAtSuitableWidth(context, lhs.int_id, lhs_bit_width_id);
  1252. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  1253. if (lhs_bit_width_id.has_value() && rhs_orig_val.uge(lhs_val.getBitWidth())) {
  1254. CARBON_DIAGNOSTIC(
  1255. CompileTimeShiftOutOfRange, Error,
  1256. "shift distance >= type width of {0} in `{1} {2:<<|>>} {3}`", unsigned,
  1257. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1258. context.emitter().Emit(
  1259. loc_id, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  1260. {.type = lhs.type_id, .value = lhs_val},
  1261. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1262. {.type = rhs.type_id, .value = rhs_orig_val});
  1263. // TODO: Is it useful to recover by returning 0 or -1?
  1264. return SemIR::ErrorInst::ConstantId;
  1265. }
  1266. if (rhs_orig_val.isNegative() &&
  1267. context.sem_ir().types().IsSignedInt(rhs.type_id)) {
  1268. CARBON_DIAGNOSTIC(CompileTimeShiftNegative, Error,
  1269. "shift distance negative in `{0} {1:<<|>>} {2}`",
  1270. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1271. context.emitter().Emit(
  1272. loc_id, CompileTimeShiftNegative,
  1273. {.type = lhs.type_id, .value = lhs_val},
  1274. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1275. {.type = rhs.type_id, .value = rhs_orig_val});
  1276. // TODO: Is it useful to recover by returning 0 or -1?
  1277. return SemIR::ErrorInst::ConstantId;
  1278. }
  1279. llvm::APInt result_val;
  1280. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  1281. if (!lhs_bit_width_id.has_value() && !lhs_val.isZero()) {
  1282. // Ensure we don't generate a ridiculously large integer through a bit
  1283. // shift.
  1284. auto width = rhs_orig_val.trySExtValue();
  1285. if (!width ||
  1286. *width > IntStore::MaxIntWidth - lhs_val.getSignificantBits()) {
  1287. CARBON_DIAGNOSTIC(CompileTimeUnsizedShiftOutOfRange, Error,
  1288. "shift distance of {0} would result in an "
  1289. "integer whose width is greater than the "
  1290. "maximum supported width of {1}",
  1291. TypedInt, int);
  1292. context.emitter().Emit(loc_id, CompileTimeUnsizedShiftOutOfRange,
  1293. {.type = rhs.type_id, .value = rhs_orig_val},
  1294. IntStore::MaxIntWidth);
  1295. return SemIR::ErrorInst::ConstantId;
  1296. }
  1297. lhs_val = lhs_val.sext(
  1298. IntStore::CanonicalBitWidth(lhs_val.getSignificantBits() + *width));
  1299. }
  1300. result_val =
  1301. lhs_val.shl(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1302. } else if (lhs_is_signed) {
  1303. result_val =
  1304. lhs_val.ashr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1305. } else {
  1306. CARBON_CHECK(lhs_bit_width_id.has_value(), "Logical shift on unsized int");
  1307. result_val =
  1308. lhs_val.lshr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1309. }
  1310. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  1311. std::move(result_val));
  1312. }
  1313. // Performs a homogeneous builtin binary integer -> integer operation.
  1314. static auto PerformBuiltinBinaryIntOp(Context& context, SemIR::LocId loc_id,
  1315. SemIR::BuiltinFunctionKind builtin_kind,
  1316. SemIR::InstId lhs_id,
  1317. SemIR::InstId rhs_id)
  1318. -> SemIR::ConstantId {
  1319. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1320. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1321. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  1322. auto type_id = lhs.type_id;
  1323. auto [is_signed, bit_width_id] =
  1324. context.sem_ir().types().GetIntTypeInfo(type_id);
  1325. auto [lhs_val, rhs_val] =
  1326. GetIntsAtSuitableWidth(context, lhs.int_id, rhs.int_id, bit_width_id);
  1327. // Check for division by zero.
  1328. switch (builtin_kind) {
  1329. case SemIR::BuiltinFunctionKind::IntSDiv:
  1330. case SemIR::BuiltinFunctionKind::IntSMod:
  1331. case SemIR::BuiltinFunctionKind::IntUDiv:
  1332. case SemIR::BuiltinFunctionKind::IntUMod:
  1333. if (rhs_val.isZero()) {
  1334. DiagnoseDivisionByZero(context, loc_id);
  1335. return SemIR::ErrorInst::ConstantId;
  1336. }
  1337. break;
  1338. default:
  1339. break;
  1340. }
  1341. BinaryIntOpResult result =
  1342. ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1343. if (result.overflow && !bit_width_id.has_value()) {
  1344. // Retry with a larger bit width. Most operations can only overflow by one
  1345. // bit, but signed n-bit multiplication can overflow to 2n-1 bits. We don't
  1346. // need to handle unsigned multiplication here because it's not permitted
  1347. // for unsized integers.
  1348. //
  1349. // Note that we speculatively first perform the calculation in the width of
  1350. // the wider operand: smaller operations are faster and overflow to a wider
  1351. // integer is unlikely to be needed, especially given that the width will
  1352. // have been rounded up to a multiple of 64 bits by the int store.
  1353. CARBON_CHECK(builtin_kind != SemIR::BuiltinFunctionKind::IntUMul,
  1354. "Unsigned arithmetic requires a fixed bitwidth");
  1355. int new_width =
  1356. builtin_kind == SemIR::BuiltinFunctionKind::IntSMul
  1357. ? lhs_val.getBitWidth() * 2
  1358. : IntStore::CanonicalBitWidth(lhs_val.getBitWidth() + 1);
  1359. new_width = std::min(new_width, IntStore::MaxIntWidth);
  1360. lhs_val = context.ints().GetAtWidth(lhs.int_id, new_width);
  1361. rhs_val = context.ints().GetAtWidth(rhs.int_id, new_width);
  1362. // Note that this can in theory still overflow if we limited `new_width` to
  1363. // `MaxIntWidth`. In that case we fall through to the signed overflow
  1364. // diagnostic below.
  1365. result = ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1366. CARBON_CHECK(!result.overflow || new_width == IntStore::MaxIntWidth);
  1367. }
  1368. if (result.overflow) {
  1369. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  1370. "integer overflow in calculation `{0} {1} {2}`", TypedInt,
  1371. Lex::TokenKind, TypedInt);
  1372. context.emitter().Emit(loc_id, CompileTimeIntegerOverflow,
  1373. {.type = type_id, .value = lhs_val}, result.op_token,
  1374. {.type = type_id, .value = rhs_val});
  1375. }
  1376. return MakeIntResult(context, type_id, is_signed,
  1377. std::move(result.result_val));
  1378. }
  1379. // Performs a builtin integer comparison.
  1380. static auto PerformBuiltinIntComparison(Context& context,
  1381. SemIR::BuiltinFunctionKind builtin_kind,
  1382. SemIR::InstId lhs_id,
  1383. SemIR::InstId rhs_id,
  1384. SemIR::TypeId bool_type_id)
  1385. -> SemIR::ConstantId {
  1386. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1387. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1388. llvm::APInt lhs_val = context.ints().Get(lhs.int_id);
  1389. llvm::APInt rhs_val = context.ints().Get(rhs.int_id);
  1390. bool result;
  1391. switch (builtin_kind) {
  1392. case SemIR::BuiltinFunctionKind::IntEq:
  1393. result = (lhs_val == rhs_val);
  1394. break;
  1395. case SemIR::BuiltinFunctionKind::IntNeq:
  1396. result = (lhs_val != rhs_val);
  1397. break;
  1398. case SemIR::BuiltinFunctionKind::IntLess:
  1399. result = lhs_val.slt(rhs_val);
  1400. break;
  1401. case SemIR::BuiltinFunctionKind::IntLessEq:
  1402. result = lhs_val.sle(rhs_val);
  1403. break;
  1404. case SemIR::BuiltinFunctionKind::IntGreater:
  1405. result = lhs_val.sgt(rhs_val);
  1406. break;
  1407. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  1408. result = lhs_val.sge(rhs_val);
  1409. break;
  1410. default:
  1411. CARBON_FATAL("Unexpected operation kind.");
  1412. }
  1413. return MakeBoolResult(context, bool_type_id, result);
  1414. }
  1415. // Performs a builtin unary float -> float operation.
  1416. static auto PerformBuiltinUnaryFloatOp(Context& context,
  1417. SemIR::BuiltinFunctionKind builtin_kind,
  1418. SemIR::InstId arg_id)
  1419. -> SemIR::ConstantId {
  1420. auto op = context.insts().GetAs<SemIR::FloatValue>(arg_id);
  1421. auto op_val = context.floats().Get(op.float_id);
  1422. switch (builtin_kind) {
  1423. case SemIR::BuiltinFunctionKind::FloatNegate:
  1424. op_val.changeSign();
  1425. break;
  1426. default:
  1427. CARBON_FATAL("Unexpected builtin kind");
  1428. }
  1429. return MakeFloatResult(context, op.type_id, std::move(op_val));
  1430. }
  1431. // Performs a builtin binary float -> float operation.
  1432. static auto PerformBuiltinBinaryFloatOp(Context& context,
  1433. SemIR::BuiltinFunctionKind builtin_kind,
  1434. SemIR::InstId lhs_id,
  1435. SemIR::InstId rhs_id)
  1436. -> SemIR::ConstantId {
  1437. auto lhs = context.insts().GetAs<SemIR::FloatValue>(lhs_id);
  1438. auto rhs = context.insts().GetAs<SemIR::FloatValue>(rhs_id);
  1439. auto lhs_val = context.floats().Get(lhs.float_id);
  1440. auto rhs_val = context.floats().Get(rhs.float_id);
  1441. llvm::APFloat result_val(lhs_val.getSemantics());
  1442. switch (builtin_kind) {
  1443. case SemIR::BuiltinFunctionKind::FloatAdd:
  1444. result_val = lhs_val + rhs_val;
  1445. break;
  1446. case SemIR::BuiltinFunctionKind::FloatSub:
  1447. result_val = lhs_val - rhs_val;
  1448. break;
  1449. case SemIR::BuiltinFunctionKind::FloatMul:
  1450. result_val = lhs_val * rhs_val;
  1451. break;
  1452. case SemIR::BuiltinFunctionKind::FloatDiv:
  1453. result_val = lhs_val / rhs_val;
  1454. break;
  1455. default:
  1456. CARBON_FATAL("Unexpected operation kind.");
  1457. }
  1458. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  1459. }
  1460. // Performs a builtin float comparison.
  1461. static auto PerformBuiltinFloatComparison(
  1462. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1463. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  1464. -> SemIR::ConstantId {
  1465. auto lhs = context.insts().GetAs<SemIR::FloatValue>(lhs_id);
  1466. auto rhs = context.insts().GetAs<SemIR::FloatValue>(rhs_id);
  1467. const auto& lhs_val = context.floats().Get(lhs.float_id);
  1468. const auto& rhs_val = context.floats().Get(rhs.float_id);
  1469. bool result;
  1470. switch (builtin_kind) {
  1471. case SemIR::BuiltinFunctionKind::FloatEq:
  1472. result = (lhs_val == rhs_val);
  1473. break;
  1474. case SemIR::BuiltinFunctionKind::FloatNeq:
  1475. result = (lhs_val != rhs_val);
  1476. break;
  1477. case SemIR::BuiltinFunctionKind::FloatLess:
  1478. result = lhs_val < rhs_val;
  1479. break;
  1480. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1481. result = lhs_val <= rhs_val;
  1482. break;
  1483. case SemIR::BuiltinFunctionKind::FloatGreater:
  1484. result = lhs_val > rhs_val;
  1485. break;
  1486. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  1487. result = lhs_val >= rhs_val;
  1488. break;
  1489. default:
  1490. CARBON_FATAL("Unexpected operation kind.");
  1491. }
  1492. return MakeBoolResult(context, bool_type_id, result);
  1493. }
  1494. // Performs a builtin boolean comparison.
  1495. static auto PerformBuiltinBoolComparison(
  1496. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1497. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  1498. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1499. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1500. return MakeBoolResult(context, bool_type_id,
  1501. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1502. ? lhs == rhs
  1503. : lhs != rhs);
  1504. }
  1505. // Converts a call argument to a FacetTypeId.
  1506. static auto ArgToFacetTypeId(Context& context, SemIR::LocId loc_id,
  1507. SemIR::InstId arg_id) -> SemIR::FacetTypeId {
  1508. auto type_arg_id = context.types().GetAsTypeInstId(arg_id);
  1509. if (auto facet_type =
  1510. context.insts().TryGetAs<SemIR::FacetType>(type_arg_id)) {
  1511. return facet_type->facet_type_id;
  1512. }
  1513. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1514. "non-facet type {0} combined with `&` operator",
  1515. SemIR::TypeId);
  1516. // TODO: Find a location for the lhs or rhs specifically, instead of
  1517. // the whole thing. If that's not possible we can change the text to
  1518. // say if it's referring to the left or the right side for the error.
  1519. // The `arg_id` instruction has no location in it for some reason.
  1520. context.emitter().Emit(loc_id, FacetTypeRequiredForTypeAndOperator,
  1521. context.types().GetTypeIdForTypeInstId(type_arg_id));
  1522. return SemIR::FacetTypeId::None;
  1523. }
  1524. // Returns a constant for a call to a builtin function.
  1525. static auto MakeConstantForBuiltinCall(EvalContext& eval_context,
  1526. SemIR::LocId loc_id, SemIR::Call call,
  1527. SemIR::BuiltinFunctionKind builtin_kind,
  1528. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1529. Phase phase) -> SemIR::ConstantId {
  1530. auto& context = eval_context.context();
  1531. switch (builtin_kind) {
  1532. case SemIR::BuiltinFunctionKind::None:
  1533. CARBON_FATAL("Not a builtin function.");
  1534. case SemIR::BuiltinFunctionKind::NoOp: {
  1535. // Return an empty tuple value.
  1536. auto type_id = GetTupleType(eval_context.context(), {});
  1537. return MakeConstantResult(
  1538. eval_context.context(),
  1539. SemIR::TupleValue{.type_id = type_id,
  1540. .elements_id = SemIR::InstBlockId::Empty},
  1541. phase);
  1542. }
  1543. case SemIR::BuiltinFunctionKind::PrimitiveCopy: {
  1544. return context.constant_values().Get(arg_ids[0]);
  1545. }
  1546. case SemIR::BuiltinFunctionKind::StringAt: {
  1547. Phase phase = Phase::Concrete;
  1548. auto str_id = GetConstantValue(eval_context, arg_ids[0], &phase);
  1549. auto index_id = GetConstantValue(eval_context, arg_ids[1], &phase);
  1550. if (phase != Phase::Concrete) {
  1551. return MakeNonConstantResult(phase);
  1552. }
  1553. auto str_struct = eval_context.insts().GetAs<SemIR::StructValue>(str_id);
  1554. auto elements = eval_context.inst_blocks().Get(str_struct.elements_id);
  1555. // String struct has two fields: a pointer to the string data and the
  1556. // length.
  1557. CARBON_CHECK(elements.size() == 2, "String struct should have 2 fields.");
  1558. auto string_literal = eval_context.insts().GetAs<SemIR::StringLiteral>(
  1559. eval_context.constant_values().GetConstantInstId(elements[0]));
  1560. const auto& string_value =
  1561. eval_context.sem_ir().string_literal_values().Get(
  1562. string_literal.string_literal_id);
  1563. auto index_inst = eval_context.insts().GetAs<SemIR::IntValue>(index_id);
  1564. const auto& index_val = eval_context.ints().Get(index_inst.int_id);
  1565. if (index_val.isNegative()) {
  1566. CARBON_DIAGNOSTIC(StringAtIndexNegative, Error,
  1567. "index `{0}` is negative.", TypedInt);
  1568. context.emitter().Emit(
  1569. loc_id, StringAtIndexNegative,
  1570. {.type = eval_context.insts().Get(index_id).type_id(),
  1571. .value = index_val});
  1572. return SemIR::ConstantId::NotConstant;
  1573. }
  1574. if (index_val.getZExtValue() >= string_value.size()) {
  1575. CARBON_DIAGNOSTIC(
  1576. StringAtIndexOutOfBounds, Error,
  1577. "string index `{0}` is out of bounds; string has length {1}.",
  1578. TypedInt, size_t);
  1579. context.emitter().Emit(
  1580. loc_id, StringAtIndexOutOfBounds,
  1581. {.type = eval_context.insts().Get(index_id).type_id(),
  1582. .value = index_val},
  1583. string_value.size());
  1584. return SemIR::ConstantId::NotConstant;
  1585. }
  1586. auto char_value =
  1587. static_cast<uint8_t>(string_value[index_val.getZExtValue()]);
  1588. auto int_id = eval_context.ints().Add(
  1589. llvm::APSInt(llvm::APInt(32, char_value), /*isUnsigned=*/false));
  1590. return MakeConstantResult(
  1591. eval_context.context(),
  1592. SemIR::IntValue{.type_id = call.type_id, .int_id = int_id}, phase);
  1593. }
  1594. case SemIR::BuiltinFunctionKind::PrintChar:
  1595. case SemIR::BuiltinFunctionKind::PrintInt:
  1596. case SemIR::BuiltinFunctionKind::ReadChar:
  1597. case SemIR::BuiltinFunctionKind::FloatAddAssign:
  1598. case SemIR::BuiltinFunctionKind::FloatSubAssign:
  1599. case SemIR::BuiltinFunctionKind::FloatMulAssign:
  1600. case SemIR::BuiltinFunctionKind::FloatDivAssign:
  1601. case SemIR::BuiltinFunctionKind::IntSAddAssign:
  1602. case SemIR::BuiltinFunctionKind::IntSSubAssign:
  1603. case SemIR::BuiltinFunctionKind::IntSMulAssign:
  1604. case SemIR::BuiltinFunctionKind::IntSDivAssign:
  1605. case SemIR::BuiltinFunctionKind::IntSModAssign:
  1606. case SemIR::BuiltinFunctionKind::IntUAddAssign:
  1607. case SemIR::BuiltinFunctionKind::IntUSubAssign:
  1608. case SemIR::BuiltinFunctionKind::IntUMulAssign:
  1609. case SemIR::BuiltinFunctionKind::IntUDivAssign:
  1610. case SemIR::BuiltinFunctionKind::IntUModAssign:
  1611. case SemIR::BuiltinFunctionKind::IntAndAssign:
  1612. case SemIR::BuiltinFunctionKind::IntOrAssign:
  1613. case SemIR::BuiltinFunctionKind::IntXorAssign:
  1614. case SemIR::BuiltinFunctionKind::IntLeftShiftAssign:
  1615. case SemIR::BuiltinFunctionKind::IntRightShiftAssign:
  1616. case SemIR::BuiltinFunctionKind::PointerMakeNull:
  1617. case SemIR::BuiltinFunctionKind::PointerIsNull: {
  1618. // These are runtime-only builtins.
  1619. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1620. return SemIR::ConstantId::NotConstant;
  1621. }
  1622. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1623. CARBON_CHECK(arg_ids.size() == 2);
  1624. auto lhs_facet_type_id = ArgToFacetTypeId(context, loc_id, arg_ids[0]);
  1625. auto rhs_facet_type_id = ArgToFacetTypeId(context, loc_id, arg_ids[1]);
  1626. // Allow errors to be diagnosed for both sides of the operator before
  1627. // returning here if any error occurred on either side.
  1628. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1629. return SemIR::ErrorInst::ConstantId;
  1630. }
  1631. // Reuse one of the argument instructions if nothing has changed.
  1632. if (lhs_facet_type_id == rhs_facet_type_id) {
  1633. return context.types().GetConstantId(
  1634. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1635. }
  1636. auto combined_info = SemIR::FacetTypeInfo::Combine(
  1637. context.facet_types().Get(lhs_facet_type_id),
  1638. context.facet_types().Get(rhs_facet_type_id));
  1639. if (!ResolveFacetTypeRewriteConstraints(
  1640. eval_context.context(), loc_id,
  1641. combined_info.rewrite_constraints)) {
  1642. phase = Phase::UnknownDueToError;
  1643. }
  1644. combined_info.Canonicalize();
  1645. return MakeFacetTypeResult(eval_context.context(), combined_info, phase);
  1646. }
  1647. case SemIR::BuiltinFunctionKind::CharLiteralMakeType: {
  1648. return context.constant_values().Get(SemIR::CharLiteralType::TypeInstId);
  1649. }
  1650. case SemIR::BuiltinFunctionKind::FloatLiteralMakeType: {
  1651. return context.constant_values().Get(SemIR::FloatLiteralType::TypeInstId);
  1652. }
  1653. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1654. return context.constant_values().Get(SemIR::IntLiteralType::TypeInstId);
  1655. }
  1656. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1657. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Signed,
  1658. arg_ids[0], phase);
  1659. }
  1660. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1661. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Unsigned,
  1662. arg_ids[0], phase);
  1663. }
  1664. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1665. return MakeFloatTypeResult(context, loc_id, arg_ids[0], phase);
  1666. }
  1667. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1668. return context.constant_values().Get(SemIR::BoolType::TypeInstId);
  1669. }
  1670. case SemIR::BuiltinFunctionKind::MaybeUnformedMakeType: {
  1671. return MakeConstantResult(
  1672. context,
  1673. SemIR::MaybeUnformedType{
  1674. .type_id = SemIR::TypeType::TypeId,
  1675. .inner_id = context.types().GetAsTypeInstId(arg_ids[0])},
  1676. phase);
  1677. }
  1678. // Character conversions.
  1679. case SemIR::BuiltinFunctionKind::CharConvertChecked: {
  1680. if (phase != Phase::Concrete) {
  1681. return MakeConstantResult(context, call, phase);
  1682. }
  1683. return PerformCheckedCharConvert(context, loc_id, arg_ids[0],
  1684. call.type_id);
  1685. }
  1686. // Integer conversions.
  1687. case SemIR::BuiltinFunctionKind::IntConvert: {
  1688. if (phase != Phase::Concrete) {
  1689. return MakeConstantResult(context, call, phase);
  1690. }
  1691. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1692. }
  1693. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1694. if (phase != Phase::Concrete) {
  1695. return MakeConstantResult(context, call, phase);
  1696. }
  1697. return PerformCheckedIntConvert(context, loc_id, arg_ids[0],
  1698. call.type_id);
  1699. }
  1700. // Unary integer -> integer operations.
  1701. case SemIR::BuiltinFunctionKind::IntSNegate:
  1702. case SemIR::BuiltinFunctionKind::IntUNegate:
  1703. case SemIR::BuiltinFunctionKind::IntComplement: {
  1704. if (phase != Phase::Concrete) {
  1705. break;
  1706. }
  1707. return PerformBuiltinUnaryIntOp(context, loc_id, builtin_kind,
  1708. arg_ids[0]);
  1709. }
  1710. // Homogeneous binary integer -> integer operations.
  1711. case SemIR::BuiltinFunctionKind::IntSAdd:
  1712. case SemIR::BuiltinFunctionKind::IntSSub:
  1713. case SemIR::BuiltinFunctionKind::IntSMul:
  1714. case SemIR::BuiltinFunctionKind::IntSDiv:
  1715. case SemIR::BuiltinFunctionKind::IntSMod:
  1716. case SemIR::BuiltinFunctionKind::IntUAdd:
  1717. case SemIR::BuiltinFunctionKind::IntUSub:
  1718. case SemIR::BuiltinFunctionKind::IntUMul:
  1719. case SemIR::BuiltinFunctionKind::IntUDiv:
  1720. case SemIR::BuiltinFunctionKind::IntUMod:
  1721. case SemIR::BuiltinFunctionKind::IntAnd:
  1722. case SemIR::BuiltinFunctionKind::IntOr:
  1723. case SemIR::BuiltinFunctionKind::IntXor: {
  1724. if (phase != Phase::Concrete) {
  1725. break;
  1726. }
  1727. return PerformBuiltinBinaryIntOp(context, loc_id, builtin_kind,
  1728. arg_ids[0], arg_ids[1]);
  1729. }
  1730. // Bit shift operations.
  1731. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1732. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1733. if (phase != Phase::Concrete) {
  1734. break;
  1735. }
  1736. return PerformBuiltinIntShiftOp(context, loc_id, builtin_kind, arg_ids[0],
  1737. arg_ids[1]);
  1738. }
  1739. // Integer comparisons.
  1740. case SemIR::BuiltinFunctionKind::IntEq:
  1741. case SemIR::BuiltinFunctionKind::IntNeq:
  1742. case SemIR::BuiltinFunctionKind::IntLess:
  1743. case SemIR::BuiltinFunctionKind::IntLessEq:
  1744. case SemIR::BuiltinFunctionKind::IntGreater:
  1745. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1746. if (phase != Phase::Concrete) {
  1747. break;
  1748. }
  1749. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1750. arg_ids[1], call.type_id);
  1751. }
  1752. // Floating-point conversions.
  1753. case SemIR::BuiltinFunctionKind::FloatConvertChecked: {
  1754. if (phase != Phase::Concrete) {
  1755. return MakeConstantResult(context, call, phase);
  1756. }
  1757. return PerformCheckedFloatConvert(context, loc_id, arg_ids[0],
  1758. call.type_id);
  1759. }
  1760. // Unary float -> float operations.
  1761. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1762. if (phase != Phase::Concrete) {
  1763. break;
  1764. }
  1765. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1766. }
  1767. // Binary float -> float operations.
  1768. case SemIR::BuiltinFunctionKind::FloatAdd:
  1769. case SemIR::BuiltinFunctionKind::FloatSub:
  1770. case SemIR::BuiltinFunctionKind::FloatMul:
  1771. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1772. if (phase != Phase::Concrete) {
  1773. break;
  1774. }
  1775. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1776. arg_ids[1]);
  1777. }
  1778. // Float comparisons.
  1779. case SemIR::BuiltinFunctionKind::FloatEq:
  1780. case SemIR::BuiltinFunctionKind::FloatNeq:
  1781. case SemIR::BuiltinFunctionKind::FloatLess:
  1782. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1783. case SemIR::BuiltinFunctionKind::FloatGreater:
  1784. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1785. if (phase != Phase::Concrete) {
  1786. break;
  1787. }
  1788. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1789. arg_ids[1], call.type_id);
  1790. }
  1791. // Bool comparisons.
  1792. case SemIR::BuiltinFunctionKind::BoolEq:
  1793. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1794. if (phase != Phase::Concrete) {
  1795. break;
  1796. }
  1797. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1798. arg_ids[1], call.type_id);
  1799. }
  1800. }
  1801. return SemIR::ConstantId::NotConstant;
  1802. }
  1803. // Makes a constant for a call instruction.
  1804. static auto MakeConstantForCall(EvalContext& eval_context,
  1805. SemIR::InstId inst_id, SemIR::Call call)
  1806. -> SemIR::ConstantId {
  1807. Phase phase = Phase::Concrete;
  1808. // A call with an invalid argument list is used to represent an erroneous
  1809. // call.
  1810. //
  1811. // TODO: Use a better representation for this.
  1812. if (call.args_id == SemIR::InstBlockId::None) {
  1813. return SemIR::ErrorInst::ConstantId;
  1814. }
  1815. // Find the constant value of the callee.
  1816. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1817. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1818. auto callee = SemIR::GetCallee(eval_context.sem_ir(), call.callee_id);
  1819. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1820. if (auto* fn = std::get_if<SemIR::CalleeFunction>(&callee)) {
  1821. // Calls to builtins might be constant.
  1822. builtin_kind =
  1823. eval_context.functions().Get(fn->function_id).builtin_function_kind();
  1824. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1825. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1826. // functions as producing constants.
  1827. return SemIR::ConstantId::NotConstant;
  1828. }
  1829. } else {
  1830. // Calls to non-functions, such as calls to generic entity names, might be
  1831. // constant.
  1832. }
  1833. // Find the argument values and the return type.
  1834. bool has_constant_operands =
  1835. has_constant_callee &&
  1836. ReplaceTypeWithConstantValue(eval_context, inst_id, &call, &phase) &&
  1837. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1838. &phase);
  1839. if (phase == Phase::UnknownDueToError) {
  1840. return SemIR::ErrorInst::ConstantId;
  1841. }
  1842. // If any operand of the call is non-constant, the call is non-constant.
  1843. // TODO: Some builtin calls might allow some operands to be non-constant.
  1844. if (!has_constant_operands) {
  1845. if (builtin_kind.IsCompTimeOnly(
  1846. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1847. call.type_id)) {
  1848. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1849. "non-constant call to compile-time-only function");
  1850. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1851. "compile-time-only function declared here");
  1852. const auto& function = eval_context.functions().Get(
  1853. std::get<SemIR::CalleeFunction>(callee).function_id);
  1854. eval_context.emitter()
  1855. .Build(inst_id, NonConstantCallToCompTimeOnlyFunction)
  1856. .Note(function.latest_decl_id(), CompTimeOnlyFunctionHere)
  1857. .Emit();
  1858. }
  1859. return SemIR::ConstantId::NotConstant;
  1860. }
  1861. // Handle calls to builtins.
  1862. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1863. return MakeConstantForBuiltinCall(
  1864. eval_context, SemIR::LocId(inst_id), call, builtin_kind,
  1865. eval_context.inst_blocks().Get(call.args_id), phase);
  1866. }
  1867. return SemIR::ConstantId::NotConstant;
  1868. }
  1869. // Given an instruction, compute its phase based on its operands.
  1870. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1871. EvalContext eval_context(&context, SemIR::LocId::None);
  1872. auto phase = GetPhase(context.constant_values(),
  1873. context.types().GetConstantId(inst.type_id()));
  1874. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  1875. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  1876. CARBON_CHECK(IsConstantOrError(phase));
  1877. return phase;
  1878. }
  1879. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1880. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1881. static auto ConvertEvalResultToConstantId(Context& context,
  1882. ConstantEvalResult result,
  1883. Phase orig_phase)
  1884. -> SemIR::ConstantId {
  1885. if (result.is_new()) {
  1886. return MakeConstantResult(
  1887. context, result.new_inst(),
  1888. result.same_phase_as_inst()
  1889. ? orig_phase
  1890. : ComputeInstPhase(context, result.new_inst()));
  1891. }
  1892. return result.existing();
  1893. }
  1894. // Evaluates an instruction of a known type in an evaluation context. The
  1895. // default behavior of this function depends on the constant kind of the
  1896. // instruction:
  1897. //
  1898. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  1899. // - InstConstantKind::Indirect, SymbolicOnly, SymbolicOrReference,
  1900. // Conditional: evaluates all the operands of the instruction, and calls
  1901. // `EvalConstantInst` to evaluate the resulting constant instruction.
  1902. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  1903. // the instruction, and produces the resulting constant instruction as the
  1904. // result.
  1905. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  1906. // constant.
  1907. //
  1908. // Returns an error constant ID if any of the nested evaluations fail, and
  1909. // returns NotConstant if any of the nested evaluations is non-constant.
  1910. //
  1911. // This template is explicitly specialized for instructions that need special
  1912. // handling.
  1913. template <typename InstT>
  1914. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  1915. SemIR::Inst inst) -> SemIR::ConstantId {
  1916. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  1917. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  1918. return SemIR::ConstantId::NotConstant;
  1919. } else if constexpr (ConstantKind == SemIR::InstConstantKind::AlwaysUnique) {
  1920. CARBON_CHECK(inst_id.has_value());
  1921. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  1922. } else {
  1923. // Build a constant instruction by replacing each non-constant operand with
  1924. // its constant value.
  1925. Phase phase = Phase::Concrete;
  1926. if ((SemIR::Internal::HasTypeIdMember<InstT> &&
  1927. !ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase)) ||
  1928. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  1929. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  1930. CARBON_FATAL("{0} should always be constant", InstT::Kind);
  1931. }
  1932. return SemIR::ConstantId::NotConstant;
  1933. }
  1934. // If any operand of the instruction has an error in it, the instruction
  1935. // itself evaluates to an error.
  1936. if (phase == Phase::UnknownDueToError) {
  1937. return SemIR::ErrorInst::ConstantId;
  1938. }
  1939. // When canonicalizing a SpecificId, we defer resolving the specific's
  1940. // declaration until here, to avoid resolving declarations from imported
  1941. // specifics. (Imported instructions are not evaluated.)
  1942. ResolveSpecificDeclForInst(eval_context, inst);
  1943. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  1944. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  1945. return MakeConstantResult(eval_context.context(), inst, phase);
  1946. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  1947. auto result_inst_id = PerformDelayedAction(
  1948. eval_context.context(), SemIR::LocId(inst_id), inst.As<InstT>());
  1949. if (result_inst_id.has_value()) {
  1950. // The result is an instruction.
  1951. return MakeConstantResult(
  1952. eval_context.context(),
  1953. SemIR::InstValue{
  1954. .type_id = GetSingletonType(eval_context.context(),
  1955. SemIR::InstType::TypeInstId),
  1956. .inst_id = result_inst_id},
  1957. Phase::Concrete);
  1958. }
  1959. // Couldn't perform the action because it's still dependent.
  1960. return MakeConstantResult(eval_context.context(), inst,
  1961. Phase::TemplateSymbolic);
  1962. } else if constexpr (InstT::Kind.constant_needs_inst_id() !=
  1963. SemIR::InstConstantNeedsInstIdKind::No) {
  1964. CARBON_CHECK(inst_id.has_value());
  1965. return ConvertEvalResultToConstantId(
  1966. eval_context.context(),
  1967. EvalConstantInst(eval_context.context(), inst_id, inst.As<InstT>()),
  1968. phase);
  1969. } else {
  1970. return ConvertEvalResultToConstantId(
  1971. eval_context.context(),
  1972. EvalConstantInst(eval_context.context(), inst.As<InstT>()), phase);
  1973. }
  1974. }
  1975. }
  1976. // Specialize evaluation for array indexing because we want to check the index
  1977. // expression even if the array expression is non-constant.
  1978. template <>
  1979. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  1980. SemIR::InstId /*inst_id*/,
  1981. SemIR::Inst inst)
  1982. -> SemIR::ConstantId {
  1983. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  1984. }
  1985. // Specialize evaluation for function calls because we want to check the callee
  1986. // expression even if an argument expression is non-constant, and because we
  1987. // will eventually want to perform control flow handling here.
  1988. template <>
  1989. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  1990. SemIR::InstId inst_id, SemIR::Inst inst)
  1991. -> SemIR::ConstantId {
  1992. return MakeConstantForCall(eval_context, inst_id, inst.As<SemIR::Call>());
  1993. }
  1994. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  1995. // `import_ref.cpp`, not by us.
  1996. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  1997. // call this.
  1998. template <>
  1999. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  2000. SemIR::InstId /*inst_id*/,
  2001. SemIR::Inst /*inst*/)
  2002. -> SemIR::ConstantId {
  2003. return SemIR::ConstantId::NotConstant;
  2004. }
  2005. // Symbolic bindings are a special case because they can reach into the eval
  2006. // context and produce a context-specific value.
  2007. template <>
  2008. auto TryEvalTypedInst<SemIR::SymbolicBinding>(EvalContext& eval_context,
  2009. SemIR::InstId inst_id,
  2010. SemIR::Inst inst)
  2011. -> SemIR::ConstantId {
  2012. auto bind = inst.As<SemIR::SymbolicBinding>();
  2013. // If we know which specific we're evaluating within and this is an argument
  2014. // of that specific, its constant value is the corresponding argument value.
  2015. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  2016. if (bind_name.bind_index().has_value()) {
  2017. if (auto value =
  2018. eval_context.GetCompileTimeAcquireValue(bind_name.bind_index());
  2019. value.has_value()) {
  2020. return value;
  2021. }
  2022. }
  2023. // The constant form of a symbolic binding is an idealized form of the
  2024. // original, with no equivalent value.
  2025. Phase phase = Phase::Concrete;
  2026. bind.value_id = SemIR::InstId::None;
  2027. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &bind, &phase) ||
  2028. !ReplaceFieldWithConstantValue(eval_context, &bind,
  2029. &SemIR::SymbolicBinding::entity_name_id,
  2030. &phase)) {
  2031. return SemIR::ConstantId::NotConstant;
  2032. }
  2033. // This correctly handles `Phase::UnknownDueToError`.
  2034. return MakeConstantResult(eval_context.context(), bind, phase);
  2035. }
  2036. template <>
  2037. auto TryEvalTypedInst<SemIR::SymbolicBindingType>(EvalContext& eval_context,
  2038. SemIR::InstId inst_id,
  2039. SemIR::Inst inst)
  2040. -> SemIR::ConstantId {
  2041. // If a specific provides a new value for the binding with `entity_name_id`,
  2042. // the SymbolicBindingType is evaluated for that new value.
  2043. const auto& bind_name = eval_context.entity_names().Get(
  2044. inst.As<SemIR::SymbolicBindingType>().entity_name_id);
  2045. if (bind_name.bind_index().has_value()) {
  2046. if (auto value =
  2047. eval_context.GetCompileTimeAcquireValue(bind_name.bind_index());
  2048. value.has_value()) {
  2049. auto value_inst_id = eval_context.constant_values().GetInstId(value);
  2050. // A SymbolicBindingType can evaluate to a FacetAccessType if the new
  2051. // value of the entity is a facet value that that does not have a concrete
  2052. // type (a FacetType) and does not have a new EntityName to point to (a
  2053. // SymbolicBinding).
  2054. auto access = SemIR::FacetAccessType{
  2055. .type_id = SemIR::TypeType::TypeId,
  2056. .facet_value_inst_id = value_inst_id,
  2057. };
  2058. return ConvertEvalResultToConstantId(
  2059. eval_context.context(),
  2060. EvalConstantInst(eval_context.context(), access),
  2061. ComputeInstPhase(eval_context.context(), access));
  2062. }
  2063. }
  2064. Phase phase = Phase::Concrete;
  2065. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase) ||
  2066. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  2067. return SemIR::ConstantId::NotConstant;
  2068. }
  2069. // Propagate error phase after getting the constant value for all fields.
  2070. if (phase == Phase::UnknownDueToError) {
  2071. return SemIR::ErrorInst::ConstantId;
  2072. }
  2073. // Evaluation of SymbolicBindingType.
  2074. //
  2075. // Like FacetAccessType, a SymbolicBindingType of a FacetValue just evaluates
  2076. // to the type inside.
  2077. //
  2078. // TODO: Look in ScopeStack with the entity_name_id to find the facet value
  2079. // and get its constant value in the current specific context. The
  2080. // facet_value_inst_id will go away.
  2081. if (auto facet_value = eval_context.insts().TryGetAs<SemIR::FacetValue>(
  2082. inst.As<SemIR::SymbolicBindingType>().facet_value_inst_id)) {
  2083. return eval_context.constant_values().Get(facet_value->type_inst_id);
  2084. }
  2085. return MakeConstantResult(eval_context.context(), inst, phase);
  2086. }
  2087. // Returns whether `const_id` is the same constant facet value as
  2088. // `facet_value_inst_id`.
  2089. //
  2090. // Compares with the canonical facet value of `const_id`, dropping any `as type`
  2091. // conversions.
  2092. static auto IsSameFacetValue(Context& context, SemIR::ConstantId const_id,
  2093. SemIR::InstId facet_value_inst_id) -> bool {
  2094. auto canon_const_id = GetCanonicalFacetOrTypeValue(context, const_id);
  2095. return canon_const_id == context.constant_values().Get(facet_value_inst_id);
  2096. }
  2097. // TODO: Convert this to an EvalConstantInst function. This will require
  2098. // providing a `GetConstantValue` overload for a requirement block.
  2099. template <>
  2100. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  2101. SemIR::InstId inst_id, SemIR::Inst inst)
  2102. -> SemIR::ConstantId {
  2103. auto typed_inst = inst.As<SemIR::WhereExpr>();
  2104. Phase phase = Phase::Concrete;
  2105. SemIR::FacetTypeInfo info;
  2106. // Add the constraints from the `WhereExpr` instruction into `info`.
  2107. if (typed_inst.requirements_id.has_value()) {
  2108. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  2109. for (auto inst_id : insts) {
  2110. if (auto base =
  2111. eval_context.insts().TryGetAs<SemIR::RequirementBaseFacetType>(
  2112. inst_id)) {
  2113. if (base->base_type_inst_id == SemIR::ErrorInst::TypeInstId) {
  2114. return SemIR::ErrorInst::ConstantId;
  2115. }
  2116. if (auto base_facet_type =
  2117. eval_context.insts().TryGetAs<SemIR::FacetType>(
  2118. base->base_type_inst_id)) {
  2119. const auto& base_info =
  2120. eval_context.facet_types().Get(base_facet_type->facet_type_id);
  2121. info.extend_constraints.append(base_info.extend_constraints);
  2122. info.self_impls_constraints.append(base_info.self_impls_constraints);
  2123. info.rewrite_constraints.append(base_info.rewrite_constraints);
  2124. info.other_requirements |= base_info.other_requirements;
  2125. }
  2126. } else if (auto rewrite =
  2127. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  2128. inst_id)) {
  2129. info.rewrite_constraints.push_back(
  2130. {.lhs_id = rewrite->lhs_id, .rhs_id = rewrite->rhs_id});
  2131. } else if (auto impls =
  2132. eval_context.insts().TryGetAs<SemIR::RequirementImpls>(
  2133. inst_id)) {
  2134. SemIR::ConstantId lhs_const_id =
  2135. eval_context.GetConstantValue(impls->lhs_id);
  2136. SemIR::ConstantId rhs_const_id =
  2137. eval_context.GetConstantValue(impls->rhs_id);
  2138. if (IsSameFacetValue(eval_context.context(), lhs_const_id,
  2139. typed_inst.period_self_id)) {
  2140. auto rhs_inst_id =
  2141. eval_context.constant_values().GetInstId(rhs_const_id);
  2142. if (rhs_inst_id == SemIR::ErrorInst::InstId) {
  2143. // `.Self impls <error>`.
  2144. return SemIR::ErrorInst::ConstantId;
  2145. } else if (rhs_inst_id == SemIR::TypeType::TypeInstId) {
  2146. // `.Self impls type` -> nothing to do.
  2147. } else {
  2148. auto facet_type = eval_context.insts().GetAs<SemIR::FacetType>(
  2149. RequireConstantValue(eval_context, impls->rhs_id, &phase));
  2150. const auto& more_info =
  2151. eval_context.facet_types().Get(facet_type.facet_type_id);
  2152. // The way to prevent lookup into the interface requirements of a
  2153. // facet type is to put it to the right of a `.Self impls`, which we
  2154. // accomplish by putting them into `self_impls_constraints`.
  2155. llvm::append_range(info.self_impls_constraints,
  2156. more_info.extend_constraints);
  2157. llvm::append_range(info.self_impls_constraints,
  2158. more_info.self_impls_constraints);
  2159. // Other requirements are copied in.
  2160. llvm::append_range(info.rewrite_constraints,
  2161. more_info.rewrite_constraints);
  2162. info.other_requirements |= more_info.other_requirements;
  2163. }
  2164. } else {
  2165. // TODO: Handle `impls` constraints beyond `.Self impls`.
  2166. info.other_requirements = true;
  2167. }
  2168. } else {
  2169. // TODO: Handle other requirements.
  2170. info.other_requirements = true;
  2171. }
  2172. }
  2173. }
  2174. auto const_info = GetConstantFacetTypeInfo(
  2175. eval_context, SemIR::LocId(inst_id), info, &phase);
  2176. return MakeFacetTypeResult(eval_context.context(), const_info, phase);
  2177. }
  2178. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  2179. static auto TryEvalInstInContext(EvalContext& eval_context,
  2180. SemIR::InstId inst_id, SemIR::Inst inst)
  2181. -> SemIR::ConstantId {
  2182. using EvalInstFn =
  2183. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  2184. ->SemIR::ConstantId;
  2185. static constexpr EvalInstFn* EvalInstFns[] = {
  2186. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  2187. #include "toolchain/sem_ir/inst_kind.def"
  2188. };
  2189. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  2190. inst_id, inst);
  2191. }
  2192. auto TryEvalInstUnsafe(Context& context, SemIR::InstId inst_id,
  2193. SemIR::Inst inst) -> SemIR::ConstantId {
  2194. EvalContext eval_context(&context, SemIR::LocId(inst_id));
  2195. return TryEvalInstInContext(eval_context, inst_id, inst);
  2196. }
  2197. auto TryEvalBlockForSpecific(Context& context, SemIR::LocId loc_id,
  2198. SemIR::SpecificId specific_id,
  2199. SemIR::GenericInstIndex::Region region)
  2200. -> SemIR::InstBlockId {
  2201. auto generic_id = context.specifics().Get(specific_id).generic_id;
  2202. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  2203. auto eval_block = context.inst_blocks().Get(eval_block_id);
  2204. llvm::SmallVector<SemIR::InstId> result;
  2205. result.resize(eval_block.size(), SemIR::InstId::None);
  2206. EvalContext eval_context(&context, loc_id, specific_id,
  2207. SpecificEvalInfo{
  2208. .region = region,
  2209. .values = result,
  2210. });
  2211. Diagnostics::AnnotationScope annotate_diagnostics(
  2212. &context.emitter(), [&](auto& builder) {
  2213. CARBON_DIAGNOSTIC(ResolvingSpecificHere, Note, "in {0} used here",
  2214. SemIR::SpecificId);
  2215. builder.Note(loc_id, ResolvingSpecificHere, specific_id);
  2216. });
  2217. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  2218. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  2219. context.insts().Get(inst_id));
  2220. result[i] = context.constant_values().GetInstId(const_id);
  2221. CARBON_CHECK(result[i].has_value(), "Failed to evaluate {0} in eval block",
  2222. context.insts().Get(inst_id));
  2223. }
  2224. return context.inst_blocks().Add(result);
  2225. }
  2226. } // namespace Carbon::Check