eval.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001
  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::NoOp: {
  1259. // Return an empty tuple value.
  1260. auto type_id = GetTupleType(eval_context.context(), {});
  1261. return MakeConstantResult(
  1262. eval_context.context(),
  1263. SemIR::TupleValue{.type_id = type_id,
  1264. .elements_id = SemIR::InstBlockId::Empty},
  1265. phase);
  1266. }
  1267. case SemIR::BuiltinFunctionKind::PrintChar:
  1268. case SemIR::BuiltinFunctionKind::PrintInt:
  1269. case SemIR::BuiltinFunctionKind::ReadChar: {
  1270. // These are runtime-only builtins.
  1271. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1272. return SemIR::ConstantId::NotConstant;
  1273. }
  1274. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1275. CARBON_CHECK(arg_ids.size() == 2);
  1276. auto lhs_facet_type_id = SemIR::FacetTypeId::None;
  1277. auto rhs_facet_type_id = SemIR::FacetTypeId::None;
  1278. for (auto [facet_type_id, type_arg_id] :
  1279. llvm::zip(std::to_array({&lhs_facet_type_id, &rhs_facet_type_id}),
  1280. context.types().GetBlockAsTypeInstIds(arg_ids))) {
  1281. if (auto facet_type =
  1282. context.insts().TryGetAs<SemIR::FacetType>(type_arg_id)) {
  1283. *facet_type_id = facet_type->facet_type_id;
  1284. } else {
  1285. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1286. "non-facet type {0} combined with `&` operator",
  1287. SemIR::TypeId);
  1288. // TODO: Find a location for the lhs or rhs specifically, instead of
  1289. // the whole thing. If that's not possible we can change the text to
  1290. // say if it's referring to the left or the right side for the error.
  1291. // The `arg_id` instruction has no location in it for some reason.
  1292. context.emitter().Emit(
  1293. loc_id, FacetTypeRequiredForTypeAndOperator,
  1294. context.types().GetTypeIdForTypeInstId(type_arg_id));
  1295. }
  1296. }
  1297. // Allow errors to be diagnosed for both sides of the operator before
  1298. // returning here if any error occurred on either side.
  1299. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1300. return SemIR::ErrorInst::SingletonConstantId;
  1301. }
  1302. // Reuse one of the argument instructions if nothing has changed.
  1303. if (lhs_facet_type_id == rhs_facet_type_id) {
  1304. return context.types().GetConstantId(
  1305. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1306. }
  1307. auto info = SemIR::FacetTypeInfo::Combine(
  1308. context.facet_types().Get(lhs_facet_type_id),
  1309. context.facet_types().Get(rhs_facet_type_id));
  1310. info.Canonicalize();
  1311. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1312. }
  1313. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1314. return context.constant_values().Get(
  1315. SemIR::IntLiteralType::SingletonInstId);
  1316. }
  1317. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1318. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Signed,
  1319. arg_ids[0], phase);
  1320. }
  1321. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1322. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Unsigned,
  1323. arg_ids[0], phase);
  1324. }
  1325. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1326. // TODO: Support a symbolic constant width.
  1327. if (phase != Phase::Concrete) {
  1328. break;
  1329. }
  1330. if (!ValidateFloatBitWidth(context, loc_id, arg_ids[0])) {
  1331. return SemIR::ErrorInst::SingletonConstantId;
  1332. }
  1333. return context.constant_values().Get(
  1334. SemIR::LegacyFloatType::SingletonInstId);
  1335. }
  1336. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1337. return context.constant_values().Get(SemIR::BoolType::SingletonInstId);
  1338. }
  1339. // Integer conversions.
  1340. case SemIR::BuiltinFunctionKind::IntConvert: {
  1341. if (phase != Phase::Concrete) {
  1342. return MakeConstantResult(context, call, phase);
  1343. }
  1344. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1345. }
  1346. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1347. if (phase != Phase::Concrete) {
  1348. return MakeConstantResult(context, call, phase);
  1349. }
  1350. return PerformCheckedIntConvert(context, loc_id, arg_ids[0],
  1351. call.type_id);
  1352. }
  1353. // Unary integer -> integer operations.
  1354. case SemIR::BuiltinFunctionKind::IntSNegate:
  1355. case SemIR::BuiltinFunctionKind::IntUNegate:
  1356. case SemIR::BuiltinFunctionKind::IntComplement: {
  1357. if (phase != Phase::Concrete) {
  1358. break;
  1359. }
  1360. return PerformBuiltinUnaryIntOp(context, loc_id, builtin_kind,
  1361. arg_ids[0]);
  1362. }
  1363. // Homogeneous binary integer -> integer operations.
  1364. case SemIR::BuiltinFunctionKind::IntSAdd:
  1365. case SemIR::BuiltinFunctionKind::IntSSub:
  1366. case SemIR::BuiltinFunctionKind::IntSMul:
  1367. case SemIR::BuiltinFunctionKind::IntSDiv:
  1368. case SemIR::BuiltinFunctionKind::IntSMod:
  1369. case SemIR::BuiltinFunctionKind::IntUAdd:
  1370. case SemIR::BuiltinFunctionKind::IntUSub:
  1371. case SemIR::BuiltinFunctionKind::IntUMul:
  1372. case SemIR::BuiltinFunctionKind::IntUDiv:
  1373. case SemIR::BuiltinFunctionKind::IntUMod:
  1374. case SemIR::BuiltinFunctionKind::IntAnd:
  1375. case SemIR::BuiltinFunctionKind::IntOr:
  1376. case SemIR::BuiltinFunctionKind::IntXor: {
  1377. if (phase != Phase::Concrete) {
  1378. break;
  1379. }
  1380. return PerformBuiltinBinaryIntOp(context, loc_id, builtin_kind,
  1381. arg_ids[0], arg_ids[1]);
  1382. }
  1383. // Bit shift operations.
  1384. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1385. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1386. if (phase != Phase::Concrete) {
  1387. break;
  1388. }
  1389. return PerformBuiltinIntShiftOp(context, loc_id, builtin_kind, arg_ids[0],
  1390. arg_ids[1]);
  1391. }
  1392. // Integer comparisons.
  1393. case SemIR::BuiltinFunctionKind::IntEq:
  1394. case SemIR::BuiltinFunctionKind::IntNeq:
  1395. case SemIR::BuiltinFunctionKind::IntLess:
  1396. case SemIR::BuiltinFunctionKind::IntLessEq:
  1397. case SemIR::BuiltinFunctionKind::IntGreater:
  1398. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1399. if (phase != Phase::Concrete) {
  1400. break;
  1401. }
  1402. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1403. arg_ids[1], call.type_id);
  1404. }
  1405. // Unary float -> float operations.
  1406. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1407. if (phase != Phase::Concrete) {
  1408. break;
  1409. }
  1410. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1411. }
  1412. // Binary float -> float operations.
  1413. case SemIR::BuiltinFunctionKind::FloatAdd:
  1414. case SemIR::BuiltinFunctionKind::FloatSub:
  1415. case SemIR::BuiltinFunctionKind::FloatMul:
  1416. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1417. if (phase != Phase::Concrete) {
  1418. break;
  1419. }
  1420. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1421. arg_ids[1]);
  1422. }
  1423. // Float comparisons.
  1424. case SemIR::BuiltinFunctionKind::FloatEq:
  1425. case SemIR::BuiltinFunctionKind::FloatNeq:
  1426. case SemIR::BuiltinFunctionKind::FloatLess:
  1427. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1428. case SemIR::BuiltinFunctionKind::FloatGreater:
  1429. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1430. if (phase != Phase::Concrete) {
  1431. break;
  1432. }
  1433. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1434. arg_ids[1], call.type_id);
  1435. }
  1436. // Bool comparisons.
  1437. case SemIR::BuiltinFunctionKind::BoolEq:
  1438. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1439. if (phase != Phase::Concrete) {
  1440. break;
  1441. }
  1442. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1443. arg_ids[1], call.type_id);
  1444. }
  1445. }
  1446. return SemIR::ConstantId::NotConstant;
  1447. }
  1448. // Makes a constant for a call instruction.
  1449. static auto MakeConstantForCall(EvalContext& eval_context, SemIR::LocId loc_id,
  1450. SemIR::Call call) -> SemIR::ConstantId {
  1451. Phase phase = Phase::Concrete;
  1452. // A call with an invalid argument list is used to represent an erroneous
  1453. // call.
  1454. //
  1455. // TODO: Use a better representation for this.
  1456. if (call.args_id == SemIR::InstBlockId::None) {
  1457. return SemIR::ErrorInst::SingletonConstantId;
  1458. }
  1459. // Find the constant value of the callee.
  1460. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1461. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1462. auto callee_function =
  1463. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1464. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1465. if (callee_function.function_id.has_value()) {
  1466. // Calls to builtins might be constant.
  1467. builtin_kind = eval_context.functions()
  1468. .Get(callee_function.function_id)
  1469. .builtin_function_kind;
  1470. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1471. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1472. // functions as producing constants.
  1473. return SemIR::ConstantId::NotConstant;
  1474. }
  1475. } else {
  1476. // Calls to non-functions, such as calls to generic entity names, might be
  1477. // constant.
  1478. }
  1479. // Find the argument values and the return type.
  1480. bool has_constant_operands =
  1481. has_constant_callee &&
  1482. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  1483. &phase) &&
  1484. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1485. &phase);
  1486. if (phase == Phase::UnknownDueToError) {
  1487. return SemIR::ErrorInst::SingletonConstantId;
  1488. }
  1489. // If any operand of the call is non-constant, the call is non-constant.
  1490. // TODO: Some builtin calls might allow some operands to be non-constant.
  1491. if (!has_constant_operands) {
  1492. if (builtin_kind.IsCompTimeOnly(
  1493. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1494. call.type_id)) {
  1495. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1496. "non-constant call to compile-time-only function");
  1497. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1498. "compile-time-only function declared here");
  1499. eval_context.emitter()
  1500. .Build(loc_id, NonConstantCallToCompTimeOnlyFunction)
  1501. .Note(eval_context.functions()
  1502. .Get(callee_function.function_id)
  1503. .latest_decl_id(),
  1504. CompTimeOnlyFunctionHere)
  1505. .Emit();
  1506. }
  1507. return SemIR::ConstantId::NotConstant;
  1508. }
  1509. // Handle calls to builtins.
  1510. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1511. return MakeConstantForBuiltinCall(
  1512. eval_context, loc_id, call, builtin_kind,
  1513. eval_context.inst_blocks().Get(call.args_id), phase);
  1514. }
  1515. return SemIR::ConstantId::NotConstant;
  1516. }
  1517. // Given an instruction, compute its phase based on its operands.
  1518. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1519. EvalContext eval_context(&context, SemIR::InstId::None);
  1520. auto phase = GetPhase(context.constant_values(),
  1521. context.types().GetConstantId(inst.type_id()));
  1522. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  1523. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  1524. CARBON_CHECK(IsConstant(phase));
  1525. return phase;
  1526. }
  1527. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1528. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1529. static auto ConvertEvalResultToConstantId(Context& context,
  1530. ConstantEvalResult result,
  1531. Phase orig_phase)
  1532. -> SemIR::ConstantId {
  1533. if (result.is_new()) {
  1534. return MakeConstantResult(
  1535. context, result.new_inst(),
  1536. result.same_phase_as_inst()
  1537. ? orig_phase
  1538. : ComputeInstPhase(context, result.new_inst()));
  1539. }
  1540. return result.existing();
  1541. }
  1542. // Evaluates an instruction of a known type in an evaluation context. The
  1543. // default behavior of this function depends on the constant kind of the
  1544. // instruction:
  1545. //
  1546. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  1547. // - InstConstantKind::Indirect, SymbolicOnly, Conditional: evaluates all the
  1548. // operands of the instruction, and calls `EvalConstantInst` to evaluate the
  1549. // resulting constant instruction.
  1550. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  1551. // the instruction, and produces the resulting constant instruction as the
  1552. // result.
  1553. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  1554. // constant.
  1555. //
  1556. // Returns an error constant ID if any of the nested evaluations fail, and
  1557. // returns NotConstant if any of the nested evaluations is non-constant.
  1558. //
  1559. // This template is explicitly specialized for instructions that need special
  1560. // handling.
  1561. template <typename InstT>
  1562. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  1563. SemIR::Inst inst) -> SemIR::ConstantId {
  1564. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  1565. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  1566. return SemIR::ConstantId::NotConstant;
  1567. } else if constexpr (ConstantKind == SemIR::InstConstantKind::Unique) {
  1568. CARBON_CHECK(inst_id.has_value());
  1569. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  1570. } else {
  1571. // Build a constant instruction by replacing each non-constant operand with
  1572. // its constant value.
  1573. Phase phase = Phase::Concrete;
  1574. if (!ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  1575. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  1576. CARBON_CHECK(phase == Phase::UnknownDueToError,
  1577. "{0} should always be constant", InstT::Kind);
  1578. }
  1579. return MakeNonConstantResult(phase);
  1580. }
  1581. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  1582. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  1583. return MakeConstantResult(eval_context.context(), inst, phase);
  1584. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  1585. auto result_inst_id = PerformDelayedAction(
  1586. eval_context.context(), eval_context.insts().GetLocId(inst_id),
  1587. inst.As<InstT>());
  1588. if (result_inst_id.has_value()) {
  1589. // The result is an instruction.
  1590. return MakeConstantResult(
  1591. eval_context.context(),
  1592. SemIR::InstValue{.type_id = SemIR::InstType::SingletonTypeId,
  1593. .inst_id = result_inst_id},
  1594. Phase::Concrete);
  1595. }
  1596. // Couldn't perform the action because it's still dependent.
  1597. return MakeConstantResult(eval_context.context(), inst,
  1598. Phase::TemplateSymbolic);
  1599. } else if constexpr (InstT::Kind.constant_needs_inst_id() !=
  1600. SemIR::InstConstantNeedsInstIdKind::No) {
  1601. CARBON_CHECK(inst_id.has_value());
  1602. return ConvertEvalResultToConstantId(
  1603. eval_context.context(),
  1604. EvalConstantInst(eval_context.context(), inst_id, inst.As<InstT>()),
  1605. phase);
  1606. } else {
  1607. return ConvertEvalResultToConstantId(
  1608. eval_context.context(),
  1609. EvalConstantInst(eval_context.context(), inst.As<InstT>()), phase);
  1610. }
  1611. }
  1612. }
  1613. // Specialize evaluation for array indexing because we want to check the index
  1614. // expression even if the array expression is non-constant.
  1615. template <>
  1616. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  1617. SemIR::InstId /*inst_id*/,
  1618. SemIR::Inst inst)
  1619. -> SemIR::ConstantId {
  1620. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  1621. }
  1622. // Specialize evaluation for function calls because we want to check the callee
  1623. // expression even if an argument expression is non-constant, and because we
  1624. // will eventually want to perform control flow handling here.
  1625. template <>
  1626. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  1627. SemIR::InstId inst_id, SemIR::Inst inst)
  1628. -> SemIR::ConstantId {
  1629. return MakeConstantForCall(eval_context,
  1630. eval_context.GetDiagnosticLoc(inst_id),
  1631. inst.As<SemIR::Call>());
  1632. }
  1633. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  1634. // `import_ref.cpp`, not by us.
  1635. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  1636. // call this.
  1637. template <>
  1638. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  1639. SemIR::InstId /*inst_id*/,
  1640. SemIR::Inst /*inst*/)
  1641. -> SemIR::ConstantId {
  1642. return SemIR::ConstantId::NotConstant;
  1643. }
  1644. // Symbolic bindings are a special case because they can reach into the eval
  1645. // context and produce a context-specific value.
  1646. template <>
  1647. auto TryEvalTypedInst<SemIR::BindSymbolicName>(EvalContext& eval_context,
  1648. SemIR::InstId /*inst_id*/,
  1649. SemIR::Inst inst)
  1650. -> SemIR::ConstantId {
  1651. auto bind = inst.As<SemIR::BindSymbolicName>();
  1652. // If we know which specific we're evaluating within and this is an argument
  1653. // of that specific, its constant value is the corresponding argument value.
  1654. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  1655. if (bind_name.bind_index().has_value()) {
  1656. if (auto value =
  1657. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  1658. value.has_value()) {
  1659. return value;
  1660. }
  1661. }
  1662. // The constant form of a symbolic binding is an idealized form of the
  1663. // original, with no equivalent value.
  1664. Phase phase = Phase::Concrete;
  1665. bind.value_id = SemIR::InstId::None;
  1666. if (!ReplaceFieldWithConstantValue(
  1667. eval_context, &bind, &SemIR::BindSymbolicName::type_id, &phase) ||
  1668. !ReplaceFieldWithConstantValue(eval_context, &bind,
  1669. &SemIR::BindSymbolicName::entity_name_id,
  1670. &phase)) {
  1671. return MakeNonConstantResult(phase);
  1672. }
  1673. return MakeConstantResult(eval_context.context(), bind, phase);
  1674. }
  1675. static auto IsPeriodSelf(EvalContext& eval_context, SemIR::ConstantId const_id)
  1676. -> bool {
  1677. // This also rejects the singleton Error value as it's concrete.
  1678. if (!const_id.is_symbolic()) {
  1679. return false;
  1680. }
  1681. const auto& symbolic =
  1682. eval_context.constant_values().GetSymbolicConstant(const_id);
  1683. // Fast early reject before doing more expensive operations.
  1684. if (symbolic.dependence != SemIR::ConstantDependence::PeriodSelf) {
  1685. return false;
  1686. }
  1687. auto inst_id = symbolic.inst_id;
  1688. // Unwrap the `FacetAccessType` instruction, which we get when the `.Self` is
  1689. // converted to `type`.
  1690. if (auto facet_access_type =
  1691. eval_context.insts().TryGetAs<SemIR::FacetAccessType>(inst_id)) {
  1692. inst_id = facet_access_type->facet_value_inst_id;
  1693. }
  1694. if (auto bind_symbolic_name =
  1695. eval_context.insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  1696. const auto& bind_name =
  1697. eval_context.entity_names().Get(bind_symbolic_name->entity_name_id);
  1698. return bind_name.name_id == SemIR::NameId::PeriodSelf;
  1699. }
  1700. return false;
  1701. }
  1702. // TODO: Convert this to an EvalConstantInst instruction. This will require
  1703. // providing a `GetConstantValue` overload for a requirement block.
  1704. template <>
  1705. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  1706. SemIR::InstId /*inst_id*/,
  1707. SemIR::Inst inst) -> SemIR::ConstantId {
  1708. auto typed_inst = inst.As<SemIR::WhereExpr>();
  1709. Phase phase = Phase::Concrete;
  1710. SemIR::TypeId base_facet_type_id =
  1711. eval_context.insts().Get(typed_inst.period_self_id).type_id();
  1712. SemIR::Inst base_facet_inst =
  1713. eval_context.GetConstantValueAsInst(base_facet_type_id);
  1714. SemIR::FacetTypeInfo info = {.other_requirements = false};
  1715. // `where` provides that the base facet is an error, `type`, or a facet
  1716. // type.
  1717. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1718. info = GetConstantFacetTypeInfo(eval_context, facet_type->facet_type_id,
  1719. &phase);
  1720. } else if (base_facet_type_id == SemIR::ErrorInst::SingletonTypeId) {
  1721. return SemIR::ErrorInst::SingletonConstantId;
  1722. } else {
  1723. CARBON_CHECK(base_facet_type_id == SemIR::TypeType::SingletonTypeId,
  1724. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1725. base_facet_inst);
  1726. }
  1727. if (typed_inst.requirements_id.has_value()) {
  1728. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  1729. for (auto inst_id : insts) {
  1730. if (auto rewrite =
  1731. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  1732. inst_id)) {
  1733. // `where` requirements using `.Self` should not be considered
  1734. // symbolic.
  1735. auto lhs_id = GetConstantValueIgnoringPeriodSelf(
  1736. eval_context, rewrite->lhs_id, &phase);
  1737. auto rhs_id = GetConstantValueIgnoringPeriodSelf(
  1738. eval_context, rewrite->rhs_id, &phase);
  1739. info.rewrite_constraints.push_back(
  1740. {.lhs_id = lhs_id, .rhs_id = rhs_id});
  1741. } else if (auto impls =
  1742. eval_context.insts().TryGetAs<SemIR::RequirementImpls>(
  1743. inst_id)) {
  1744. SemIR::ConstantId lhs = eval_context.GetConstantValue(impls->lhs_id);
  1745. SemIR::ConstantId rhs = eval_context.GetConstantValue(impls->rhs_id);
  1746. if (rhs != SemIR::ErrorInst::SingletonConstantId &&
  1747. IsPeriodSelf(eval_context, lhs)) {
  1748. auto rhs_inst_id = eval_context.constant_values().GetInstId(rhs);
  1749. if (rhs_inst_id == SemIR::TypeType::SingletonInstId) {
  1750. // `.Self impls type` -> nothing to do.
  1751. } else {
  1752. auto facet_type =
  1753. eval_context.insts().GetAs<SemIR::FacetType>(rhs_inst_id);
  1754. SemIR::FacetTypeInfo more_info = GetConstantFacetTypeInfo(
  1755. eval_context, facet_type.facet_type_id, &phase);
  1756. // The way to prevent lookup into the interface requirements of a
  1757. // facet type is to put it to the right of a `.Self impls`, which we
  1758. // accomplish by putting them into `self_impls_constraints`.
  1759. llvm::append_range(info.self_impls_constraints,
  1760. more_info.extend_constraints);
  1761. llvm::append_range(info.self_impls_constraints,
  1762. more_info.self_impls_constraints);
  1763. // Other requirements are copied in.
  1764. llvm::append_range(info.rewrite_constraints,
  1765. more_info.rewrite_constraints);
  1766. info.other_requirements |= more_info.other_requirements;
  1767. }
  1768. } else {
  1769. // TODO: Handle `impls` constraints beyond `.Self impls`.
  1770. info.other_requirements = true;
  1771. }
  1772. } else {
  1773. // TODO: Handle other requirements
  1774. info.other_requirements = true;
  1775. }
  1776. }
  1777. }
  1778. info.Canonicalize();
  1779. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1780. }
  1781. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1782. static auto TryEvalInstInContext(EvalContext& eval_context,
  1783. SemIR::InstId inst_id, SemIR::Inst inst)
  1784. -> SemIR::ConstantId {
  1785. using EvalInstFn =
  1786. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  1787. ->SemIR::ConstantId;
  1788. static constexpr EvalInstFn* EvalInstFns[] = {
  1789. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  1790. #include "toolchain/sem_ir/inst_kind.def"
  1791. };
  1792. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  1793. inst_id, inst);
  1794. }
  1795. auto TryEvalInstUnsafe(Context& context, SemIR::InstId inst_id,
  1796. SemIR::Inst inst) -> SemIR::ConstantId {
  1797. EvalContext eval_context(&context, inst_id);
  1798. return TryEvalInstInContext(eval_context, inst_id, inst);
  1799. }
  1800. auto TryEvalBlockForSpecific(Context& context, SemIR::LocId loc_id,
  1801. SemIR::SpecificId specific_id,
  1802. SemIR::GenericInstIndex::Region region)
  1803. -> SemIR::InstBlockId {
  1804. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1805. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1806. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1807. llvm::SmallVector<SemIR::InstId> result;
  1808. result.resize(eval_block.size(), SemIR::InstId::None);
  1809. EvalContext eval_context(&context, loc_id, specific_id,
  1810. SpecificEvalInfo{
  1811. .region = region,
  1812. .values = result,
  1813. });
  1814. Diagnostics::AnnotationScope annotate_diagnostics(
  1815. &context.emitter(), [&](auto& builder) {
  1816. CARBON_DIAGNOSTIC(ResolvingSpecificHere, Note, "in {0} used here",
  1817. SemIR::SpecificId);
  1818. builder.Note(loc_id, ResolvingSpecificHere, specific_id);
  1819. });
  1820. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1821. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1822. context.insts().Get(inst_id));
  1823. result[i] = context.constant_values().GetInstId(const_id);
  1824. CARBON_CHECK(result[i].has_value(), "Failed to evaluate {0} in eval block",
  1825. context.insts().Get(inst_id));
  1826. }
  1827. return context.inst_blocks().Add(result);
  1828. }
  1829. } // namespace Carbon::Check