eval.cpp 90 KB

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