eval.cpp 86 KB

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