eval.cpp 93 KB

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