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. static auto GetTypeOfInst(EvalContext& eval_context, SemIR::InstId inst_id,
  408. Phase* phase) -> SemIR::TypeId {
  409. auto type_id = eval_context.GetTypeOfInst(inst_id);
  410. *phase = LatestPhase(*phase,
  411. GetPhase(eval_context.constant_values(),
  412. eval_context.types().GetConstantId(type_id)));
  413. return type_id;
  414. }
  415. // AbsoluteInstBlockId can not have its values substituted, so this overload is
  416. // deleted. This prevents conversion to InstBlockId.
  417. static auto GetConstantValue(EvalContext& eval_context,
  418. SemIR::AbsoluteInstBlockId inst_block_id,
  419. Phase* phase) -> SemIR::InstBlockId = delete;
  420. // If the given instruction block contains only constants, returns a
  421. // corresponding block of those values.
  422. static auto GetConstantValue(EvalContext& eval_context,
  423. SemIR::InstBlockId inst_block_id, Phase* phase)
  424. -> SemIR::InstBlockId {
  425. if (!inst_block_id.has_value()) {
  426. return SemIR::InstBlockId::None;
  427. }
  428. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  429. llvm::SmallVector<SemIR::InstId> const_insts;
  430. for (auto inst_id : insts) {
  431. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  432. if (!const_inst_id.has_value()) {
  433. return SemIR::InstBlockId::None;
  434. }
  435. // Once we leave the small buffer, we know the first few elements are all
  436. // constant, so it's likely that the entire block is constant. Resize to the
  437. // target size given that we're going to allocate memory now anyway.
  438. if (const_insts.size() == const_insts.capacity()) {
  439. const_insts.reserve(insts.size());
  440. }
  441. const_insts.push_back(const_inst_id);
  442. }
  443. // TODO: If the new block is identical to the original block, and we know the
  444. // old ID was canonical, return the original ID.
  445. return eval_context.inst_blocks().AddCanonical(const_insts);
  446. }
  447. // Compute the constant value of a type block. This may be different from the
  448. // input type block if we have known generic arguments.
  449. static auto GetConstantValue(EvalContext& eval_context,
  450. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  451. -> SemIR::StructTypeFieldsId {
  452. if (!fields_id.has_value()) {
  453. return SemIR::StructTypeFieldsId::None;
  454. }
  455. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  456. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  457. for (auto field : fields) {
  458. auto new_type_inst_id =
  459. GetConstantValue(eval_context, field.type_inst_id, phase);
  460. if (!new_type_inst_id.has_value()) {
  461. return SemIR::StructTypeFieldsId::None;
  462. }
  463. // Once we leave the small buffer, we know the first few elements are all
  464. // constant, so it's likely that the entire block is constant. Resize to the
  465. // target size given that we're going to allocate memory now anyway.
  466. if (new_fields.size() == new_fields.capacity()) {
  467. new_fields.reserve(fields.size());
  468. }
  469. new_fields.push_back(
  470. {.name_id = field.name_id, .type_inst_id = new_type_inst_id});
  471. }
  472. // TODO: If the new block is identical to the original block, and we know the
  473. // old ID was canonical, return the original ID.
  474. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  475. }
  476. // The constant value of a specific is the specific with the corresponding
  477. // constant values for its arguments.
  478. static auto GetConstantValue(EvalContext& eval_context,
  479. SemIR::SpecificId specific_id, Phase* phase)
  480. -> SemIR::SpecificId {
  481. if (!specific_id.has_value()) {
  482. return SemIR::SpecificId::None;
  483. }
  484. const auto& specific = eval_context.specifics().Get(specific_id);
  485. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  486. if (!args_id.has_value()) {
  487. return SemIR::SpecificId::None;
  488. }
  489. // Generally, when making a new specific, it's done through MakeSpecific(),
  490. // which will ensure the declaration is resolved.
  491. //
  492. // However, the SpecificId returned here is intentionally left without its
  493. // declaration resolved. Imported instructions with SpecificIds should not
  494. // have the specific's declaration resolved, but other instructions which
  495. // include a new SpecificId should.
  496. //
  497. // The resolving of the specific's declaration will be ensured later when
  498. // evaluating the instruction containing the SpecificId.
  499. if (args_id == specific.args_id) {
  500. return specific_id;
  501. }
  502. return eval_context.context().specifics().GetOrAdd(specific.generic_id,
  503. args_id);
  504. }
  505. static auto GetConstantValue(EvalContext& eval_context,
  506. SemIR::SpecificInterfaceId specific_interface_id,
  507. Phase* phase) -> SemIR::SpecificInterfaceId {
  508. const auto& interface =
  509. eval_context.specific_interfaces().Get(specific_interface_id);
  510. if (!interface.specific_id.has_value()) {
  511. return specific_interface_id;
  512. }
  513. return eval_context.specific_interfaces().Add(
  514. {.interface_id = interface.interface_id,
  515. .specific_id =
  516. GetConstantValue(eval_context, interface.specific_id, phase)});
  517. }
  518. // Like `GetConstantValue` but does a `FacetTypeId` -> `FacetTypeInfo`
  519. // conversion. Does not perform canonicalization.
  520. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  521. SemIR::FacetTypeId facet_type_id,
  522. Phase* phase) -> SemIR::FacetTypeInfo {
  523. const auto& orig = eval_context.facet_types().Get(facet_type_id);
  524. SemIR::FacetTypeInfo info;
  525. info.extend_constraints.reserve(orig.extend_constraints.size());
  526. for (const auto& interface : orig.extend_constraints) {
  527. info.extend_constraints.push_back(
  528. {.interface_id = interface.interface_id,
  529. .specific_id =
  530. GetConstantValue(eval_context, interface.specific_id, phase)});
  531. }
  532. info.self_impls_constraints.reserve(orig.self_impls_constraints.size());
  533. for (const auto& interface : orig.self_impls_constraints) {
  534. info.self_impls_constraints.push_back(
  535. {.interface_id = interface.interface_id,
  536. .specific_id =
  537. GetConstantValue(eval_context, interface.specific_id, phase)});
  538. }
  539. info.rewrite_constraints.reserve(orig.rewrite_constraints.size());
  540. for (const auto& rewrite : orig.rewrite_constraints) {
  541. // `where` requirements using `.Self` should not be considered symbolic.
  542. auto lhs_id =
  543. GetConstantValueIgnoringPeriodSelf(eval_context, rewrite.lhs_id, phase);
  544. auto rhs_id =
  545. GetConstantValueIgnoringPeriodSelf(eval_context, rewrite.rhs_id, phase);
  546. info.rewrite_constraints.push_back({.lhs_id = lhs_id, .rhs_id = rhs_id});
  547. }
  548. // TODO: Process other requirements.
  549. info.other_requirements = orig.other_requirements;
  550. return info;
  551. }
  552. static auto GetConstantValue(EvalContext& eval_context,
  553. SemIR::FacetTypeId facet_type_id, Phase* phase)
  554. -> SemIR::FacetTypeId {
  555. SemIR::FacetTypeInfo info =
  556. GetConstantFacetTypeInfo(eval_context, facet_type_id, phase);
  557. info.Canonicalize();
  558. // TODO: Return `facet_type_id` if we can detect nothing has changed.
  559. return eval_context.facet_types().Add(info);
  560. }
  561. static auto GetConstantValue(EvalContext& eval_context,
  562. SemIR::EntityNameId entity_name_id, Phase* phase)
  563. -> SemIR::EntityNameId {
  564. const auto& bind_name = eval_context.entity_names().Get(entity_name_id);
  565. Phase name_phase;
  566. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  567. name_phase = Phase::PeriodSelfSymbolic;
  568. } else if (!bind_name.bind_index().has_value()) {
  569. name_phase = Phase::Concrete;
  570. } else if (bind_name.is_template) {
  571. name_phase = Phase::TemplateSymbolic;
  572. } else {
  573. name_phase = Phase::CheckedSymbolic;
  574. }
  575. *phase = LatestPhase(*phase, name_phase);
  576. return eval_context.entity_names().MakeCanonical(entity_name_id);
  577. }
  578. // Replaces the specified field of the given typed instruction with its constant
  579. // value, if it has constant phase. Returns true on success, false if the value
  580. // has runtime phase.
  581. template <typename InstT, typename FieldIdT>
  582. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  583. InstT* inst, FieldIdT InstT::* field,
  584. Phase* phase) -> bool {
  585. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  586. if (!unwrapped.has_value() && (inst->*field).has_value()) {
  587. return false;
  588. }
  589. inst->*field = unwrapped;
  590. return true;
  591. }
  592. // Function template that can be called with an argument of type `T`. Used below
  593. // to detect which overloads of `GetConstantValue` exist.
  594. template <typename T>
  595. static void Accept(T /*arg*/) {}
  596. // Determines whether a `GetConstantValue` overload exists for a given ID type.
  597. // Note that we do not check whether `GetConstantValue` is *callable* with a
  598. // given ID type, because that would use the `InstId` overload for
  599. // `AbsoluteInstId` and similar wrapper types, which should be left alone.
  600. template <typename IdT>
  601. static constexpr bool HasGetConstantValueOverload = requires {
  602. Accept<auto (*)(EvalContext&, IdT, Phase*)->IdT>(GetConstantValue);
  603. };
  604. using ArgHandlerFnT = auto(EvalContext& context, int32_t arg, Phase* phase)
  605. -> int32_t;
  606. // Returns the arg handler for an `IdKind`.
  607. template <typename... Types>
  608. static auto GetArgHandlerFn(TypeEnum<Types...> id_kind) -> ArgHandlerFnT* {
  609. static constexpr std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> Table =
  610. {
  611. [](EvalContext& eval_context, int32_t arg, Phase* phase) -> int32_t {
  612. auto id = SemIR::Inst::FromRaw<Types>(arg);
  613. if constexpr (HasGetConstantValueOverload<Types>) {
  614. // If we have a custom `GetConstantValue` overload, call it.
  615. return SemIR::Inst::ToRaw(
  616. GetConstantValue(eval_context, id, phase));
  617. } else {
  618. // Otherwise, we assume the value is already constant.
  619. return arg;
  620. }
  621. }...,
  622. // Invalid and None handling (ordering-sensitive).
  623. [](auto...) -> int32_t { CARBON_FATAL("Unexpected invalid IdKind"); },
  624. [](EvalContext& /*context*/, int32_t arg,
  625. Phase* /*phase*/) -> int32_t { return arg; },
  626. };
  627. return Table[id_kind.ToIndex()];
  628. }
  629. // Given the stored value `arg` of an instruction field and its corresponding
  630. // kind `kind`, returns the constant value to use for that field, if it has a
  631. // constant phase. `*phase` is updated to include the new constant value. If
  632. // the resulting phase is not constant, the returned value is not useful and
  633. // will typically be `NoneIndex`.
  634. static auto GetConstantValueForArg(EvalContext& eval_context,
  635. SemIR::Inst::ArgAndKind arg_and_kind,
  636. Phase* phase) -> int32_t {
  637. return GetArgHandlerFn(arg_and_kind.kind())(eval_context,
  638. arg_and_kind.value(), phase);
  639. }
  640. // Given an instruction, replaces its operands with their constant values from
  641. // the specified evaluation context. `*phase` is updated to describe the
  642. // constant phase of the result. Returns whether `*phase` is a constant phase;
  643. // if not, `inst` may not be fully updated and should not be used.
  644. static auto ReplaceAllFieldsWithConstantValues(EvalContext& eval_context,
  645. SemIR::Inst* inst, Phase* phase)
  646. -> bool {
  647. auto arg0 =
  648. GetConstantValueForArg(eval_context, inst->arg0_and_kind(), phase);
  649. if (!IsConstant(*phase)) {
  650. return false;
  651. }
  652. auto arg1 =
  653. GetConstantValueForArg(eval_context, inst->arg1_and_kind(), phase);
  654. if (!IsConstant(*phase)) {
  655. return false;
  656. }
  657. inst->SetArgs(arg0, arg1);
  658. return true;
  659. }
  660. // Given an instruction and its ID, replaces its type with the corresponding
  661. // value in this evaluation context. Updates `*phase` to describe the phase of
  662. // the result, and returns whether `*phase` is a constant phase.
  663. //
  664. // If the `InstId` is not provided, the instruction is assumed to be new and
  665. // therefore unattached, so the type is not updated.
  666. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  667. SemIR::InstId inst_id,
  668. SemIR::Inst* inst, Phase* phase)
  669. -> bool {
  670. if (inst_id.has_value()) {
  671. inst->SetType(GetTypeOfInst(eval_context, inst_id, phase));
  672. }
  673. return IsConstant(*phase);
  674. }
  675. template <typename InstT>
  676. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  677. SemIR::InstId inst_id, InstT* inst,
  678. Phase* phase) -> bool {
  679. if (inst_id.has_value()) {
  680. inst->type_id = GetTypeOfInst(eval_context, inst_id, phase);
  681. }
  682. return IsConstant(*phase);
  683. }
  684. template <typename... Types>
  685. static auto KindHasGetConstantValueOverload(TypeEnum<Types...> e) -> bool {
  686. static constexpr std::array<bool, SemIR::IdKind::NumTypes> Values = {
  687. (HasGetConstantValueOverload<Types>)...};
  688. return Values[e.ToIndex()];
  689. }
  690. static auto ResolveSpecificDeclForSpecificId(EvalContext& eval_context,
  691. SemIR::SpecificId specific_id)
  692. -> void {
  693. if (!specific_id.has_value()) {
  694. return;
  695. }
  696. const auto& specific = eval_context.specifics().Get(specific_id);
  697. const auto& generic = eval_context.generics().Get(specific.generic_id);
  698. if (specific_id == generic.self_specific_id) {
  699. // Impl witness table construction happens before its generic decl is
  700. // finish, in order to make the table's instructions dependent
  701. // instructions of the Impl's generic. But those instructions can refer to
  702. // the generic's self specific. We can not resolve the specific
  703. // declaration for the self specific until the generic is finished, but it
  704. // is explicitly resolved at that time in `FinishGenericDecl()`.
  705. return;
  706. }
  707. ResolveSpecificDecl(eval_context.context(), eval_context.fallback_loc_id(),
  708. specific_id);
  709. }
  710. // Resolves the specific declarations for a specific id in any field of the
  711. // `inst` instruction.
  712. static auto ResolveSpecificDeclForInst(EvalContext& eval_context,
  713. const SemIR::Inst& inst) -> void {
  714. for (auto arg_and_kind : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  715. // This switch must handle any field type that has a GetConstantValue()
  716. // overload which canonicalizes a specific (and thus potentially forms a new
  717. // specific) as part of forming its constant value.
  718. CARBON_KIND_SWITCH(arg_and_kind) {
  719. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  720. const auto& info =
  721. eval_context.context().facet_types().Get(facet_type_id);
  722. for (const auto& interface : info.extend_constraints) {
  723. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  724. }
  725. for (const auto& interface : info.self_impls_constraints) {
  726. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  727. }
  728. break;
  729. }
  730. case CARBON_KIND(SemIR::SpecificId specific_id): {
  731. ResolveSpecificDeclForSpecificId(eval_context, specific_id);
  732. break;
  733. }
  734. case CARBON_KIND(SemIR::SpecificInterfaceId specific_interface_id): {
  735. ResolveSpecificDeclForSpecificId(eval_context,
  736. eval_context.specific_interfaces()
  737. .Get(specific_interface_id)
  738. .specific_id);
  739. break;
  740. }
  741. // These id types have a GetConstantValue() overload but that overload
  742. // does not canonicalize any SpecificId in the value type.
  743. case SemIR::IdKind::For<SemIR::DestInstId>:
  744. case SemIR::IdKind::For<SemIR::EntityNameId>:
  745. case SemIR::IdKind::For<SemIR::InstBlockId>:
  746. case SemIR::IdKind::For<SemIR::InstId>:
  747. case SemIR::IdKind::For<SemIR::MetaInstId>:
  748. case SemIR::IdKind::For<SemIR::StructTypeFieldsId>:
  749. case SemIR::IdKind::For<SemIR::TypeInstId>:
  750. break;
  751. case SemIR::IdKind::None:
  752. // No arg.
  753. break;
  754. default:
  755. CARBON_CHECK(
  756. !KindHasGetConstantValueOverload(arg_and_kind.kind()),
  757. "Missing case for {0} which has a GetConstantValue() overload",
  758. arg_and_kind.kind());
  759. break;
  760. }
  761. }
  762. }
  763. auto AddImportedConstant(Context& context, SemIR::Inst inst)
  764. -> SemIR::ConstantId {
  765. EvalContext eval_context(&context, SemIR::LocId::None);
  766. CARBON_CHECK(inst.kind().has_type(), "Can't import untyped instructions: {0}",
  767. inst.kind());
  768. Phase phase = GetPhase(context.constant_values(),
  769. context.types().GetConstantId(inst.type_id()));
  770. if (!ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  771. return SemIR::ConstantId::NotConstant;
  772. }
  773. return MakeConstantResult(context, inst, phase);
  774. }
  775. // Performs an index into a homogeneous aggregate, retrieving the specified
  776. // element.
  777. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  778. -> SemIR::ConstantId {
  779. Phase phase = Phase::Concrete;
  780. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  781. if (!index_id.has_value()) {
  782. return MakeNonConstantResult(phase);
  783. }
  784. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  785. if (!index) {
  786. CARBON_CHECK(phase != Phase::Concrete,
  787. "Concrete constant integer should be a literal");
  788. return MakeNonConstantResult(phase);
  789. }
  790. // Array indexing is invalid if the index is constant and out of range,
  791. // regardless of whether the array itself is constant.
  792. const auto& index_val = eval_context.ints().Get(index->int_id);
  793. auto aggregate_type_id = eval_context.GetTypeOfInst(inst.array_id);
  794. if (auto array_type =
  795. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  796. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  797. array_type->bound_id)) {
  798. // This awkward call to `getZExtValue` is a workaround for APInt not
  799. // supporting comparisons between integers of different bit widths.
  800. if (index_val.getActiveBits() > 64 ||
  801. eval_context.ints()
  802. .Get(bound->int_id)
  803. .ule(index_val.getZExtValue())) {
  804. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  805. "array index `{0}` is past the end of type {1}",
  806. TypedInt, SemIR::TypeId);
  807. eval_context.emitter().Emit(
  808. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  809. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  810. return SemIR::ErrorInst::ConstantId;
  811. }
  812. }
  813. }
  814. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  815. if (!aggregate_id.has_value()) {
  816. return MakeNonConstantResult(phase);
  817. }
  818. auto aggregate =
  819. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  820. if (!aggregate) {
  821. // TODO: Consider forming a symbolic constant or reference constant array
  822. // index in this case.
  823. return MakeNonConstantResult(phase);
  824. }
  825. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  826. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  827. }
  828. // Forms a constant int type as an evaluation result. Requires that width_id is
  829. // constant.
  830. static auto MakeIntTypeResult(Context& context, SemIR::LocId loc_id,
  831. SemIR::IntKind int_kind, SemIR::InstId width_id,
  832. Phase phase) -> SemIR::ConstantId {
  833. auto result = SemIR::IntType{
  834. .type_id = GetSingletonType(context, SemIR::TypeType::TypeInstId),
  835. .int_kind = int_kind,
  836. .bit_width_id = width_id};
  837. if (!ValidateIntType(context, loc_id, result)) {
  838. return SemIR::ErrorInst::ConstantId;
  839. }
  840. return MakeConstantResult(context, result, phase);
  841. }
  842. // Performs a conversion between integer types, truncating if the value doesn't
  843. // fit in the destination type.
  844. static auto PerformIntConvert(Context& context, SemIR::InstId arg_id,
  845. SemIR::TypeId dest_type_id) -> SemIR::ConstantId {
  846. auto arg_val =
  847. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(arg_id).int_id);
  848. auto [dest_is_signed, bit_width_id] =
  849. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  850. if (bit_width_id.has_value()) {
  851. // TODO: If the value fits in the destination type, reuse the existing
  852. // int_id rather than recomputing it. This is probably the most common case.
  853. bool src_is_signed = context.sem_ir().types().IsSignedInt(
  854. context.insts().Get(arg_id).type_id());
  855. unsigned width = context.ints().Get(bit_width_id).getZExtValue();
  856. arg_val =
  857. src_is_signed ? arg_val.sextOrTrunc(width) : arg_val.zextOrTrunc(width);
  858. }
  859. return MakeIntResult(context, dest_type_id, dest_is_signed, arg_val);
  860. }
  861. // Performs a conversion between integer types, diagnosing if the value doesn't
  862. // fit in the destination type.
  863. static auto PerformCheckedIntConvert(Context& context, SemIR::LocId loc_id,
  864. SemIR::InstId arg_id,
  865. SemIR::TypeId dest_type_id)
  866. -> SemIR::ConstantId {
  867. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  868. auto arg_val = context.ints().Get(arg.int_id);
  869. auto [is_signed, bit_width_id] =
  870. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  871. auto width = bit_width_id.has_value()
  872. ? context.ints().Get(bit_width_id).getZExtValue()
  873. : arg_val.getBitWidth();
  874. if (!is_signed && arg_val.isNegative()) {
  875. CARBON_DIAGNOSTIC(
  876. NegativeIntInUnsignedType, Error,
  877. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  878. SemIR::TypeId);
  879. context.emitter().Emit(loc_id, NegativeIntInUnsignedType,
  880. {.type = arg.type_id, .value = arg_val},
  881. dest_type_id);
  882. }
  883. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  884. if (arg_non_sign_bits + is_signed > width) {
  885. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  886. "integer value {0} too large for type {1}", TypedInt,
  887. SemIR::TypeId);
  888. context.emitter().Emit(loc_id, IntTooLargeForType,
  889. {.type = arg.type_id, .value = arg_val},
  890. dest_type_id);
  891. }
  892. return MakeConstantResult(
  893. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  894. Phase::Concrete);
  895. }
  896. // Issues a diagnostic for a compile-time division by zero.
  897. static auto DiagnoseDivisionByZero(Context& context, SemIR::LocId loc_id)
  898. -> void {
  899. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  900. context.emitter().Emit(loc_id, CompileTimeDivisionByZero);
  901. }
  902. // Get an integer at a suitable bit-width: either `bit_width_id` if it has a
  903. // value, or the canonical width from the value store if not.
  904. static auto GetIntAtSuitableWidth(Context& context, IntId int_id,
  905. IntId bit_width_id) -> llvm::APInt {
  906. return bit_width_id.has_value()
  907. ? context.ints().GetAtWidth(int_id, bit_width_id)
  908. : context.ints().Get(int_id);
  909. }
  910. // Performs a builtin unary integer -> integer operation.
  911. static auto PerformBuiltinUnaryIntOp(Context& context, SemIR::LocId loc_id,
  912. SemIR::BuiltinFunctionKind builtin_kind,
  913. SemIR::InstId arg_id)
  914. -> SemIR::ConstantId {
  915. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  916. auto [is_signed, bit_width_id] =
  917. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  918. llvm::APInt op_val = GetIntAtSuitableWidth(context, op.int_id, bit_width_id);
  919. switch (builtin_kind) {
  920. case SemIR::BuiltinFunctionKind::IntSNegate:
  921. if (op_val.isMinSignedValue()) {
  922. if (bit_width_id.has_value()) {
  923. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  924. "integer overflow in negation of {0}", TypedInt);
  925. context.emitter().Emit(loc_id, CompileTimeIntegerNegateOverflow,
  926. {.type = op.type_id, .value = op_val});
  927. } else {
  928. // Widen the integer so we don't overflow into the sign bit.
  929. op_val = op_val.sext(op_val.getBitWidth() +
  930. llvm::APInt::APINT_BITS_PER_WORD);
  931. }
  932. }
  933. op_val.negate();
  934. break;
  935. case SemIR::BuiltinFunctionKind::IntUNegate:
  936. CARBON_CHECK(bit_width_id.has_value(), "Unsigned negate on unsized int");
  937. op_val.negate();
  938. break;
  939. case SemIR::BuiltinFunctionKind::IntComplement:
  940. // TODO: Should we have separate builtins for signed and unsigned
  941. // complement? Like with signed/unsigned negate, these operations do
  942. // different things to the integer value, even though they do the same
  943. // thing to the bits. We treat IntLiteral complement as signed complement,
  944. // given that the result of unsigned complement depends on the bit width.
  945. op_val.flipAllBits();
  946. break;
  947. default:
  948. CARBON_FATAL("Unexpected builtin kind");
  949. }
  950. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  951. }
  952. namespace {
  953. // A pair of APInts that are the operands of a binary operator. We use an
  954. // aggregate rather than `std::pair` to allow RVO of the individual ints.
  955. struct APIntBinaryOperands {
  956. llvm::APInt lhs;
  957. llvm::APInt rhs;
  958. };
  959. } // namespace
  960. // Get a pair of integers at the same suitable bit-width: either their actual
  961. // width if they have a fixed width, or the smallest canonical width in which
  962. // they both fit otherwise.
  963. static auto GetIntsAtSuitableWidth(Context& context, IntId lhs_id, IntId rhs_id,
  964. IntId bit_width_id) -> APIntBinaryOperands {
  965. // Unsized operands: take the wider of the bit widths.
  966. if (!bit_width_id.has_value()) {
  967. APIntBinaryOperands result = {.lhs = context.ints().Get(lhs_id),
  968. .rhs = context.ints().Get(rhs_id)};
  969. if (result.lhs.getBitWidth() != result.rhs.getBitWidth()) {
  970. if (result.lhs.getBitWidth() > result.rhs.getBitWidth()) {
  971. result.rhs = result.rhs.sext(result.lhs.getBitWidth());
  972. } else {
  973. result.lhs = result.lhs.sext(result.rhs.getBitWidth());
  974. }
  975. }
  976. return result;
  977. }
  978. return {.lhs = context.ints().GetAtWidth(lhs_id, bit_width_id),
  979. .rhs = context.ints().GetAtWidth(rhs_id, bit_width_id)};
  980. }
  981. namespace {
  982. // The result of performing a binary int operation.
  983. struct BinaryIntOpResult {
  984. llvm::APInt result_val;
  985. bool overflow;
  986. Lex::TokenKind op_token;
  987. };
  988. } // namespace
  989. // Computes the result of a homogeneous binary (int, int) -> int operation.
  990. static auto ComputeBinaryIntOpResult(SemIR::BuiltinFunctionKind builtin_kind,
  991. const llvm::APInt& lhs_val,
  992. const llvm::APInt& rhs_val)
  993. -> BinaryIntOpResult {
  994. llvm::APInt result_val;
  995. bool overflow = false;
  996. Lex::TokenKind op_token = Lex::TokenKind::Not;
  997. switch (builtin_kind) {
  998. // Arithmetic.
  999. case SemIR::BuiltinFunctionKind::IntSAdd:
  1000. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  1001. op_token = Lex::TokenKind::Plus;
  1002. break;
  1003. case SemIR::BuiltinFunctionKind::IntSSub:
  1004. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  1005. op_token = Lex::TokenKind::Minus;
  1006. break;
  1007. case SemIR::BuiltinFunctionKind::IntSMul:
  1008. result_val = lhs_val.smul_ov(rhs_val, overflow);
  1009. op_token = Lex::TokenKind::Star;
  1010. break;
  1011. case SemIR::BuiltinFunctionKind::IntSDiv:
  1012. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  1013. op_token = Lex::TokenKind::Slash;
  1014. break;
  1015. case SemIR::BuiltinFunctionKind::IntSMod:
  1016. result_val = lhs_val.srem(rhs_val);
  1017. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  1018. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  1019. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  1020. op_token = Lex::TokenKind::Percent;
  1021. break;
  1022. case SemIR::BuiltinFunctionKind::IntUAdd:
  1023. result_val = lhs_val + rhs_val;
  1024. op_token = Lex::TokenKind::Plus;
  1025. break;
  1026. case SemIR::BuiltinFunctionKind::IntUSub:
  1027. result_val = lhs_val - rhs_val;
  1028. op_token = Lex::TokenKind::Minus;
  1029. break;
  1030. case SemIR::BuiltinFunctionKind::IntUMul:
  1031. result_val = lhs_val * rhs_val;
  1032. op_token = Lex::TokenKind::Star;
  1033. break;
  1034. case SemIR::BuiltinFunctionKind::IntUDiv:
  1035. result_val = lhs_val.udiv(rhs_val);
  1036. op_token = Lex::TokenKind::Slash;
  1037. break;
  1038. case SemIR::BuiltinFunctionKind::IntUMod:
  1039. result_val = lhs_val.urem(rhs_val);
  1040. op_token = Lex::TokenKind::Percent;
  1041. break;
  1042. // Bitwise.
  1043. case SemIR::BuiltinFunctionKind::IntAnd:
  1044. result_val = lhs_val & rhs_val;
  1045. op_token = Lex::TokenKind::And;
  1046. break;
  1047. case SemIR::BuiltinFunctionKind::IntOr:
  1048. result_val = lhs_val | rhs_val;
  1049. op_token = Lex::TokenKind::Pipe;
  1050. break;
  1051. case SemIR::BuiltinFunctionKind::IntXor:
  1052. result_val = lhs_val ^ rhs_val;
  1053. op_token = Lex::TokenKind::Caret;
  1054. break;
  1055. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1056. case SemIR::BuiltinFunctionKind::IntRightShift:
  1057. CARBON_FATAL("Non-homogeneous operation handled separately.");
  1058. default:
  1059. CARBON_FATAL("Unexpected operation kind.");
  1060. }
  1061. return {.result_val = std::move(result_val),
  1062. .overflow = overflow,
  1063. .op_token = op_token};
  1064. }
  1065. // Performs a builtin integer bit shift operation.
  1066. static auto PerformBuiltinIntShiftOp(Context& context, SemIR::LocId loc_id,
  1067. SemIR::BuiltinFunctionKind builtin_kind,
  1068. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  1069. -> SemIR::ConstantId {
  1070. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1071. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1072. auto [lhs_is_signed, lhs_bit_width_id] =
  1073. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  1074. llvm::APInt lhs_val =
  1075. GetIntAtSuitableWidth(context, lhs.int_id, lhs_bit_width_id);
  1076. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  1077. if (lhs_bit_width_id.has_value() && rhs_orig_val.uge(lhs_val.getBitWidth())) {
  1078. CARBON_DIAGNOSTIC(
  1079. CompileTimeShiftOutOfRange, Error,
  1080. "shift distance >= type width of {0} in `{1} {2:<<|>>} {3}`", unsigned,
  1081. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1082. context.emitter().Emit(
  1083. loc_id, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  1084. {.type = lhs.type_id, .value = lhs_val},
  1085. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1086. {.type = rhs.type_id, .value = rhs_orig_val});
  1087. // TODO: Is it useful to recover by returning 0 or -1?
  1088. return SemIR::ErrorInst::ConstantId;
  1089. }
  1090. if (rhs_orig_val.isNegative() &&
  1091. context.sem_ir().types().IsSignedInt(rhs.type_id)) {
  1092. CARBON_DIAGNOSTIC(CompileTimeShiftNegative, Error,
  1093. "shift distance negative in `{0} {1:<<|>>} {2}`",
  1094. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1095. context.emitter().Emit(
  1096. loc_id, CompileTimeShiftNegative,
  1097. {.type = lhs.type_id, .value = lhs_val},
  1098. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1099. {.type = rhs.type_id, .value = rhs_orig_val});
  1100. // TODO: Is it useful to recover by returning 0 or -1?
  1101. return SemIR::ErrorInst::ConstantId;
  1102. }
  1103. llvm::APInt result_val;
  1104. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  1105. if (!lhs_bit_width_id.has_value() && !lhs_val.isZero()) {
  1106. // Ensure we don't generate a ridiculously large integer through a bit
  1107. // shift.
  1108. auto width = rhs_orig_val.trySExtValue();
  1109. if (!width ||
  1110. *width > IntStore::MaxIntWidth - lhs_val.getSignificantBits()) {
  1111. CARBON_DIAGNOSTIC(CompileTimeUnsizedShiftOutOfRange, Error,
  1112. "shift distance of {0} would result in an "
  1113. "integer whose width is greater than the "
  1114. "maximum supported width of {1}",
  1115. TypedInt, int);
  1116. context.emitter().Emit(loc_id, CompileTimeUnsizedShiftOutOfRange,
  1117. {.type = rhs.type_id, .value = rhs_orig_val},
  1118. IntStore::MaxIntWidth);
  1119. return SemIR::ErrorInst::ConstantId;
  1120. }
  1121. lhs_val = lhs_val.sext(
  1122. IntStore::CanonicalBitWidth(lhs_val.getSignificantBits() + *width));
  1123. }
  1124. result_val =
  1125. lhs_val.shl(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1126. } else if (lhs_is_signed) {
  1127. result_val =
  1128. lhs_val.ashr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1129. } else {
  1130. CARBON_CHECK(lhs_bit_width_id.has_value(), "Logical shift on unsized int");
  1131. result_val =
  1132. lhs_val.lshr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1133. }
  1134. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  1135. std::move(result_val));
  1136. }
  1137. // Performs a homogeneous builtin binary integer -> integer operation.
  1138. static auto PerformBuiltinBinaryIntOp(Context& context, SemIR::LocId loc_id,
  1139. SemIR::BuiltinFunctionKind builtin_kind,
  1140. SemIR::InstId lhs_id,
  1141. SemIR::InstId rhs_id)
  1142. -> SemIR::ConstantId {
  1143. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1144. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1145. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  1146. auto type_id = lhs.type_id;
  1147. auto [is_signed, bit_width_id] =
  1148. context.sem_ir().types().GetIntTypeInfo(type_id);
  1149. auto [lhs_val, rhs_val] =
  1150. GetIntsAtSuitableWidth(context, lhs.int_id, rhs.int_id, bit_width_id);
  1151. // Check for division by zero.
  1152. switch (builtin_kind) {
  1153. case SemIR::BuiltinFunctionKind::IntSDiv:
  1154. case SemIR::BuiltinFunctionKind::IntSMod:
  1155. case SemIR::BuiltinFunctionKind::IntUDiv:
  1156. case SemIR::BuiltinFunctionKind::IntUMod:
  1157. if (rhs_val.isZero()) {
  1158. DiagnoseDivisionByZero(context, loc_id);
  1159. return SemIR::ErrorInst::ConstantId;
  1160. }
  1161. break;
  1162. default:
  1163. break;
  1164. }
  1165. BinaryIntOpResult result =
  1166. ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1167. if (result.overflow && !bit_width_id.has_value()) {
  1168. // Retry with a larger bit width. Most operations can only overflow by one
  1169. // bit, but signed n-bit multiplication can overflow to 2n-1 bits. We don't
  1170. // need to handle unsigned multiplication here because it's not permitted
  1171. // for unsized integers.
  1172. //
  1173. // Note that we speculatively first perform the calculation in the width of
  1174. // the wider operand: smaller operations are faster and overflow to a wider
  1175. // integer is unlikely to be needed, especially given that the width will
  1176. // have been rounded up to a multiple of 64 bits by the int store.
  1177. CARBON_CHECK(builtin_kind != SemIR::BuiltinFunctionKind::IntUMul,
  1178. "Unsigned arithmetic requires a fixed bitwidth");
  1179. int new_width =
  1180. builtin_kind == SemIR::BuiltinFunctionKind::IntSMul
  1181. ? lhs_val.getBitWidth() * 2
  1182. : IntStore::CanonicalBitWidth(lhs_val.getBitWidth() + 1);
  1183. new_width = std::min(new_width, IntStore::MaxIntWidth);
  1184. lhs_val = context.ints().GetAtWidth(lhs.int_id, new_width);
  1185. rhs_val = context.ints().GetAtWidth(rhs.int_id, new_width);
  1186. // Note that this can in theory still overflow if we limited `new_width` to
  1187. // `MaxIntWidth`. In that case we fall through to the signed overflow
  1188. // diagnostic below.
  1189. result = ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1190. CARBON_CHECK(!result.overflow || new_width == IntStore::MaxIntWidth);
  1191. }
  1192. if (result.overflow) {
  1193. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  1194. "integer overflow in calculation `{0} {1} {2}`", TypedInt,
  1195. Lex::TokenKind, TypedInt);
  1196. context.emitter().Emit(loc_id, CompileTimeIntegerOverflow,
  1197. {.type = type_id, .value = lhs_val}, result.op_token,
  1198. {.type = type_id, .value = rhs_val});
  1199. }
  1200. return MakeIntResult(context, type_id, is_signed,
  1201. std::move(result.result_val));
  1202. }
  1203. // Performs a builtin integer comparison.
  1204. static auto PerformBuiltinIntComparison(Context& context,
  1205. SemIR::BuiltinFunctionKind builtin_kind,
  1206. SemIR::InstId lhs_id,
  1207. SemIR::InstId rhs_id,
  1208. SemIR::TypeId bool_type_id)
  1209. -> SemIR::ConstantId {
  1210. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1211. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1212. llvm::APInt lhs_val = context.ints().Get(lhs.int_id);
  1213. llvm::APInt rhs_val = context.ints().Get(rhs.int_id);
  1214. bool result;
  1215. switch (builtin_kind) {
  1216. case SemIR::BuiltinFunctionKind::IntEq:
  1217. result = (lhs_val == rhs_val);
  1218. break;
  1219. case SemIR::BuiltinFunctionKind::IntNeq:
  1220. result = (lhs_val != rhs_val);
  1221. break;
  1222. case SemIR::BuiltinFunctionKind::IntLess:
  1223. result = lhs_val.slt(rhs_val);
  1224. break;
  1225. case SemIR::BuiltinFunctionKind::IntLessEq:
  1226. result = lhs_val.sle(rhs_val);
  1227. break;
  1228. case SemIR::BuiltinFunctionKind::IntGreater:
  1229. result = lhs_val.sgt(rhs_val);
  1230. break;
  1231. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  1232. result = lhs_val.sge(rhs_val);
  1233. break;
  1234. default:
  1235. CARBON_FATAL("Unexpected operation kind.");
  1236. }
  1237. return MakeBoolResult(context, bool_type_id, result);
  1238. }
  1239. // Performs a builtin unary float -> float operation.
  1240. static auto PerformBuiltinUnaryFloatOp(Context& context,
  1241. SemIR::BuiltinFunctionKind builtin_kind,
  1242. SemIR::InstId arg_id)
  1243. -> SemIR::ConstantId {
  1244. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  1245. auto op_val = context.floats().Get(op.float_id);
  1246. switch (builtin_kind) {
  1247. case SemIR::BuiltinFunctionKind::FloatNegate:
  1248. op_val.changeSign();
  1249. break;
  1250. default:
  1251. CARBON_FATAL("Unexpected builtin kind");
  1252. }
  1253. return MakeFloatResult(context, op.type_id, std::move(op_val));
  1254. }
  1255. // Performs a builtin binary float -> float operation.
  1256. static auto PerformBuiltinBinaryFloatOp(Context& context,
  1257. SemIR::BuiltinFunctionKind builtin_kind,
  1258. SemIR::InstId lhs_id,
  1259. SemIR::InstId rhs_id)
  1260. -> SemIR::ConstantId {
  1261. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1262. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1263. auto lhs_val = context.floats().Get(lhs.float_id);
  1264. auto rhs_val = context.floats().Get(rhs.float_id);
  1265. llvm::APFloat result_val(lhs_val.getSemantics());
  1266. switch (builtin_kind) {
  1267. case SemIR::BuiltinFunctionKind::FloatAdd:
  1268. result_val = lhs_val + rhs_val;
  1269. break;
  1270. case SemIR::BuiltinFunctionKind::FloatSub:
  1271. result_val = lhs_val - rhs_val;
  1272. break;
  1273. case SemIR::BuiltinFunctionKind::FloatMul:
  1274. result_val = lhs_val * rhs_val;
  1275. break;
  1276. case SemIR::BuiltinFunctionKind::FloatDiv:
  1277. result_val = lhs_val / rhs_val;
  1278. break;
  1279. default:
  1280. CARBON_FATAL("Unexpected operation kind.");
  1281. }
  1282. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  1283. }
  1284. // Performs a builtin float comparison.
  1285. static auto PerformBuiltinFloatComparison(
  1286. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1287. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  1288. -> SemIR::ConstantId {
  1289. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  1290. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  1291. const auto& lhs_val = context.floats().Get(lhs.float_id);
  1292. const auto& rhs_val = context.floats().Get(rhs.float_id);
  1293. bool result;
  1294. switch (builtin_kind) {
  1295. case SemIR::BuiltinFunctionKind::FloatEq:
  1296. result = (lhs_val == rhs_val);
  1297. break;
  1298. case SemIR::BuiltinFunctionKind::FloatNeq:
  1299. result = (lhs_val != rhs_val);
  1300. break;
  1301. case SemIR::BuiltinFunctionKind::FloatLess:
  1302. result = lhs_val < rhs_val;
  1303. break;
  1304. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1305. result = lhs_val <= rhs_val;
  1306. break;
  1307. case SemIR::BuiltinFunctionKind::FloatGreater:
  1308. result = lhs_val > rhs_val;
  1309. break;
  1310. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  1311. result = lhs_val >= rhs_val;
  1312. break;
  1313. default:
  1314. CARBON_FATAL("Unexpected operation kind.");
  1315. }
  1316. return MakeBoolResult(context, bool_type_id, result);
  1317. }
  1318. // Performs a builtin boolean comparison.
  1319. static auto PerformBuiltinBoolComparison(
  1320. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1321. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  1322. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1323. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1324. return MakeBoolResult(context, bool_type_id,
  1325. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1326. ? lhs == rhs
  1327. : lhs != rhs);
  1328. }
  1329. // Returns a constant for a call to a builtin function.
  1330. static auto MakeConstantForBuiltinCall(EvalContext& eval_context,
  1331. SemIR::LocId loc_id, SemIR::Call call,
  1332. SemIR::BuiltinFunctionKind builtin_kind,
  1333. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1334. Phase phase) -> SemIR::ConstantId {
  1335. auto& context = eval_context.context();
  1336. switch (builtin_kind) {
  1337. case SemIR::BuiltinFunctionKind::None:
  1338. CARBON_FATAL("Not a builtin function.");
  1339. case SemIR::BuiltinFunctionKind::NoOp: {
  1340. // Return an empty tuple value.
  1341. auto type_id = GetTupleType(eval_context.context(), {});
  1342. return MakeConstantResult(
  1343. eval_context.context(),
  1344. SemIR::TupleValue{.type_id = type_id,
  1345. .elements_id = SemIR::InstBlockId::Empty},
  1346. phase);
  1347. }
  1348. case SemIR::BuiltinFunctionKind::PrintChar:
  1349. case SemIR::BuiltinFunctionKind::PrintInt:
  1350. case SemIR::BuiltinFunctionKind::ReadChar:
  1351. case SemIR::BuiltinFunctionKind::IntSAddAssign:
  1352. case SemIR::BuiltinFunctionKind::IntSSubAssign:
  1353. case SemIR::BuiltinFunctionKind::IntSMulAssign:
  1354. case SemIR::BuiltinFunctionKind::IntSDivAssign:
  1355. case SemIR::BuiltinFunctionKind::IntSModAssign:
  1356. case SemIR::BuiltinFunctionKind::IntUAddAssign:
  1357. case SemIR::BuiltinFunctionKind::IntUSubAssign:
  1358. case SemIR::BuiltinFunctionKind::IntUMulAssign:
  1359. case SemIR::BuiltinFunctionKind::IntUDivAssign:
  1360. case SemIR::BuiltinFunctionKind::IntUModAssign:
  1361. case SemIR::BuiltinFunctionKind::IntAndAssign:
  1362. case SemIR::BuiltinFunctionKind::IntOrAssign:
  1363. case SemIR::BuiltinFunctionKind::IntXorAssign:
  1364. case SemIR::BuiltinFunctionKind::IntLeftShiftAssign:
  1365. case SemIR::BuiltinFunctionKind::IntRightShiftAssign: {
  1366. // These are runtime-only builtins.
  1367. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1368. return SemIR::ConstantId::NotConstant;
  1369. }
  1370. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1371. CARBON_CHECK(arg_ids.size() == 2);
  1372. auto lhs_facet_type_id = SemIR::FacetTypeId::None;
  1373. auto rhs_facet_type_id = SemIR::FacetTypeId::None;
  1374. for (auto [facet_type_id, type_arg_id] :
  1375. llvm::zip(std::to_array({&lhs_facet_type_id, &rhs_facet_type_id}),
  1376. context.types().GetBlockAsTypeInstIds(arg_ids))) {
  1377. if (auto facet_type =
  1378. context.insts().TryGetAs<SemIR::FacetType>(type_arg_id)) {
  1379. *facet_type_id = facet_type->facet_type_id;
  1380. } else {
  1381. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1382. "non-facet type {0} combined with `&` operator",
  1383. SemIR::TypeId);
  1384. // TODO: Find a location for the lhs or rhs specifically, instead of
  1385. // the whole thing. If that's not possible we can change the text to
  1386. // say if it's referring to the left or the right side for the error.
  1387. // The `arg_id` instruction has no location in it for some reason.
  1388. context.emitter().Emit(
  1389. loc_id, FacetTypeRequiredForTypeAndOperator,
  1390. context.types().GetTypeIdForTypeInstId(type_arg_id));
  1391. }
  1392. }
  1393. // Allow errors to be diagnosed for both sides of the operator before
  1394. // returning here if any error occurred on either side.
  1395. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1396. return SemIR::ErrorInst::ConstantId;
  1397. }
  1398. // Reuse one of the argument instructions if nothing has changed.
  1399. if (lhs_facet_type_id == rhs_facet_type_id) {
  1400. return context.types().GetConstantId(
  1401. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1402. }
  1403. auto info = SemIR::FacetTypeInfo::Combine(
  1404. context.facet_types().Get(lhs_facet_type_id),
  1405. context.facet_types().Get(rhs_facet_type_id));
  1406. info.Canonicalize();
  1407. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1408. }
  1409. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1410. return context.constant_values().Get(SemIR::IntLiteralType::TypeInstId);
  1411. }
  1412. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1413. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Signed,
  1414. arg_ids[0], phase);
  1415. }
  1416. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1417. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Unsigned,
  1418. arg_ids[0], phase);
  1419. }
  1420. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1421. // TODO: Support a symbolic constant width.
  1422. if (phase != Phase::Concrete) {
  1423. break;
  1424. }
  1425. if (!ValidateFloatBitWidth(context, loc_id, arg_ids[0])) {
  1426. return SemIR::ErrorInst::ConstantId;
  1427. }
  1428. return context.constant_values().Get(SemIR::LegacyFloatType::TypeInstId);
  1429. }
  1430. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1431. return context.constant_values().Get(SemIR::BoolType::TypeInstId);
  1432. }
  1433. // Integer conversions.
  1434. case SemIR::BuiltinFunctionKind::IntConvert: {
  1435. if (phase != Phase::Concrete) {
  1436. return MakeConstantResult(context, call, phase);
  1437. }
  1438. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1439. }
  1440. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1441. if (phase != Phase::Concrete) {
  1442. return MakeConstantResult(context, call, phase);
  1443. }
  1444. return PerformCheckedIntConvert(context, loc_id, arg_ids[0],
  1445. call.type_id);
  1446. }
  1447. // Unary integer -> integer operations.
  1448. case SemIR::BuiltinFunctionKind::IntSNegate:
  1449. case SemIR::BuiltinFunctionKind::IntUNegate:
  1450. case SemIR::BuiltinFunctionKind::IntComplement: {
  1451. if (phase != Phase::Concrete) {
  1452. break;
  1453. }
  1454. return PerformBuiltinUnaryIntOp(context, loc_id, builtin_kind,
  1455. arg_ids[0]);
  1456. }
  1457. // Homogeneous binary integer -> integer operations.
  1458. case SemIR::BuiltinFunctionKind::IntSAdd:
  1459. case SemIR::BuiltinFunctionKind::IntSSub:
  1460. case SemIR::BuiltinFunctionKind::IntSMul:
  1461. case SemIR::BuiltinFunctionKind::IntSDiv:
  1462. case SemIR::BuiltinFunctionKind::IntSMod:
  1463. case SemIR::BuiltinFunctionKind::IntUAdd:
  1464. case SemIR::BuiltinFunctionKind::IntUSub:
  1465. case SemIR::BuiltinFunctionKind::IntUMul:
  1466. case SemIR::BuiltinFunctionKind::IntUDiv:
  1467. case SemIR::BuiltinFunctionKind::IntUMod:
  1468. case SemIR::BuiltinFunctionKind::IntAnd:
  1469. case SemIR::BuiltinFunctionKind::IntOr:
  1470. case SemIR::BuiltinFunctionKind::IntXor: {
  1471. if (phase != Phase::Concrete) {
  1472. break;
  1473. }
  1474. return PerformBuiltinBinaryIntOp(context, loc_id, builtin_kind,
  1475. arg_ids[0], arg_ids[1]);
  1476. }
  1477. // Bit shift operations.
  1478. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1479. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1480. if (phase != Phase::Concrete) {
  1481. break;
  1482. }
  1483. return PerformBuiltinIntShiftOp(context, loc_id, builtin_kind, arg_ids[0],
  1484. arg_ids[1]);
  1485. }
  1486. // Integer comparisons.
  1487. case SemIR::BuiltinFunctionKind::IntEq:
  1488. case SemIR::BuiltinFunctionKind::IntNeq:
  1489. case SemIR::BuiltinFunctionKind::IntLess:
  1490. case SemIR::BuiltinFunctionKind::IntLessEq:
  1491. case SemIR::BuiltinFunctionKind::IntGreater:
  1492. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1493. if (phase != Phase::Concrete) {
  1494. break;
  1495. }
  1496. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1497. arg_ids[1], call.type_id);
  1498. }
  1499. // Unary float -> float operations.
  1500. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1501. if (phase != Phase::Concrete) {
  1502. break;
  1503. }
  1504. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1505. }
  1506. // Binary float -> float operations.
  1507. case SemIR::BuiltinFunctionKind::FloatAdd:
  1508. case SemIR::BuiltinFunctionKind::FloatSub:
  1509. case SemIR::BuiltinFunctionKind::FloatMul:
  1510. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1511. if (phase != Phase::Concrete) {
  1512. break;
  1513. }
  1514. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1515. arg_ids[1]);
  1516. }
  1517. // Float comparisons.
  1518. case SemIR::BuiltinFunctionKind::FloatEq:
  1519. case SemIR::BuiltinFunctionKind::FloatNeq:
  1520. case SemIR::BuiltinFunctionKind::FloatLess:
  1521. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1522. case SemIR::BuiltinFunctionKind::FloatGreater:
  1523. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1524. if (phase != Phase::Concrete) {
  1525. break;
  1526. }
  1527. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1528. arg_ids[1], call.type_id);
  1529. }
  1530. // Bool comparisons.
  1531. case SemIR::BuiltinFunctionKind::BoolEq:
  1532. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1533. if (phase != Phase::Concrete) {
  1534. break;
  1535. }
  1536. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1537. arg_ids[1], call.type_id);
  1538. }
  1539. }
  1540. return SemIR::ConstantId::NotConstant;
  1541. }
  1542. // Makes a constant for a call instruction.
  1543. static auto MakeConstantForCall(EvalContext& eval_context,
  1544. SemIR::InstId inst_id, SemIR::Call call)
  1545. -> SemIR::ConstantId {
  1546. Phase phase = Phase::Concrete;
  1547. // A call with an invalid argument list is used to represent an erroneous
  1548. // call.
  1549. //
  1550. // TODO: Use a better representation for this.
  1551. if (call.args_id == SemIR::InstBlockId::None) {
  1552. return SemIR::ErrorInst::ConstantId;
  1553. }
  1554. // Find the constant value of the callee.
  1555. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1556. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1557. auto callee_function =
  1558. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1559. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1560. if (callee_function.function_id.has_value()) {
  1561. // Calls to builtins might be constant.
  1562. builtin_kind = eval_context.functions()
  1563. .Get(callee_function.function_id)
  1564. .builtin_function_kind;
  1565. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1566. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1567. // functions as producing constants.
  1568. return SemIR::ConstantId::NotConstant;
  1569. }
  1570. } else {
  1571. // Calls to non-functions, such as calls to generic entity names, might be
  1572. // constant.
  1573. }
  1574. // Find the argument values and the return type.
  1575. bool has_constant_operands =
  1576. has_constant_callee &&
  1577. ReplaceTypeWithConstantValue(eval_context, inst_id, &call, &phase) &&
  1578. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1579. &phase);
  1580. if (phase == Phase::UnknownDueToError) {
  1581. return SemIR::ErrorInst::ConstantId;
  1582. }
  1583. // If any operand of the call is non-constant, the call is non-constant.
  1584. // TODO: Some builtin calls might allow some operands to be non-constant.
  1585. if (!has_constant_operands) {
  1586. if (builtin_kind.IsCompTimeOnly(
  1587. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1588. call.type_id)) {
  1589. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1590. "non-constant call to compile-time-only function");
  1591. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1592. "compile-time-only function declared here");
  1593. eval_context.emitter()
  1594. .Build(inst_id, NonConstantCallToCompTimeOnlyFunction)
  1595. .Note(eval_context.functions()
  1596. .Get(callee_function.function_id)
  1597. .latest_decl_id(),
  1598. CompTimeOnlyFunctionHere)
  1599. .Emit();
  1600. }
  1601. return SemIR::ConstantId::NotConstant;
  1602. }
  1603. // Handle calls to builtins.
  1604. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1605. return MakeConstantForBuiltinCall(
  1606. eval_context, SemIR::LocId(inst_id), call, builtin_kind,
  1607. eval_context.inst_blocks().Get(call.args_id), phase);
  1608. }
  1609. return SemIR::ConstantId::NotConstant;
  1610. }
  1611. // Given an instruction, compute its phase based on its operands.
  1612. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1613. EvalContext eval_context(&context, SemIR::LocId::None);
  1614. auto phase = GetPhase(context.constant_values(),
  1615. context.types().GetConstantId(inst.type_id()));
  1616. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  1617. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  1618. CARBON_CHECK(phase != Phase::Runtime);
  1619. return phase;
  1620. }
  1621. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1622. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1623. static auto ConvertEvalResultToConstantId(Context& context,
  1624. ConstantEvalResult result,
  1625. Phase orig_phase)
  1626. -> SemIR::ConstantId {
  1627. if (result.is_new()) {
  1628. return MakeConstantResult(
  1629. context, result.new_inst(),
  1630. result.same_phase_as_inst()
  1631. ? orig_phase
  1632. : ComputeInstPhase(context, result.new_inst()));
  1633. }
  1634. return result.existing();
  1635. }
  1636. // Evaluates an instruction of a known type in an evaluation context. The
  1637. // default behavior of this function depends on the constant kind of the
  1638. // instruction:
  1639. //
  1640. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  1641. // - InstConstantKind::Indirect, SymbolicOnly, SymbolicOrReference,
  1642. // Conditional: evaluates all the operands of the instruction, and calls
  1643. // `EvalConstantInst` to evaluate the resulting constant instruction.
  1644. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  1645. // the instruction, and produces the resulting constant instruction as the
  1646. // result.
  1647. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  1648. // constant.
  1649. //
  1650. // Returns an error constant ID if any of the nested evaluations fail, and
  1651. // returns NotConstant if any of the nested evaluations is non-constant.
  1652. //
  1653. // This template is explicitly specialized for instructions that need special
  1654. // handling.
  1655. template <typename InstT>
  1656. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  1657. SemIR::Inst inst) -> SemIR::ConstantId {
  1658. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  1659. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  1660. return SemIR::ConstantId::NotConstant;
  1661. } else if constexpr (ConstantKind == SemIR::InstConstantKind::AlwaysUnique) {
  1662. CARBON_CHECK(inst_id.has_value());
  1663. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  1664. } else {
  1665. // Build a constant instruction by replacing each non-constant operand with
  1666. // its constant value.
  1667. Phase phase = Phase::Concrete;
  1668. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase) ||
  1669. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  1670. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  1671. CARBON_CHECK(phase == Phase::UnknownDueToError,
  1672. "{0} should always be constant", InstT::Kind);
  1673. }
  1674. return MakeNonConstantResult(phase);
  1675. }
  1676. // When canonicalizing a SpecificId, we defer resolving the specific's
  1677. // declaration until here, to avoid resolving declarations from imported
  1678. // specifics. (Imported instructions are not evaluated.)
  1679. ResolveSpecificDeclForInst(eval_context, inst);
  1680. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  1681. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  1682. return MakeConstantResult(eval_context.context(), inst, phase);
  1683. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  1684. auto result_inst_id = PerformDelayedAction(
  1685. eval_context.context(), SemIR::LocId(inst_id), inst.As<InstT>());
  1686. if (result_inst_id.has_value()) {
  1687. // The result is an instruction.
  1688. return MakeConstantResult(
  1689. eval_context.context(),
  1690. SemIR::InstValue{.type_id = SemIR::InstType::TypeId,
  1691. .inst_id = result_inst_id},
  1692. Phase::Concrete);
  1693. }
  1694. // Couldn't perform the action because it's still dependent.
  1695. return MakeConstantResult(eval_context.context(), inst,
  1696. Phase::TemplateSymbolic);
  1697. } else if constexpr (InstT::Kind.constant_needs_inst_id() !=
  1698. SemIR::InstConstantNeedsInstIdKind::No) {
  1699. CARBON_CHECK(inst_id.has_value());
  1700. return ConvertEvalResultToConstantId(
  1701. eval_context.context(),
  1702. EvalConstantInst(eval_context.context(), inst_id, inst.As<InstT>()),
  1703. phase);
  1704. } else {
  1705. return ConvertEvalResultToConstantId(
  1706. eval_context.context(),
  1707. EvalConstantInst(eval_context.context(), inst.As<InstT>()), phase);
  1708. }
  1709. }
  1710. }
  1711. // Specialize evaluation for array indexing because we want to check the index
  1712. // expression even if the array expression is non-constant.
  1713. template <>
  1714. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  1715. SemIR::InstId /*inst_id*/,
  1716. SemIR::Inst inst)
  1717. -> SemIR::ConstantId {
  1718. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  1719. }
  1720. // Specialize evaluation for function calls because we want to check the callee
  1721. // expression even if an argument expression is non-constant, and because we
  1722. // will eventually want to perform control flow handling here.
  1723. template <>
  1724. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  1725. SemIR::InstId inst_id, SemIR::Inst inst)
  1726. -> SemIR::ConstantId {
  1727. return MakeConstantForCall(eval_context, inst_id, inst.As<SemIR::Call>());
  1728. }
  1729. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  1730. // `import_ref.cpp`, not by us.
  1731. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  1732. // call this.
  1733. template <>
  1734. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  1735. SemIR::InstId /*inst_id*/,
  1736. SemIR::Inst /*inst*/)
  1737. -> SemIR::ConstantId {
  1738. return SemIR::ConstantId::NotConstant;
  1739. }
  1740. // Symbolic bindings are a special case because they can reach into the eval
  1741. // context and produce a context-specific value.
  1742. template <>
  1743. auto TryEvalTypedInst<SemIR::BindSymbolicName>(EvalContext& eval_context,
  1744. SemIR::InstId inst_id,
  1745. SemIR::Inst inst)
  1746. -> SemIR::ConstantId {
  1747. auto bind = inst.As<SemIR::BindSymbolicName>();
  1748. // If we know which specific we're evaluating within and this is an argument
  1749. // of that specific, its constant value is the corresponding argument value.
  1750. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  1751. if (bind_name.bind_index().has_value()) {
  1752. if (auto value =
  1753. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  1754. value.has_value()) {
  1755. return value;
  1756. }
  1757. }
  1758. // The constant form of a symbolic binding is an idealized form of the
  1759. // original, with no equivalent value.
  1760. Phase phase = Phase::Concrete;
  1761. bind.value_id = SemIR::InstId::None;
  1762. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &bind, &phase) ||
  1763. !ReplaceFieldWithConstantValue(eval_context, &bind,
  1764. &SemIR::BindSymbolicName::entity_name_id,
  1765. &phase)) {
  1766. return MakeNonConstantResult(phase);
  1767. }
  1768. return MakeConstantResult(eval_context.context(), bind, phase);
  1769. }
  1770. static auto IsPeriodSelf(EvalContext& eval_context, SemIR::ConstantId const_id)
  1771. -> bool {
  1772. // This also rejects the singleton Error value as it's concrete.
  1773. if (!const_id.is_symbolic()) {
  1774. return false;
  1775. }
  1776. const auto& symbolic =
  1777. eval_context.constant_values().GetSymbolicConstant(const_id);
  1778. // Fast early reject before doing more expensive operations.
  1779. if (symbolic.dependence != SemIR::ConstantDependence::PeriodSelf) {
  1780. return false;
  1781. }
  1782. auto inst_id = symbolic.inst_id;
  1783. // Unwrap the `FacetAccessType` instruction, which we get when the `.Self` is
  1784. // converted to `type`.
  1785. if (auto facet_access_type =
  1786. eval_context.insts().TryGetAs<SemIR::FacetAccessType>(inst_id)) {
  1787. inst_id = facet_access_type->facet_value_inst_id;
  1788. }
  1789. if (auto bind_symbolic_name =
  1790. eval_context.insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  1791. const auto& bind_name =
  1792. eval_context.entity_names().Get(bind_symbolic_name->entity_name_id);
  1793. return bind_name.name_id == SemIR::NameId::PeriodSelf;
  1794. }
  1795. return false;
  1796. }
  1797. // TODO: Convert this to an EvalConstantInst instruction. This will require
  1798. // providing a `GetConstantValue` overload for a requirement block.
  1799. template <>
  1800. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  1801. SemIR::InstId /*inst_id*/,
  1802. SemIR::Inst inst) -> SemIR::ConstantId {
  1803. auto typed_inst = inst.As<SemIR::WhereExpr>();
  1804. Phase phase = Phase::Concrete;
  1805. SemIR::TypeId base_facet_type_id =
  1806. eval_context.GetTypeOfInst(typed_inst.period_self_id);
  1807. SemIR::Inst base_facet_inst =
  1808. eval_context.types().GetAsInst(base_facet_type_id);
  1809. SemIR::FacetTypeInfo info = {.other_requirements = false};
  1810. // `where` provides that the base facet is an error, `type`, or a facet
  1811. // type.
  1812. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1813. info = GetConstantFacetTypeInfo(eval_context, facet_type->facet_type_id,
  1814. &phase);
  1815. } else if (base_facet_type_id == SemIR::ErrorInst::TypeId) {
  1816. return SemIR::ErrorInst::ConstantId;
  1817. } else {
  1818. CARBON_CHECK(base_facet_type_id == SemIR::TypeType::TypeId,
  1819. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1820. base_facet_inst);
  1821. }
  1822. if (typed_inst.requirements_id.has_value()) {
  1823. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  1824. for (auto inst_id : insts) {
  1825. if (auto rewrite =
  1826. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  1827. inst_id)) {
  1828. // `where` requirements using `.Self` should not be considered
  1829. // symbolic.
  1830. auto lhs_id = GetConstantValueIgnoringPeriodSelf(
  1831. eval_context, rewrite->lhs_id, &phase);
  1832. auto rhs_id = GetConstantValueIgnoringPeriodSelf(
  1833. eval_context, rewrite->rhs_id, &phase);
  1834. info.rewrite_constraints.push_back(
  1835. {.lhs_id = lhs_id, .rhs_id = rhs_id});
  1836. } else if (auto impls =
  1837. eval_context.insts().TryGetAs<SemIR::RequirementImpls>(
  1838. inst_id)) {
  1839. SemIR::ConstantId lhs = eval_context.GetConstantValue(impls->lhs_id);
  1840. SemIR::ConstantId rhs = eval_context.GetConstantValue(impls->rhs_id);
  1841. if (rhs != SemIR::ErrorInst::ConstantId &&
  1842. IsPeriodSelf(eval_context, lhs)) {
  1843. auto rhs_inst_id = eval_context.constant_values().GetInstId(rhs);
  1844. if (rhs_inst_id == SemIR::TypeType::TypeInstId) {
  1845. // `.Self impls type` -> nothing to do.
  1846. } else {
  1847. auto facet_type =
  1848. eval_context.insts().GetAs<SemIR::FacetType>(rhs_inst_id);
  1849. SemIR::FacetTypeInfo more_info = GetConstantFacetTypeInfo(
  1850. eval_context, facet_type.facet_type_id, &phase);
  1851. // The way to prevent lookup into the interface requirements of a
  1852. // facet type is to put it to the right of a `.Self impls`, which we
  1853. // accomplish by putting them into `self_impls_constraints`.
  1854. llvm::append_range(info.self_impls_constraints,
  1855. more_info.extend_constraints);
  1856. llvm::append_range(info.self_impls_constraints,
  1857. more_info.self_impls_constraints);
  1858. // Other requirements are copied in.
  1859. llvm::append_range(info.rewrite_constraints,
  1860. more_info.rewrite_constraints);
  1861. info.other_requirements |= more_info.other_requirements;
  1862. }
  1863. } else {
  1864. // TODO: Handle `impls` constraints beyond `.Self impls`.
  1865. info.other_requirements = true;
  1866. }
  1867. } else {
  1868. // TODO: Handle other requirements
  1869. info.other_requirements = true;
  1870. }
  1871. }
  1872. }
  1873. info.Canonicalize();
  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