eval.cpp 90 KB

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