eval.cpp 88 KB

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