eval.cpp 83 KB

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