eval.cpp 88 KB

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