eval.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  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/diagnostics/diagnostic_emitter.h"
  9. #include "toolchain/diagnostics/format_providers.h"
  10. #include "toolchain/sem_ir/builtin_function_kind.h"
  11. #include "toolchain/sem_ir/function.h"
  12. #include "toolchain/sem_ir/generic.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/inst_kind.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Check {
  17. namespace {
  18. // Information about an eval block of a specific that we are currently building.
  19. struct SpecificEvalInfo {
  20. // The region within the specific whose eval block we are building.
  21. SemIR::GenericInstIndex::Region region;
  22. // The work-in-progress contents of the eval block.
  23. llvm::ArrayRef<SemIR::InstId> values;
  24. };
  25. // Information about the context within which we are performing evaluation.
  26. class EvalContext {
  27. public:
  28. explicit EvalContext(
  29. Context& context,
  30. SemIR::SpecificId specific_id = SemIR::SpecificId::Invalid,
  31. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  32. : context_(context),
  33. specific_id_(specific_id),
  34. specific_eval_info_(specific_eval_info) {}
  35. // Gets the value of the specified compile-time binding in this context.
  36. // Returns `Invalid` if the value is not fixed in this context.
  37. auto GetCompileTimeBindValue(SemIR::CompileTimeBindIndex bind_index)
  38. -> SemIR::ConstantId {
  39. if (!bind_index.is_valid() || !specific_id_.is_valid()) {
  40. return SemIR::ConstantId::Invalid;
  41. }
  42. const auto& specific = specifics().Get(specific_id_);
  43. auto args = inst_blocks().Get(specific.args_id);
  44. // Bindings past the ones with known arguments can appear as local
  45. // bindings of entities declared within this generic.
  46. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  47. return SemIR::ConstantId::Invalid;
  48. }
  49. return constant_values().Get(args[bind_index.index]);
  50. }
  51. // Given a constant value from the SemIR we're evaluating, finds the
  52. // corresponding constant value to use in the context of this evaluation.
  53. // This can be different if the original SemIR is for a generic and we are
  54. // evaluating with specific arguments for the generic parameters.
  55. auto GetInContext(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  56. if (!const_id.is_symbolic()) {
  57. return const_id;
  58. }
  59. // While resolving a specific, map from previous instructions in the eval
  60. // block into their evaluated values. These values won't be present on the
  61. // specific itself yet, so `GetConstantInSpecific` won't be able to find
  62. // them.
  63. if (specific_eval_info_) {
  64. const auto& symbolic_info =
  65. constant_values().GetSymbolicConstant(const_id);
  66. if (symbolic_info.index.is_valid() &&
  67. symbolic_info.generic_id ==
  68. specifics().Get(specific_id_).generic_id &&
  69. symbolic_info.index.region() == specific_eval_info_->region) {
  70. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  71. CARBON_CHECK(inst_id.is_valid(),
  72. "Forward reference in eval block: index {0} referenced "
  73. "before evaluation",
  74. symbolic_info.index.index());
  75. return constant_values().Get(inst_id);
  76. }
  77. }
  78. // Map from a specific constant value to the canonical value.
  79. return GetConstantInSpecific(sem_ir(), specific_id_, const_id);
  80. }
  81. // Gets the constant value of the specified instruction in this context.
  82. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  83. return GetInContext(constant_values().Get(inst_id));
  84. }
  85. // Gets the constant value of the specified type in this context.
  86. auto GetConstantValue(SemIR::TypeId type_id) -> SemIR::ConstantId {
  87. return GetInContext(types().GetConstantId(type_id));
  88. }
  89. // Gets the constant value of the specified type in this context.
  90. auto GetConstantValueAsType(SemIR::TypeId id) -> SemIR::TypeId {
  91. return context().GetTypeIdForTypeConstant(GetConstantValue(id));
  92. }
  93. // Gets the instruction describing the constant value of the specified type in
  94. // this context.
  95. auto GetConstantValueAsInst(SemIR::TypeId id) -> SemIR::Inst {
  96. return insts().Get(
  97. context().constant_values().GetInstId(GetConstantValue(id)));
  98. }
  99. auto ints() -> CanonicalValueStore<IntId>& { return sem_ir().ints(); }
  100. auto floats() -> FloatValueStore& { return sem_ir().floats(); }
  101. auto entity_names() -> SemIR::EntityNameStore& {
  102. return sem_ir().entity_names();
  103. }
  104. auto functions() -> const ValueStore<SemIR::FunctionId>& {
  105. return sem_ir().functions();
  106. }
  107. auto classes() -> const ValueStore<SemIR::ClassId>& {
  108. return sem_ir().classes();
  109. }
  110. auto interfaces() -> const ValueStore<SemIR::InterfaceId>& {
  111. return sem_ir().interfaces();
  112. }
  113. auto specifics() -> const SemIR::SpecificStore& {
  114. return sem_ir().specifics();
  115. }
  116. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  117. return sem_ir().type_blocks();
  118. }
  119. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  120. auto inst_blocks() -> SemIR::InstBlockStore& {
  121. return sem_ir().inst_blocks();
  122. }
  123. // Gets the constant value store. Note that this does not provide the constant
  124. // values that should be used from this evaluation context, and so should be
  125. // used with caution.
  126. auto constant_values() -> const SemIR::ConstantValueStore& {
  127. return sem_ir().constant_values();
  128. }
  129. // Gets the types store. Note that this does not provide the type values that
  130. // should be used from this evaluation context, and so should be used with
  131. // caution.
  132. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  133. auto context() -> Context& { return context_; }
  134. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  135. auto emitter() -> Context::DiagnosticEmitter& { return context().emitter(); }
  136. private:
  137. // The type-checking context in which we're performing evaluation.
  138. Context& context_;
  139. // The specific that we are evaluating within.
  140. SemIR::SpecificId specific_id_;
  141. // If we are currently evaluating an eval block for `specific_id_`,
  142. // information about that evaluation.
  143. std::optional<SpecificEvalInfo> specific_eval_info_;
  144. };
  145. } // namespace
  146. namespace {
  147. // The evaluation phase for an expression, computed by evaluation. These are
  148. // ordered so that the phase of an expression is the numerically highest phase
  149. // of its constituent evaluations. Note that an expression with any runtime
  150. // component is known to have Runtime phase even if it involves an evaluation
  151. // with UnknownDueToError phase.
  152. enum class Phase : uint8_t {
  153. // Value could be entirely and concretely computed.
  154. Template,
  155. // Evaluation phase is symbolic because the expression involves a reference to
  156. // a symbolic binding.
  157. Symbolic,
  158. // The evaluation phase is unknown because evaluation encountered an
  159. // already-diagnosed semantic or syntax error. This is treated as being
  160. // potentially constant, but with an unknown phase.
  161. UnknownDueToError,
  162. // The expression has runtime phase because of a non-constant subexpression.
  163. Runtime,
  164. };
  165. } // namespace
  166. // Gets the phase in which the value of a constant will become available.
  167. static auto GetPhase(SemIR::ConstantId constant_id) -> Phase {
  168. if (!constant_id.is_constant()) {
  169. return Phase::Runtime;
  170. } else if (constant_id == SemIR::ConstantId::Error) {
  171. return Phase::UnknownDueToError;
  172. } else if (constant_id.is_template()) {
  173. return Phase::Template;
  174. } else {
  175. CARBON_CHECK(constant_id.is_symbolic());
  176. return Phase::Symbolic;
  177. }
  178. }
  179. // Returns the later of two phases.
  180. static auto LatestPhase(Phase a, Phase b) -> Phase {
  181. return static_cast<Phase>(
  182. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  183. }
  184. // Forms a `constant_id` describing a given evaluation result.
  185. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  186. -> SemIR::ConstantId {
  187. switch (phase) {
  188. case Phase::Template:
  189. return context.AddConstant(inst, /*is_symbolic=*/false);
  190. case Phase::Symbolic:
  191. return context.AddConstant(inst, /*is_symbolic=*/true);
  192. case Phase::UnknownDueToError:
  193. return SemIR::ConstantId::Error;
  194. case Phase::Runtime:
  195. return SemIR::ConstantId::NotConstant;
  196. }
  197. }
  198. // Forms a `constant_id` describing why an evaluation was not constant.
  199. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  200. return phase == Phase::UnknownDueToError ? SemIR::ConstantId::Error
  201. : SemIR::ConstantId::NotConstant;
  202. }
  203. // Converts a bool value into a ConstantId.
  204. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  205. bool result) -> SemIR::ConstantId {
  206. return MakeConstantResult(
  207. context,
  208. SemIR::BoolLiteral{.type_id = bool_type_id,
  209. .value = SemIR::BoolValue::From(result)},
  210. Phase::Template);
  211. }
  212. // Converts an APInt value into a ConstantId.
  213. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  214. llvm::APInt value) -> SemIR::ConstantId {
  215. auto result = context.ints().Add(std::move(value));
  216. return MakeConstantResult(
  217. context, SemIR::IntLiteral{.type_id = type_id, .int_id = result},
  218. Phase::Template);
  219. }
  220. // Converts an APFloat value into a ConstantId.
  221. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  222. llvm::APFloat value) -> SemIR::ConstantId {
  223. auto result = context.floats().Add(std::move(value));
  224. return MakeConstantResult(
  225. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  226. Phase::Template);
  227. }
  228. // `GetConstantValue` checks to see whether the provided ID describes a value
  229. // with constant phase, and if so, returns the corresponding constant value.
  230. // Overloads are provided for different kinds of ID.
  231. // If the given instruction is constant, returns its constant value.
  232. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  233. Phase* phase) -> SemIR::InstId {
  234. auto const_id = eval_context.GetConstantValue(inst_id);
  235. *phase = LatestPhase(*phase, GetPhase(const_id));
  236. return eval_context.constant_values().GetInstId(const_id);
  237. }
  238. // Given a type which may refer to a generic parameter, returns the
  239. // corresponding type in the evaluation context.
  240. static auto GetConstantValue(EvalContext& eval_context, SemIR::TypeId type_id,
  241. Phase* phase) -> SemIR::TypeId {
  242. auto const_id = eval_context.GetConstantValue(type_id);
  243. *phase = LatestPhase(*phase, GetPhase(const_id));
  244. return eval_context.context().GetTypeIdForTypeConstant(const_id);
  245. }
  246. // If the given instruction block contains only constants, returns a
  247. // corresponding block of those values.
  248. static auto GetConstantValue(EvalContext& eval_context,
  249. SemIR::InstBlockId inst_block_id, Phase* phase)
  250. -> SemIR::InstBlockId {
  251. if (!inst_block_id.is_valid()) {
  252. return SemIR::InstBlockId::Invalid;
  253. }
  254. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  255. llvm::SmallVector<SemIR::InstId> const_insts;
  256. for (auto inst_id : insts) {
  257. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  258. if (!const_inst_id.is_valid()) {
  259. return SemIR::InstBlockId::Invalid;
  260. }
  261. // Once we leave the small buffer, we know the first few elements are all
  262. // constant, so it's likely that the entire block is constant. Resize to the
  263. // target size given that we're going to allocate memory now anyway.
  264. if (const_insts.size() == const_insts.capacity()) {
  265. const_insts.reserve(insts.size());
  266. }
  267. const_insts.push_back(const_inst_id);
  268. }
  269. // TODO: If the new block is identical to the original block, and we know the
  270. // old ID was canonical, return the original ID.
  271. return eval_context.inst_blocks().AddCanonical(const_insts);
  272. }
  273. // Compute the constant value of a type block. This may be different from the
  274. // input type block if we have known generic arguments.
  275. static auto GetConstantValue(EvalContext& eval_context,
  276. SemIR::TypeBlockId type_block_id, Phase* phase)
  277. -> SemIR::TypeBlockId {
  278. if (!type_block_id.is_valid()) {
  279. return SemIR::TypeBlockId::Invalid;
  280. }
  281. auto types = eval_context.type_blocks().Get(type_block_id);
  282. llvm::SmallVector<SemIR::TypeId> new_types;
  283. for (auto type_id : types) {
  284. auto new_type_id = GetConstantValue(eval_context, type_id, phase);
  285. if (!new_type_id.is_valid()) {
  286. return SemIR::TypeBlockId::Invalid;
  287. }
  288. // Once we leave the small buffer, we know the first few elements are all
  289. // constant, so it's likely that the entire block is constant. Resize to the
  290. // target size given that we're going to allocate memory now anyway.
  291. if (new_types.size() == new_types.capacity()) {
  292. new_types.reserve(types.size());
  293. }
  294. new_types.push_back(new_type_id);
  295. }
  296. // TODO: If the new block is identical to the original block, and we know the
  297. // old ID was canonical, return the original ID.
  298. return eval_context.type_blocks().AddCanonical(new_types);
  299. }
  300. // The constant value of a specific is the specific with the corresponding
  301. // constant values for its arguments.
  302. static auto GetConstantValue(EvalContext& eval_context,
  303. SemIR::SpecificId specific_id, Phase* phase)
  304. -> SemIR::SpecificId {
  305. if (!specific_id.is_valid()) {
  306. return SemIR::SpecificId::Invalid;
  307. }
  308. const auto& specific = eval_context.specifics().Get(specific_id);
  309. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  310. if (!args_id.is_valid()) {
  311. return SemIR::SpecificId::Invalid;
  312. }
  313. if (args_id == specific.args_id) {
  314. return specific_id;
  315. }
  316. return MakeSpecific(eval_context.context(), specific.generic_id, args_id);
  317. }
  318. // Replaces the specified field of the given typed instruction with its constant
  319. // value, if it has constant phase. Returns true on success, false if the value
  320. // has runtime phase.
  321. template <typename InstT, typename FieldIdT>
  322. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  323. InstT* inst, FieldIdT InstT::*field,
  324. Phase* phase) -> bool {
  325. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  326. if (!unwrapped.is_valid() && (inst->*field).is_valid()) {
  327. return false;
  328. }
  329. inst->*field = unwrapped;
  330. return true;
  331. }
  332. // If the specified fields of the given typed instruction have constant values,
  333. // replaces the fields with their constant values and builds a corresponding
  334. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  335. // `ConstantId::Error` if any subexpression is an error.
  336. //
  337. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  338. // which should return a `bool` indicating whether the new constant is valid. If
  339. // validation passes, `transform_fn(typed_inst)` is called to produce the final
  340. // constant instruction, and a corresponding ConstantId for the new constant is
  341. // returned. If validation fails, it should produce a suitable error message.
  342. // `ConstantId::Error` is returned.
  343. template <typename InstT, typename ValidateFn, typename TransformFn,
  344. typename... EachFieldIdT>
  345. static auto RebuildIfFieldsAreConstantImpl(
  346. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  347. TransformFn transform_fn, EachFieldIdT InstT::*... each_field_id)
  348. -> SemIR::ConstantId {
  349. // Build a constant instruction by replacing each non-constant operand with
  350. // its constant value.
  351. auto typed_inst = inst.As<InstT>();
  352. Phase phase = Phase::Template;
  353. if ((ReplaceFieldWithConstantValue(eval_context, &typed_inst, each_field_id,
  354. &phase) &&
  355. ...)) {
  356. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  357. return SemIR::ConstantId::Error;
  358. }
  359. return MakeConstantResult(eval_context.context(), transform_fn(typed_inst),
  360. phase);
  361. }
  362. return MakeNonConstantResult(phase);
  363. }
  364. // Same as above but with an identity transform function.
  365. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  366. static auto RebuildAndValidateIfFieldsAreConstant(
  367. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  368. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  369. return RebuildIfFieldsAreConstantImpl(eval_context, inst, validate_fn,
  370. std::identity{}, each_field_id...);
  371. }
  372. // Same as above but with no validation step.
  373. template <typename InstT, typename TransformFn, typename... EachFieldIdT>
  374. static auto TransformIfFieldsAreConstant(EvalContext& eval_context,
  375. SemIR::Inst inst,
  376. TransformFn transform_fn,
  377. EachFieldIdT InstT::*... each_field_id)
  378. -> SemIR::ConstantId {
  379. return RebuildIfFieldsAreConstantImpl(
  380. eval_context, inst, [](...) { return true; }, transform_fn,
  381. each_field_id...);
  382. }
  383. // Same as above but with no validation or transform step.
  384. template <typename InstT, typename... EachFieldIdT>
  385. static auto RebuildIfFieldsAreConstant(EvalContext& eval_context,
  386. SemIR::Inst inst,
  387. EachFieldIdT InstT::*... each_field_id)
  388. -> SemIR::ConstantId {
  389. return RebuildIfFieldsAreConstantImpl(
  390. eval_context, inst, [](...) { return true; }, std::identity{},
  391. each_field_id...);
  392. }
  393. // Rebuilds the given aggregate initialization instruction as a corresponding
  394. // constant aggregate value, if its elements are all constants.
  395. static auto RebuildInitAsValue(EvalContext& eval_context, SemIR::Inst inst,
  396. SemIR::InstKind value_kind)
  397. -> SemIR::ConstantId {
  398. return TransformIfFieldsAreConstant(
  399. eval_context, inst,
  400. [&](SemIR::AnyAggregateInit result) {
  401. return SemIR::AnyAggregateValue{.kind = value_kind,
  402. .type_id = result.type_id,
  403. .elements_id = result.elements_id};
  404. },
  405. &SemIR::AnyAggregateInit::type_id, &SemIR::AnyAggregateInit::elements_id);
  406. }
  407. // Performs an access into an aggregate, retrieving the specified element.
  408. static auto PerformAggregateAccess(EvalContext& eval_context, SemIR::Inst inst)
  409. -> SemIR::ConstantId {
  410. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  411. Phase phase = Phase::Template;
  412. if (auto aggregate_id =
  413. GetConstantValue(eval_context, access_inst.aggregate_id, &phase);
  414. aggregate_id.is_valid()) {
  415. if (auto aggregate =
  416. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(
  417. aggregate_id)) {
  418. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  419. auto index = static_cast<size_t>(access_inst.index.index);
  420. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  421. // `Phase` is not used here. If this element is a template constant, then
  422. // so is the result of indexing, even if the aggregate also contains a
  423. // symbolic context.
  424. return eval_context.GetConstantValue(elements[index]);
  425. } else {
  426. CARBON_CHECK(phase != Phase::Template,
  427. "Failed to evaluate template constant {0}", inst);
  428. }
  429. }
  430. return MakeNonConstantResult(phase);
  431. }
  432. // Performs an index into a homogeneous aggregate, retrieving the specified
  433. // element.
  434. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::Inst inst)
  435. -> SemIR::ConstantId {
  436. auto index_inst = inst.As<SemIR::ArrayIndex>();
  437. Phase phase = Phase::Template;
  438. auto index_id = GetConstantValue(eval_context, index_inst.index_id, &phase);
  439. if (!index_id.is_valid()) {
  440. return MakeNonConstantResult(phase);
  441. }
  442. auto index = eval_context.insts().TryGetAs<SemIR::IntLiteral>(index_id);
  443. if (!index) {
  444. CARBON_CHECK(phase != Phase::Template,
  445. "Template constant integer should be a literal");
  446. return MakeNonConstantResult(phase);
  447. }
  448. // Array indexing is invalid if the index is constant and out of range,
  449. // regardless of whether the array itself is constant.
  450. const auto& index_val = eval_context.ints().Get(index->int_id);
  451. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  452. eval_context.insts().Get(index_inst.array_id).type_id());
  453. if (auto array_type =
  454. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  455. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntLiteral>(
  456. array_type->bound_id)) {
  457. // This awkward call to `getZExtValue` is a workaround for APInt not
  458. // supporting comparisons between integers of different bit widths.
  459. if (index_val.getActiveBits() > 64 ||
  460. eval_context.ints()
  461. .Get(bound->int_id)
  462. .ule(index_val.getZExtValue())) {
  463. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  464. "array index `{0}` is past the end of type {1}",
  465. TypedInt, SemIR::TypeId);
  466. eval_context.emitter().Emit(
  467. index_inst.index_id, ArrayIndexOutOfBounds,
  468. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  469. return SemIR::ConstantId::Error;
  470. }
  471. }
  472. }
  473. auto aggregate_id =
  474. GetConstantValue(eval_context, index_inst.array_id, &phase);
  475. if (!aggregate_id.is_valid()) {
  476. return MakeNonConstantResult(phase);
  477. }
  478. auto aggregate =
  479. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  480. if (!aggregate) {
  481. CARBON_CHECK(phase != Phase::Template,
  482. "Unexpected representation for template constant aggregate");
  483. return MakeNonConstantResult(phase);
  484. }
  485. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  486. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  487. }
  488. // Enforces that an integer type has a valid bit width.
  489. static auto ValidateIntType(Context& context, SemIRLoc loc,
  490. SemIR::IntType result) -> bool {
  491. auto bit_width =
  492. context.insts().TryGetAs<SemIR::IntLiteral>(result.bit_width_id);
  493. if (!bit_width) {
  494. // Symbolic bit width.
  495. return true;
  496. }
  497. const auto& bit_width_val = context.ints().Get(bit_width->int_id);
  498. if (bit_width_val.isZero() ||
  499. (context.types().IsSignedInt(bit_width->type_id) &&
  500. bit_width_val.isNegative())) {
  501. CARBON_DIAGNOSTIC(IntWidthNotPositive, Error,
  502. "integer type width of {0} is not positive", TypedInt);
  503. context.emitter().Emit(
  504. loc, IntWidthNotPositive,
  505. {.type = bit_width->type_id, .value = bit_width_val});
  506. return false;
  507. }
  508. // TODO: Pick a maximum size and document it in the design. For now
  509. // we use 2^^23, because that's the largest size that LLVM supports.
  510. constexpr int MaxIntWidth = 1 << 23;
  511. if (bit_width_val.ugt(MaxIntWidth)) {
  512. CARBON_DIAGNOSTIC(IntWidthTooLarge, Error,
  513. "integer type width of {0} is greater than the "
  514. "maximum supported width of {1}",
  515. TypedInt, int);
  516. context.emitter().Emit(loc, IntWidthTooLarge,
  517. {.type = bit_width->type_id, .value = bit_width_val},
  518. MaxIntWidth);
  519. return false;
  520. }
  521. return true;
  522. }
  523. // Forms a constant int type as an evaluation result. Requires that width_id is
  524. // constant.
  525. static auto MakeIntTypeResult(Context& context, SemIRLoc loc,
  526. SemIR::IntKind int_kind, SemIR::InstId width_id,
  527. Phase phase) -> SemIR::ConstantId {
  528. auto result = SemIR::IntType{
  529. .type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::TypeType),
  530. .int_kind = int_kind,
  531. .bit_width_id = width_id};
  532. if (!ValidateIntType(context, loc, result)) {
  533. return SemIR::ConstantId::Error;
  534. }
  535. return MakeConstantResult(context, result, phase);
  536. }
  537. // Enforces that the bit width is 64 for a float.
  538. static auto ValidateFloatBitWidth(Context& context, SemIRLoc loc,
  539. SemIR::InstId inst_id) -> bool {
  540. auto inst = context.insts().GetAs<SemIR::IntLiteral>(inst_id);
  541. if (context.ints().Get(inst.int_id) == 64) {
  542. return true;
  543. }
  544. CARBON_DIAGNOSTIC(CompileTimeFloatBitWidth, Error, "bit width must be 64");
  545. context.emitter().Emit(loc, CompileTimeFloatBitWidth);
  546. return false;
  547. }
  548. // Enforces that a float type has a valid bit width.
  549. static auto ValidateFloatType(Context& context, SemIRLoc loc,
  550. SemIR::FloatType result) -> bool {
  551. auto bit_width =
  552. context.insts().TryGetAs<SemIR::IntLiteral>(result.bit_width_id);
  553. if (!bit_width) {
  554. // Symbolic bit width.
  555. return true;
  556. }
  557. return ValidateFloatBitWidth(context, loc, result.bit_width_id);
  558. }
  559. // Issues a diagnostic for a compile-time division by zero.
  560. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  561. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  562. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  563. }
  564. // Performs a builtin unary integer -> integer operation.
  565. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  566. SemIR::BuiltinFunctionKind builtin_kind,
  567. SemIR::InstId arg_id)
  568. -> SemIR::ConstantId {
  569. auto op = context.insts().GetAs<SemIR::IntLiteral>(arg_id);
  570. auto op_val = context.ints().Get(op.int_id);
  571. switch (builtin_kind) {
  572. case SemIR::BuiltinFunctionKind::IntSNegate:
  573. if (context.types().IsSignedInt(op.type_id) &&
  574. op_val.isMinSignedValue()) {
  575. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  576. "integer overflow in negation of {0}", TypedInt);
  577. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  578. {.type = op.type_id, .value = op_val});
  579. }
  580. op_val.negate();
  581. break;
  582. case SemIR::BuiltinFunctionKind::IntUNegate:
  583. op_val.negate();
  584. break;
  585. case SemIR::BuiltinFunctionKind::IntComplement:
  586. op_val.flipAllBits();
  587. break;
  588. default:
  589. CARBON_FATAL("Unexpected builtin kind");
  590. }
  591. return MakeIntResult(context, op.type_id, std::move(op_val));
  592. }
  593. // Performs a builtin binary integer -> integer operation.
  594. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  595. SemIR::BuiltinFunctionKind builtin_kind,
  596. SemIR::InstId lhs_id,
  597. SemIR::InstId rhs_id)
  598. -> SemIR::ConstantId {
  599. auto lhs = context.insts().GetAs<SemIR::IntLiteral>(lhs_id);
  600. auto rhs = context.insts().GetAs<SemIR::IntLiteral>(rhs_id);
  601. const auto& lhs_val = context.ints().Get(lhs.int_id);
  602. const auto& rhs_val = context.ints().Get(rhs.int_id);
  603. // Check for division by zero.
  604. switch (builtin_kind) {
  605. case SemIR::BuiltinFunctionKind::IntSDiv:
  606. case SemIR::BuiltinFunctionKind::IntSMod:
  607. case SemIR::BuiltinFunctionKind::IntUDiv:
  608. case SemIR::BuiltinFunctionKind::IntUMod:
  609. if (rhs_val.isZero()) {
  610. DiagnoseDivisionByZero(context, loc);
  611. return SemIR::ConstantId::Error;
  612. }
  613. break;
  614. default:
  615. break;
  616. }
  617. bool overflow = false;
  618. llvm::APInt result_val;
  619. Lex::TokenKind op_token = Lex::TokenKind::Not;
  620. switch (builtin_kind) {
  621. // Arithmetic.
  622. case SemIR::BuiltinFunctionKind::IntSAdd:
  623. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  624. op_token = Lex::TokenKind::Plus;
  625. break;
  626. case SemIR::BuiltinFunctionKind::IntSSub:
  627. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  628. op_token = Lex::TokenKind::Minus;
  629. break;
  630. case SemIR::BuiltinFunctionKind::IntSMul:
  631. result_val = lhs_val.smul_ov(rhs_val, overflow);
  632. op_token = Lex::TokenKind::Star;
  633. break;
  634. case SemIR::BuiltinFunctionKind::IntSDiv:
  635. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  636. op_token = Lex::TokenKind::Slash;
  637. break;
  638. case SemIR::BuiltinFunctionKind::IntSMod:
  639. result_val = lhs_val.srem(rhs_val);
  640. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  641. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  642. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  643. op_token = Lex::TokenKind::Percent;
  644. break;
  645. case SemIR::BuiltinFunctionKind::IntUAdd:
  646. result_val = lhs_val + rhs_val;
  647. op_token = Lex::TokenKind::Plus;
  648. break;
  649. case SemIR::BuiltinFunctionKind::IntUSub:
  650. result_val = lhs_val - rhs_val;
  651. op_token = Lex::TokenKind::Minus;
  652. break;
  653. case SemIR::BuiltinFunctionKind::IntUMul:
  654. result_val = lhs_val * rhs_val;
  655. op_token = Lex::TokenKind::Star;
  656. break;
  657. case SemIR::BuiltinFunctionKind::IntUDiv:
  658. result_val = lhs_val.udiv(rhs_val);
  659. op_token = Lex::TokenKind::Slash;
  660. break;
  661. case SemIR::BuiltinFunctionKind::IntUMod:
  662. result_val = lhs_val.urem(rhs_val);
  663. op_token = Lex::TokenKind::Percent;
  664. break;
  665. // Bitwise.
  666. case SemIR::BuiltinFunctionKind::IntAnd:
  667. result_val = lhs_val & rhs_val;
  668. op_token = Lex::TokenKind::And;
  669. break;
  670. case SemIR::BuiltinFunctionKind::IntOr:
  671. result_val = lhs_val | rhs_val;
  672. op_token = Lex::TokenKind::Pipe;
  673. break;
  674. case SemIR::BuiltinFunctionKind::IntXor:
  675. result_val = lhs_val ^ rhs_val;
  676. op_token = Lex::TokenKind::Caret;
  677. break;
  678. // Bit shift.
  679. case SemIR::BuiltinFunctionKind::IntLeftShift:
  680. case SemIR::BuiltinFunctionKind::IntRightShift:
  681. if (rhs_val.uge(lhs_val.getBitWidth()) ||
  682. (rhs_val.isNegative() && context.types().IsSignedInt(rhs.type_id))) {
  683. CARBON_DIAGNOSTIC(
  684. CompileTimeShiftOutOfRange, Error,
  685. "shift distance not in range [0, {0}) in {1} {2:<<|>>} {3}",
  686. unsigned, TypedInt, BoolAsSelect, TypedInt);
  687. context.emitter().Emit(
  688. loc, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  689. {.type = lhs.type_id, .value = lhs_val},
  690. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  691. {.type = rhs.type_id, .value = rhs_val});
  692. // TODO: Is it useful to recover by returning 0 or -1?
  693. return SemIR::ConstantId::Error;
  694. }
  695. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  696. result_val = lhs_val.shl(rhs_val);
  697. } else if (context.types().IsSignedInt(lhs.type_id)) {
  698. result_val = lhs_val.ashr(rhs_val);
  699. } else {
  700. result_val = lhs_val.lshr(rhs_val);
  701. }
  702. break;
  703. default:
  704. CARBON_FATAL("Unexpected operation kind.");
  705. }
  706. if (overflow) {
  707. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  708. "integer overflow in calculation {0} {1} {2}", TypedInt,
  709. Lex::TokenKind, TypedInt);
  710. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  711. {.type = lhs.type_id, .value = lhs_val}, op_token,
  712. {.type = rhs.type_id, .value = rhs_val});
  713. }
  714. return MakeIntResult(context, lhs.type_id, std::move(result_val));
  715. }
  716. // Performs a builtin integer comparison.
  717. static auto PerformBuiltinIntComparison(Context& context,
  718. SemIR::BuiltinFunctionKind builtin_kind,
  719. SemIR::InstId lhs_id,
  720. SemIR::InstId rhs_id,
  721. SemIR::TypeId bool_type_id)
  722. -> SemIR::ConstantId {
  723. auto lhs = context.insts().GetAs<SemIR::IntLiteral>(lhs_id);
  724. const auto& lhs_val = context.ints().Get(lhs.int_id);
  725. const auto& rhs_val = context.ints().Get(
  726. context.insts().GetAs<SemIR::IntLiteral>(rhs_id).int_id);
  727. bool is_signed = context.types().IsSignedInt(lhs.type_id);
  728. bool result;
  729. switch (builtin_kind) {
  730. case SemIR::BuiltinFunctionKind::IntEq:
  731. result = (lhs_val == rhs_val);
  732. break;
  733. case SemIR::BuiltinFunctionKind::IntNeq:
  734. result = (lhs_val != rhs_val);
  735. break;
  736. case SemIR::BuiltinFunctionKind::IntLess:
  737. result = is_signed ? lhs_val.slt(rhs_val) : lhs_val.ult(rhs_val);
  738. break;
  739. case SemIR::BuiltinFunctionKind::IntLessEq:
  740. result = is_signed ? lhs_val.sle(rhs_val) : lhs_val.ule(rhs_val);
  741. break;
  742. case SemIR::BuiltinFunctionKind::IntGreater:
  743. result = is_signed ? lhs_val.sgt(rhs_val) : lhs_val.sgt(rhs_val);
  744. break;
  745. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  746. result = is_signed ? lhs_val.sge(rhs_val) : lhs_val.sge(rhs_val);
  747. break;
  748. default:
  749. CARBON_FATAL("Unexpected operation kind.");
  750. }
  751. return MakeBoolResult(context, bool_type_id, result);
  752. }
  753. // Performs a builtin unary float -> float operation.
  754. static auto PerformBuiltinUnaryFloatOp(Context& context,
  755. SemIR::BuiltinFunctionKind builtin_kind,
  756. SemIR::InstId arg_id)
  757. -> SemIR::ConstantId {
  758. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  759. auto op_val = context.floats().Get(op.float_id);
  760. switch (builtin_kind) {
  761. case SemIR::BuiltinFunctionKind::FloatNegate:
  762. op_val.changeSign();
  763. break;
  764. default:
  765. CARBON_FATAL("Unexpected builtin kind");
  766. }
  767. return MakeFloatResult(context, op.type_id, std::move(op_val));
  768. }
  769. // Performs a builtin binary float -> float operation.
  770. static auto PerformBuiltinBinaryFloatOp(Context& context,
  771. SemIR::BuiltinFunctionKind builtin_kind,
  772. SemIR::InstId lhs_id,
  773. SemIR::InstId rhs_id)
  774. -> SemIR::ConstantId {
  775. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  776. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  777. auto lhs_val = context.floats().Get(lhs.float_id);
  778. auto rhs_val = context.floats().Get(rhs.float_id);
  779. llvm::APFloat result_val(lhs_val.getSemantics());
  780. switch (builtin_kind) {
  781. case SemIR::BuiltinFunctionKind::FloatAdd:
  782. result_val = lhs_val + rhs_val;
  783. break;
  784. case SemIR::BuiltinFunctionKind::FloatSub:
  785. result_val = lhs_val - rhs_val;
  786. break;
  787. case SemIR::BuiltinFunctionKind::FloatMul:
  788. result_val = lhs_val * rhs_val;
  789. break;
  790. case SemIR::BuiltinFunctionKind::FloatDiv:
  791. result_val = lhs_val / rhs_val;
  792. break;
  793. default:
  794. CARBON_FATAL("Unexpected operation kind.");
  795. }
  796. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  797. }
  798. // Performs a builtin float comparison.
  799. static auto PerformBuiltinFloatComparison(
  800. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  801. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  802. -> SemIR::ConstantId {
  803. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  804. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  805. const auto& lhs_val = context.floats().Get(lhs.float_id);
  806. const auto& rhs_val = context.floats().Get(rhs.float_id);
  807. bool result;
  808. switch (builtin_kind) {
  809. case SemIR::BuiltinFunctionKind::FloatEq:
  810. result = (lhs_val == rhs_val);
  811. break;
  812. case SemIR::BuiltinFunctionKind::FloatNeq:
  813. result = (lhs_val != rhs_val);
  814. break;
  815. case SemIR::BuiltinFunctionKind::FloatLess:
  816. result = lhs_val < rhs_val;
  817. break;
  818. case SemIR::BuiltinFunctionKind::FloatLessEq:
  819. result = lhs_val <= rhs_val;
  820. break;
  821. case SemIR::BuiltinFunctionKind::FloatGreater:
  822. result = lhs_val > rhs_val;
  823. break;
  824. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  825. result = lhs_val >= rhs_val;
  826. break;
  827. default:
  828. CARBON_FATAL("Unexpected operation kind.");
  829. }
  830. return MakeBoolResult(context, bool_type_id, result);
  831. }
  832. // Returns a constant for a call to a builtin function.
  833. static auto MakeConstantForBuiltinCall(Context& context, SemIRLoc loc,
  834. SemIR::Call call,
  835. SemIR::BuiltinFunctionKind builtin_kind,
  836. llvm::ArrayRef<SemIR::InstId> arg_ids,
  837. Phase phase) -> SemIR::ConstantId {
  838. switch (builtin_kind) {
  839. case SemIR::BuiltinFunctionKind::None:
  840. CARBON_FATAL("Not a builtin function.");
  841. case SemIR::BuiltinFunctionKind::PrintInt: {
  842. // Providing a constant result would allow eliding the function call.
  843. return SemIR::ConstantId::NotConstant;
  844. }
  845. case SemIR::BuiltinFunctionKind::BigIntMakeType: {
  846. return context.constant_values().Get(SemIR::InstId::BuiltinBigIntType);
  847. }
  848. case SemIR::BuiltinFunctionKind::IntMakeType32: {
  849. return context.constant_values().Get(SemIR::InstId::BuiltinIntType);
  850. }
  851. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  852. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  853. phase);
  854. }
  855. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  856. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  857. arg_ids[0], phase);
  858. }
  859. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  860. // TODO: Support a symbolic constant width.
  861. if (phase != Phase::Template) {
  862. break;
  863. }
  864. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  865. return SemIR::ConstantId::Error;
  866. }
  867. return context.constant_values().Get(SemIR::InstId::BuiltinFloatType);
  868. }
  869. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  870. return context.constant_values().Get(SemIR::InstId::BuiltinBoolType);
  871. }
  872. // Unary integer -> integer operations.
  873. case SemIR::BuiltinFunctionKind::IntSNegate:
  874. case SemIR::BuiltinFunctionKind::IntUNegate:
  875. case SemIR::BuiltinFunctionKind::IntComplement: {
  876. if (phase != Phase::Template) {
  877. break;
  878. }
  879. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  880. }
  881. // Binary integer -> integer operations.
  882. case SemIR::BuiltinFunctionKind::IntSAdd:
  883. case SemIR::BuiltinFunctionKind::IntSSub:
  884. case SemIR::BuiltinFunctionKind::IntSMul:
  885. case SemIR::BuiltinFunctionKind::IntSDiv:
  886. case SemIR::BuiltinFunctionKind::IntSMod:
  887. case SemIR::BuiltinFunctionKind::IntUAdd:
  888. case SemIR::BuiltinFunctionKind::IntUSub:
  889. case SemIR::BuiltinFunctionKind::IntUMul:
  890. case SemIR::BuiltinFunctionKind::IntUDiv:
  891. case SemIR::BuiltinFunctionKind::IntUMod:
  892. case SemIR::BuiltinFunctionKind::IntAnd:
  893. case SemIR::BuiltinFunctionKind::IntOr:
  894. case SemIR::BuiltinFunctionKind::IntXor:
  895. case SemIR::BuiltinFunctionKind::IntLeftShift:
  896. case SemIR::BuiltinFunctionKind::IntRightShift: {
  897. if (phase != Phase::Template) {
  898. break;
  899. }
  900. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  901. arg_ids[1]);
  902. }
  903. // Integer comparisons.
  904. case SemIR::BuiltinFunctionKind::IntEq:
  905. case SemIR::BuiltinFunctionKind::IntNeq:
  906. case SemIR::BuiltinFunctionKind::IntLess:
  907. case SemIR::BuiltinFunctionKind::IntLessEq:
  908. case SemIR::BuiltinFunctionKind::IntGreater:
  909. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  910. if (phase != Phase::Template) {
  911. break;
  912. }
  913. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  914. arg_ids[1], call.type_id);
  915. }
  916. // Unary float -> float operations.
  917. case SemIR::BuiltinFunctionKind::FloatNegate: {
  918. if (phase != Phase::Template) {
  919. break;
  920. }
  921. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  922. }
  923. // Binary float -> float operations.
  924. case SemIR::BuiltinFunctionKind::FloatAdd:
  925. case SemIR::BuiltinFunctionKind::FloatSub:
  926. case SemIR::BuiltinFunctionKind::FloatMul:
  927. case SemIR::BuiltinFunctionKind::FloatDiv: {
  928. if (phase != Phase::Template) {
  929. break;
  930. }
  931. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  932. arg_ids[1]);
  933. }
  934. // Float comparisons.
  935. case SemIR::BuiltinFunctionKind::FloatEq:
  936. case SemIR::BuiltinFunctionKind::FloatNeq:
  937. case SemIR::BuiltinFunctionKind::FloatLess:
  938. case SemIR::BuiltinFunctionKind::FloatLessEq:
  939. case SemIR::BuiltinFunctionKind::FloatGreater:
  940. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  941. if (phase != Phase::Template) {
  942. break;
  943. }
  944. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  945. arg_ids[1], call.type_id);
  946. }
  947. }
  948. return SemIR::ConstantId::NotConstant;
  949. }
  950. // Makes a constant for a call instruction.
  951. static auto MakeConstantForCall(EvalContext& eval_context, SemIRLoc loc,
  952. SemIR::Call call) -> SemIR::ConstantId {
  953. Phase phase = Phase::Template;
  954. // A call with an invalid argument list is used to represent an erroneous
  955. // call.
  956. //
  957. // TODO: Use a better representation for this.
  958. if (call.args_id == SemIR::InstBlockId::Invalid) {
  959. return SemIR::ConstantId::Error;
  960. }
  961. // If the callee or return type isn't constant, this is not a constant call.
  962. if (!ReplaceFieldWithConstantValue(eval_context, &call,
  963. &SemIR::Call::callee_id, &phase) ||
  964. !ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  965. &phase)) {
  966. return SemIR::ConstantId::NotConstant;
  967. }
  968. auto callee_function =
  969. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  970. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  971. if (callee_function.function_id.is_valid()) {
  972. // Calls to builtins might be constant.
  973. builtin_kind = eval_context.functions()
  974. .Get(callee_function.function_id)
  975. .builtin_function_kind;
  976. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  977. // TODO: Eventually we'll want to treat some kinds of non-builtin
  978. // functions as producing constants.
  979. return SemIR::ConstantId::NotConstant;
  980. }
  981. } else {
  982. // Calls to non-functions, such as calls to generic entity names, might be
  983. // constant.
  984. }
  985. // If the arguments aren't constant, this is not a constant call.
  986. if (!ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  987. &phase)) {
  988. return SemIR::ConstantId::NotConstant;
  989. }
  990. if (phase == Phase::UnknownDueToError) {
  991. return SemIR::ConstantId::Error;
  992. }
  993. // Handle calls to builtins.
  994. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  995. return MakeConstantForBuiltinCall(
  996. eval_context.context(), loc, call, builtin_kind,
  997. eval_context.inst_blocks().Get(call.args_id), phase);
  998. }
  999. return SemIR::ConstantId::NotConstant;
  1000. }
  1001. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1002. static auto TryEvalInstInContext(EvalContext& eval_context,
  1003. SemIR::InstId inst_id, SemIR::Inst inst)
  1004. -> SemIR::ConstantId {
  1005. // TODO: Ensure we have test coverage for each of these cases that can result
  1006. // in a constant, once those situations are all reachable.
  1007. CARBON_KIND_SWITCH(inst) {
  1008. // These cases are constants if their operands are.
  1009. case SemIR::AddrOf::Kind:
  1010. return RebuildIfFieldsAreConstant(eval_context, inst,
  1011. &SemIR::AddrOf::type_id,
  1012. &SemIR::AddrOf::lvalue_id);
  1013. case CARBON_KIND(SemIR::ArrayType array_type): {
  1014. return RebuildAndValidateIfFieldsAreConstant(
  1015. eval_context, inst,
  1016. [&](SemIR::ArrayType result) {
  1017. auto bound_id = array_type.bound_id;
  1018. auto int_bound = eval_context.insts().TryGetAs<SemIR::IntLiteral>(
  1019. result.bound_id);
  1020. if (!int_bound) {
  1021. // TODO: Permit symbolic array bounds. This will require fixing
  1022. // callers of `GetArrayBoundValue`.
  1023. eval_context.context().TODO(bound_id, "symbolic array bound");
  1024. return false;
  1025. }
  1026. // TODO: We should check that the size of the resulting array type
  1027. // fits in 64 bits, not just that the bound does. Should we use a
  1028. // 32-bit limit for 32-bit targets?
  1029. const auto& bound_val = eval_context.ints().Get(int_bound->int_id);
  1030. if (eval_context.types().IsSignedInt(int_bound->type_id) &&
  1031. bound_val.isNegative()) {
  1032. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  1033. "array bound of {0} is negative", TypedInt);
  1034. eval_context.emitter().Emit(
  1035. bound_id, ArrayBoundNegative,
  1036. {.type = int_bound->type_id, .value = bound_val});
  1037. return false;
  1038. }
  1039. if (bound_val.getActiveBits() > 64) {
  1040. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  1041. "array bound of {0} is too large", TypedInt);
  1042. eval_context.emitter().Emit(
  1043. bound_id, ArrayBoundTooLarge,
  1044. {.type = int_bound->type_id, .value = bound_val});
  1045. return false;
  1046. }
  1047. return true;
  1048. },
  1049. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  1050. }
  1051. case SemIR::AssociatedEntity::Kind:
  1052. return RebuildIfFieldsAreConstant(eval_context, inst,
  1053. &SemIR::AssociatedEntity::type_id);
  1054. case SemIR::AssociatedEntityType::Kind:
  1055. return RebuildIfFieldsAreConstant(
  1056. eval_context, inst, &SemIR::AssociatedEntityType::interface_type_id,
  1057. &SemIR::AssociatedEntityType::entity_type_id);
  1058. case SemIR::BoundMethod::Kind:
  1059. return RebuildIfFieldsAreConstant(
  1060. eval_context, inst, &SemIR::BoundMethod::type_id,
  1061. &SemIR::BoundMethod::object_id, &SemIR::BoundMethod::function_id);
  1062. case SemIR::ClassType::Kind:
  1063. return RebuildIfFieldsAreConstant(eval_context, inst,
  1064. &SemIR::ClassType::specific_id);
  1065. case SemIR::CompleteTypeWitness::Kind:
  1066. return RebuildIfFieldsAreConstant(
  1067. eval_context, inst, &SemIR::CompleteTypeWitness::object_repr_id);
  1068. case SemIR::FunctionType::Kind:
  1069. return RebuildIfFieldsAreConstant(eval_context, inst,
  1070. &SemIR::FunctionType::specific_id);
  1071. case SemIR::GenericClassType::Kind:
  1072. return RebuildIfFieldsAreConstant(
  1073. eval_context, inst, &SemIR::GenericClassType::enclosing_specific_id);
  1074. case SemIR::GenericInterfaceType::Kind:
  1075. return RebuildIfFieldsAreConstant(
  1076. eval_context, inst,
  1077. &SemIR::GenericInterfaceType::enclosing_specific_id);
  1078. case SemIR::InterfaceType::Kind:
  1079. return RebuildIfFieldsAreConstant(eval_context, inst,
  1080. &SemIR::InterfaceType::specific_id);
  1081. case SemIR::InterfaceWitness::Kind:
  1082. return RebuildIfFieldsAreConstant(eval_context, inst,
  1083. &SemIR::InterfaceWitness::elements_id);
  1084. case CARBON_KIND(SemIR::IntType int_type): {
  1085. return RebuildAndValidateIfFieldsAreConstant(
  1086. eval_context, inst,
  1087. [&](SemIR::IntType result) {
  1088. return ValidateIntType(
  1089. eval_context.context(),
  1090. inst_id.is_valid() ? inst_id : int_type.bit_width_id, result);
  1091. },
  1092. &SemIR::IntType::bit_width_id);
  1093. }
  1094. case SemIR::PointerType::Kind:
  1095. return RebuildIfFieldsAreConstant(eval_context, inst,
  1096. &SemIR::PointerType::pointee_id);
  1097. case CARBON_KIND(SemIR::FloatType float_type): {
  1098. return RebuildAndValidateIfFieldsAreConstant(
  1099. eval_context, inst,
  1100. [&](SemIR::FloatType result) {
  1101. return ValidateFloatType(eval_context.context(),
  1102. float_type.bit_width_id, result);
  1103. },
  1104. &SemIR::FloatType::bit_width_id);
  1105. }
  1106. case SemIR::SpecificFunction::Kind:
  1107. return RebuildIfFieldsAreConstant(eval_context, inst,
  1108. &SemIR::SpecificFunction::callee_id,
  1109. &SemIR::SpecificFunction::specific_id);
  1110. case SemIR::StructType::Kind:
  1111. return RebuildIfFieldsAreConstant(eval_context, inst,
  1112. &SemIR::StructType::fields_id);
  1113. case SemIR::StructTypeField::Kind:
  1114. return RebuildIfFieldsAreConstant(eval_context, inst,
  1115. &SemIR::StructTypeField::field_type_id);
  1116. case SemIR::StructValue::Kind:
  1117. return RebuildIfFieldsAreConstant(eval_context, inst,
  1118. &SemIR::StructValue::type_id,
  1119. &SemIR::StructValue::elements_id);
  1120. case SemIR::TupleType::Kind:
  1121. return RebuildIfFieldsAreConstant(eval_context, inst,
  1122. &SemIR::TupleType::elements_id);
  1123. case SemIR::TupleValue::Kind:
  1124. return RebuildIfFieldsAreConstant(eval_context, inst,
  1125. &SemIR::TupleValue::type_id,
  1126. &SemIR::TupleValue::elements_id);
  1127. case SemIR::UnboundElementType::Kind:
  1128. return RebuildIfFieldsAreConstant(
  1129. eval_context, inst, &SemIR::UnboundElementType::class_type_id,
  1130. &SemIR::UnboundElementType::element_type_id);
  1131. // Initializers evaluate to a value of the object representation.
  1132. case SemIR::ArrayInit::Kind:
  1133. // TODO: Add an `ArrayValue` to represent a constant array object
  1134. // representation instead of using a `TupleValue`.
  1135. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1136. case SemIR::ClassInit::Kind:
  1137. // TODO: Add a `ClassValue` to represent a constant class object
  1138. // representation instead of using a `StructValue`.
  1139. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1140. case SemIR::StructInit::Kind:
  1141. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1142. case SemIR::TupleInit::Kind:
  1143. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1144. case SemIR::BuiltinInst::Kind:
  1145. // Builtins are always template constants.
  1146. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1147. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  1148. return TransformIfFieldsAreConstant(
  1149. eval_context, fn_decl,
  1150. [&](SemIR::FunctionDecl result) {
  1151. return SemIR::StructValue{.type_id = result.type_id,
  1152. .elements_id = SemIR::InstBlockId::Empty};
  1153. },
  1154. &SemIR::FunctionDecl::type_id);
  1155. }
  1156. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  1157. // If the class has generic parameters, we don't produce a class type, but
  1158. // a callable whose return value is a class type.
  1159. if (eval_context.classes().Get(class_decl.class_id).has_parameters()) {
  1160. return TransformIfFieldsAreConstant(
  1161. eval_context, class_decl,
  1162. [&](SemIR::ClassDecl result) {
  1163. return SemIR::StructValue{
  1164. .type_id = result.type_id,
  1165. .elements_id = SemIR::InstBlockId::Empty};
  1166. },
  1167. &SemIR::ClassDecl::type_id);
  1168. }
  1169. // A non-generic class declaration evaluates to the class type.
  1170. return MakeConstantResult(
  1171. eval_context.context(),
  1172. SemIR::ClassType{.type_id = SemIR::TypeId::TypeType,
  1173. .class_id = class_decl.class_id,
  1174. .specific_id = SemIR::SpecificId::Invalid},
  1175. Phase::Template);
  1176. }
  1177. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  1178. // If the interface has generic parameters, we don't produce an interface
  1179. // type, but a callable whose return value is an interface type.
  1180. if (eval_context.interfaces()
  1181. .Get(interface_decl.interface_id)
  1182. .has_parameters()) {
  1183. return TransformIfFieldsAreConstant(
  1184. eval_context, interface_decl,
  1185. [&](SemIR::InterfaceDecl result) {
  1186. return SemIR::StructValue{
  1187. .type_id = result.type_id,
  1188. .elements_id = SemIR::InstBlockId::Empty};
  1189. },
  1190. &SemIR::InterfaceDecl::type_id);
  1191. }
  1192. // A non-generic interface declaration evaluates to the interface type.
  1193. return MakeConstantResult(
  1194. eval_context.context(),
  1195. SemIR::InterfaceType{.type_id = SemIR::TypeId::TypeType,
  1196. .interface_id = interface_decl.interface_id,
  1197. .specific_id = SemIR::SpecificId::Invalid},
  1198. Phase::Template);
  1199. }
  1200. case CARBON_KIND(SemIR::SpecificConstant specific): {
  1201. // Pull the constant value out of the specific.
  1202. return SemIR::GetConstantValueInSpecific(
  1203. eval_context.sem_ir(), specific.specific_id, specific.inst_id);
  1204. }
  1205. // These cases are treated as being the unique canonical definition of the
  1206. // corresponding constant value.
  1207. // TODO: This doesn't properly handle redeclarations. Consider adding a
  1208. // corresponding `Value` inst for each of these cases, or returning the
  1209. // first declaration.
  1210. case SemIR::AssociatedConstantDecl::Kind:
  1211. case SemIR::BaseDecl::Kind:
  1212. case SemIR::FieldDecl::Kind:
  1213. case SemIR::ImplDecl::Kind:
  1214. case SemIR::Namespace::Kind:
  1215. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  1216. case SemIR::BoolLiteral::Kind:
  1217. case SemIR::FloatLiteral::Kind:
  1218. case SemIR::IntLiteral::Kind:
  1219. case SemIR::StringLiteral::Kind:
  1220. // Promote literals to the constant block.
  1221. // TODO: Convert literals into a canonical form. Currently we can form two
  1222. // different `i32` constants with the same value if they are represented
  1223. // by `APInt`s with different bit widths.
  1224. // TODO: Can the type of an IntLiteral or FloatLiteral be symbolic? If so,
  1225. // we may need to rebuild.
  1226. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1227. // The elements of a constant aggregate can be accessed.
  1228. case SemIR::ClassElementAccess::Kind:
  1229. case SemIR::InterfaceWitnessAccess::Kind:
  1230. case SemIR::StructAccess::Kind:
  1231. case SemIR::TupleAccess::Kind:
  1232. return PerformAggregateAccess(eval_context, inst);
  1233. case SemIR::ArrayIndex::Kind:
  1234. return PerformArrayIndex(eval_context, inst);
  1235. case CARBON_KIND(SemIR::Call call): {
  1236. return MakeConstantForCall(eval_context, inst_id, call);
  1237. }
  1238. // TODO: These need special handling.
  1239. case SemIR::BindValue::Kind:
  1240. case SemIR::Deref::Kind:
  1241. case SemIR::ImportRefLoaded::Kind:
  1242. case SemIR::Temporary::Kind:
  1243. case SemIR::TemporaryStorage::Kind:
  1244. case SemIR::ValueAsRef::Kind:
  1245. break;
  1246. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  1247. // TODO: disable constant evaluation of SymbolicBindingPattern once
  1248. // DeduceGenericCallArguments no longer needs implicit params to have
  1249. // constant values.
  1250. const auto& bind_name =
  1251. eval_context.entity_names().Get(bind.entity_name_id);
  1252. // If we know which specific we're evaluating within and this is an
  1253. // argument of that specific, its constant value is the corresponding
  1254. // argument value.
  1255. if (auto value =
  1256. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1257. value.is_valid()) {
  1258. return value;
  1259. }
  1260. // The constant form of a symbolic binding is an idealized form of the
  1261. // original, with no equivalent value.
  1262. bind.entity_name_id =
  1263. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1264. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1265. }
  1266. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  1267. const auto& bind_name =
  1268. eval_context.entity_names().Get(bind.entity_name_id);
  1269. // If we know which specific we're evaluating within and this is an
  1270. // argument of that specific, its constant value is the corresponding
  1271. // argument value.
  1272. if (auto value =
  1273. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1274. value.is_valid()) {
  1275. return value;
  1276. }
  1277. // The constant form of a symbolic binding is an idealized form of the
  1278. // original, with no equivalent value.
  1279. bind.entity_name_id =
  1280. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1281. bind.value_id = SemIR::InstId::Invalid;
  1282. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1283. }
  1284. // These semantic wrappers don't change the constant value.
  1285. case CARBON_KIND(SemIR::AsCompatible inst): {
  1286. return eval_context.GetConstantValue(inst.source_id);
  1287. }
  1288. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  1289. return eval_context.GetConstantValue(typed_inst.value_id);
  1290. }
  1291. case CARBON_KIND(SemIR::ExportDecl typed_inst): {
  1292. return eval_context.GetConstantValue(typed_inst.value_id);
  1293. }
  1294. case CARBON_KIND(SemIR::NameRef typed_inst): {
  1295. return eval_context.GetConstantValue(typed_inst.value_id);
  1296. }
  1297. case CARBON_KIND(SemIR::ParamPattern param_pattern): {
  1298. return eval_context.GetConstantValue(param_pattern.subpattern_id);
  1299. }
  1300. case CARBON_KIND(SemIR::Converted typed_inst): {
  1301. return eval_context.GetConstantValue(typed_inst.result_id);
  1302. }
  1303. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  1304. return eval_context.GetConstantValue(typed_inst.src_id);
  1305. }
  1306. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  1307. return eval_context.GetConstantValue(typed_inst.result_id);
  1308. }
  1309. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  1310. return eval_context.GetConstantValue(typed_inst.init_id);
  1311. }
  1312. case CARBON_KIND(SemIR::FacetTypeAccess typed_inst): {
  1313. // TODO: Once we start tracking the witness in the facet value, remove it
  1314. // here. For now, we model a facet value as just a type.
  1315. return eval_context.GetConstantValue(typed_inst.facet_id);
  1316. }
  1317. case CARBON_KIND(SemIR::WhereExpr typed_inst): {
  1318. // TODO: This currently ignores the requirements and just produces the
  1319. // left-hand type argument to the `where`.
  1320. return eval_context.GetConstantValue(
  1321. eval_context.insts().Get(typed_inst.period_self_id).type_id());
  1322. }
  1323. // `not true` -> `false`, `not false` -> `true`.
  1324. // All other uses of unary `not` are non-constant.
  1325. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  1326. auto const_id = eval_context.GetConstantValue(typed_inst.operand_id);
  1327. auto phase = GetPhase(const_id);
  1328. if (phase == Phase::Template) {
  1329. auto value = eval_context.insts().GetAs<SemIR::BoolLiteral>(
  1330. eval_context.constant_values().GetInstId(const_id));
  1331. return MakeBoolResult(eval_context.context(), value.type_id,
  1332. !value.value.ToBool());
  1333. }
  1334. if (phase == Phase::UnknownDueToError) {
  1335. return SemIR::ConstantId::Error;
  1336. }
  1337. break;
  1338. }
  1339. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1340. // to itself.
  1341. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1342. auto phase = Phase::Template;
  1343. auto inner_id =
  1344. GetConstantValue(eval_context, typed_inst.inner_id, &phase);
  1345. if (eval_context.context().types().Is<SemIR::ConstType>(inner_id)) {
  1346. return eval_context.context().types().GetConstantId(inner_id);
  1347. }
  1348. typed_inst.inner_id = inner_id;
  1349. return MakeConstantResult(eval_context.context(), typed_inst, phase);
  1350. }
  1351. // These cases are either not expressions or not constant.
  1352. case SemIR::AdaptDecl::Kind:
  1353. case SemIR::AddrPattern::Kind:
  1354. case SemIR::Assign::Kind:
  1355. case SemIR::BindName::Kind:
  1356. case SemIR::BindingPattern::Kind:
  1357. case SemIR::BlockArg::Kind:
  1358. case SemIR::Branch::Kind:
  1359. case SemIR::BranchIf::Kind:
  1360. case SemIR::BranchWithArg::Kind:
  1361. case SemIR::ImportDecl::Kind:
  1362. case SemIR::Param::Kind:
  1363. case SemIR::RequirementEquivalent::Kind:
  1364. case SemIR::RequirementImpls::Kind:
  1365. case SemIR::RequirementRewrite::Kind:
  1366. case SemIR::ReturnExpr::Kind:
  1367. case SemIR::Return::Kind:
  1368. case SemIR::StructLiteral::Kind:
  1369. case SemIR::TupleLiteral::Kind:
  1370. case SemIR::VarStorage::Kind:
  1371. break;
  1372. case SemIR::ImportRefUnloaded::Kind:
  1373. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  1374. inst);
  1375. }
  1376. return SemIR::ConstantId::NotConstant;
  1377. }
  1378. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  1379. -> SemIR::ConstantId {
  1380. EvalContext eval_context(context);
  1381. return TryEvalInstInContext(eval_context, inst_id, inst);
  1382. }
  1383. auto TryEvalBlockForSpecific(Context& context, SemIR::SpecificId specific_id,
  1384. SemIR::GenericInstIndex::Region region)
  1385. -> SemIR::InstBlockId {
  1386. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1387. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1388. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1389. llvm::SmallVector<SemIR::InstId> result;
  1390. result.resize(eval_block.size(), SemIR::InstId::Invalid);
  1391. EvalContext eval_context(context, specific_id,
  1392. SpecificEvalInfo{
  1393. .region = region,
  1394. .values = result,
  1395. });
  1396. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1397. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1398. context.insts().Get(inst_id));
  1399. result[i] = context.constant_values().GetInstId(const_id);
  1400. // TODO: If this becomes possible through monomorphization failure, produce
  1401. // a diagnostic and put `SemIR::InstId::BuiltinError` in the table entry.
  1402. CARBON_CHECK(result[i].is_valid());
  1403. }
  1404. return context.inst_blocks().Add(result);
  1405. }
  1406. } // namespace Carbon::Check