eval.cpp 86 KB

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