eval.cpp 81 KB

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