eval.cpp 91 KB

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