eval.cpp 86 KB

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