eval.cpp 78 KB

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