eval.cpp 81 KB

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