eval.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  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 "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/diagnostic_helpers.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/diagnostics/diagnostic_emitter.h"
  9. #include "toolchain/diagnostics/format_providers.h"
  10. #include "toolchain/sem_ir/builtin_function_kind.h"
  11. #include "toolchain/sem_ir/function.h"
  12. #include "toolchain/sem_ir/generic.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/inst_kind.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Check {
  17. namespace {
  18. // Information about an eval block of a specific that we are currently building.
  19. struct SpecificEvalInfo {
  20. // The region within the specific whose eval block we are building.
  21. SemIR::GenericInstIndex::Region region;
  22. // The work-in-progress contents of the eval block.
  23. llvm::ArrayRef<SemIR::InstId> values;
  24. };
  25. // Information about the context within which we are performing evaluation.
  26. class EvalContext {
  27. public:
  28. explicit EvalContext(
  29. Context& context,
  30. SemIR::SpecificId specific_id = SemIR::SpecificId::Invalid,
  31. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  32. : context_(context),
  33. specific_id_(specific_id),
  34. specific_eval_info_(specific_eval_info) {}
  35. // Gets the value of the specified compile-time binding in this context.
  36. // Returns `Invalid` if the value is not fixed in this context.
  37. auto GetCompileTimeBindValue(SemIR::CompileTimeBindIndex bind_index)
  38. -> SemIR::ConstantId {
  39. if (!bind_index.is_valid() || !specific_id_.is_valid()) {
  40. return SemIR::ConstantId::Invalid;
  41. }
  42. const auto& specific = specifics().Get(specific_id_);
  43. auto args = inst_blocks().Get(specific.args_id);
  44. // Bindings past the ones with known arguments can appear as local
  45. // bindings of entities declared within this generic.
  46. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  47. return SemIR::ConstantId::Invalid;
  48. }
  49. return constant_values().Get(args[bind_index.index]);
  50. }
  51. // Given a constant value from the SemIR we're evaluating, finds the
  52. // corresponding constant value to use in the context of this evaluation.
  53. // This can be different if the original SemIR is for a generic and we are
  54. // evaluating with specific arguments for the generic parameters.
  55. auto GetInContext(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  56. if (!const_id.is_symbolic()) {
  57. return const_id;
  58. }
  59. // While resolving a specific, map from previous instructions in the eval
  60. // block into their evaluated values. These values won't be present on the
  61. // specific itself yet, so `GetConstantInSpecific` won't be able to find
  62. // them.
  63. if (specific_eval_info_) {
  64. const auto& symbolic_info =
  65. constant_values().GetSymbolicConstant(const_id);
  66. if (symbolic_info.index.is_valid() &&
  67. symbolic_info.generic_id ==
  68. specifics().Get(specific_id_).generic_id &&
  69. symbolic_info.index.region() == specific_eval_info_->region) {
  70. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  71. CARBON_CHECK(inst_id.is_valid(),
  72. "Forward reference in eval block: index {0} referenced "
  73. "before evaluation",
  74. symbolic_info.index.index());
  75. return constant_values().Get(inst_id);
  76. }
  77. }
  78. // Map from a specific constant value to the canonical value.
  79. return GetConstantInSpecific(sem_ir(), specific_id_, const_id);
  80. }
  81. // Gets the constant value of the specified instruction in this context.
  82. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  83. return GetInContext(constant_values().Get(inst_id));
  84. }
  85. // Gets the constant value of the specified type in this context.
  86. auto GetConstantValue(SemIR::TypeId type_id) -> SemIR::ConstantId {
  87. return GetInContext(types().GetConstantId(type_id));
  88. }
  89. // Gets the constant value of the specified type in this context.
  90. auto GetConstantValueAsType(SemIR::TypeId id) -> SemIR::TypeId {
  91. return context().GetTypeIdForTypeConstant(GetConstantValue(id));
  92. }
  93. // Gets the instruction describing the constant value of the specified type in
  94. // this context.
  95. auto GetConstantValueAsInst(SemIR::TypeId id) -> SemIR::Inst {
  96. return insts().Get(
  97. context().constant_values().GetInstId(GetConstantValue(id)));
  98. }
  99. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  100. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  101. auto entity_names() -> SemIR::EntityNameStore& {
  102. return sem_ir().entity_names();
  103. }
  104. auto functions() -> const ValueStore<SemIR::FunctionId>& {
  105. return sem_ir().functions();
  106. }
  107. auto classes() -> const ValueStore<SemIR::ClassId>& {
  108. return sem_ir().classes();
  109. }
  110. auto interfaces() -> const ValueStore<SemIR::InterfaceId>& {
  111. return sem_ir().interfaces();
  112. }
  113. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  114. return sem_ir().facet_types();
  115. }
  116. auto specifics() -> const SemIR::SpecificStore& {
  117. return sem_ir().specifics();
  118. }
  119. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  120. return sem_ir().type_blocks();
  121. }
  122. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  123. auto inst_blocks() -> SemIR::InstBlockStore& {
  124. return sem_ir().inst_blocks();
  125. }
  126. // Gets the constant value store. Note that this does not provide the constant
  127. // values that should be used from this evaluation context, and so should be
  128. // used with caution.
  129. auto constant_values() -> const SemIR::ConstantValueStore& {
  130. return sem_ir().constant_values();
  131. }
  132. // Gets the types store. Note that this does not provide the type values that
  133. // should be used from this evaluation context, and so should be used with
  134. // caution.
  135. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  136. auto context() -> Context& { return context_; }
  137. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  138. auto emitter() -> Context::DiagnosticEmitter& { return context().emitter(); }
  139. private:
  140. // The type-checking context in which we're performing evaluation.
  141. Context& context_;
  142. // The specific that we are evaluating within.
  143. SemIR::SpecificId specific_id_;
  144. // If we are currently evaluating an eval block for `specific_id_`,
  145. // information about that evaluation.
  146. std::optional<SpecificEvalInfo> specific_eval_info_;
  147. };
  148. } // namespace
  149. namespace {
  150. // The evaluation phase for an expression, computed by evaluation. These are
  151. // ordered so that the phase of an expression is the numerically highest phase
  152. // of its constituent evaluations. Note that an expression with any runtime
  153. // component is known to have Runtime phase even if it involves an evaluation
  154. // with UnknownDueToError phase.
  155. enum class Phase : uint8_t {
  156. // Value could be entirely and concretely computed.
  157. Template,
  158. // Evaluation phase is symbolic because the expression involves a reference to
  159. // a symbolic binding.
  160. Symbolic,
  161. // The evaluation phase is unknown because evaluation encountered an
  162. // already-diagnosed semantic or syntax error. This is treated as being
  163. // potentially constant, but with an unknown phase.
  164. UnknownDueToError,
  165. // The expression has runtime phase because of a non-constant subexpression.
  166. Runtime,
  167. };
  168. } // namespace
  169. // Gets the phase in which the value of a constant will become available.
  170. static auto GetPhase(SemIR::ConstantId constant_id) -> Phase {
  171. if (!constant_id.is_constant()) {
  172. return Phase::Runtime;
  173. } else if (constant_id == SemIR::ConstantId::Error) {
  174. return Phase::UnknownDueToError;
  175. } else if (constant_id.is_template()) {
  176. return Phase::Template;
  177. } else {
  178. CARBON_CHECK(constant_id.is_symbolic());
  179. return Phase::Symbolic;
  180. }
  181. }
  182. // Returns the later of two phases.
  183. static auto LatestPhase(Phase a, Phase b) -> Phase {
  184. return static_cast<Phase>(
  185. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  186. }
  187. // Forms a `constant_id` describing a given evaluation result.
  188. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  189. -> SemIR::ConstantId {
  190. switch (phase) {
  191. case Phase::Template:
  192. return context.AddConstant(inst, /*is_symbolic=*/false);
  193. case Phase::Symbolic:
  194. return context.AddConstant(inst, /*is_symbolic=*/true);
  195. case Phase::UnknownDueToError:
  196. return SemIR::ConstantId::Error;
  197. case Phase::Runtime:
  198. return SemIR::ConstantId::NotConstant;
  199. }
  200. }
  201. // Forms a `constant_id` describing why an evaluation was not constant.
  202. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  203. return phase == Phase::UnknownDueToError ? SemIR::ConstantId::Error
  204. : SemIR::ConstantId::NotConstant;
  205. }
  206. // Converts a bool value into a ConstantId.
  207. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  208. bool result) -> SemIR::ConstantId {
  209. return MakeConstantResult(
  210. context,
  211. SemIR::BoolLiteral{.type_id = bool_type_id,
  212. .value = SemIR::BoolValue::From(result)},
  213. Phase::Template);
  214. }
  215. // Converts an APInt value into a ConstantId.
  216. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  217. llvm::APInt value) -> SemIR::ConstantId {
  218. auto result = context.ints().Add(std::move(value));
  219. return MakeConstantResult(
  220. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  221. Phase::Template);
  222. }
  223. // Converts an APFloat value into a ConstantId.
  224. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  225. llvm::APFloat value) -> SemIR::ConstantId {
  226. auto result = context.floats().Add(std::move(value));
  227. return MakeConstantResult(
  228. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  229. Phase::Template);
  230. }
  231. // `GetConstantValue` checks to see whether the provided ID describes a value
  232. // with constant phase, and if so, returns the corresponding constant value.
  233. // Overloads are provided for different kinds of ID.
  234. // If the given instruction is constant, returns its constant value.
  235. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  236. Phase* phase) -> SemIR::InstId {
  237. auto const_id = eval_context.GetConstantValue(inst_id);
  238. *phase = LatestPhase(*phase, GetPhase(const_id));
  239. return eval_context.constant_values().GetInstId(const_id);
  240. }
  241. // Given a type which may refer to a generic parameter, returns the
  242. // corresponding type in the evaluation context.
  243. static auto GetConstantValue(EvalContext& eval_context, SemIR::TypeId type_id,
  244. Phase* phase) -> SemIR::TypeId {
  245. auto const_id = eval_context.GetConstantValue(type_id);
  246. *phase = LatestPhase(*phase, GetPhase(const_id));
  247. return eval_context.context().GetTypeIdForTypeConstant(const_id);
  248. }
  249. // If the given instruction block contains only constants, returns a
  250. // corresponding block of those values.
  251. static auto GetConstantValue(EvalContext& eval_context,
  252. SemIR::InstBlockId inst_block_id, Phase* phase)
  253. -> SemIR::InstBlockId {
  254. if (!inst_block_id.is_valid()) {
  255. return SemIR::InstBlockId::Invalid;
  256. }
  257. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  258. llvm::SmallVector<SemIR::InstId> const_insts;
  259. for (auto inst_id : insts) {
  260. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  261. if (!const_inst_id.is_valid()) {
  262. return SemIR::InstBlockId::Invalid;
  263. }
  264. // Once we leave the small buffer, we know the first few elements are all
  265. // constant, so it's likely that the entire block is constant. Resize to the
  266. // target size given that we're going to allocate memory now anyway.
  267. if (const_insts.size() == const_insts.capacity()) {
  268. const_insts.reserve(insts.size());
  269. }
  270. const_insts.push_back(const_inst_id);
  271. }
  272. // TODO: If the new block is identical to the original block, and we know the
  273. // old ID was canonical, return the original ID.
  274. return eval_context.inst_blocks().AddCanonical(const_insts);
  275. }
  276. // Compute the constant value of a type block. This may be different from the
  277. // input type block if we have known generic arguments.
  278. static auto GetConstantValue(EvalContext& eval_context,
  279. SemIR::TypeBlockId type_block_id, Phase* phase)
  280. -> SemIR::TypeBlockId {
  281. if (!type_block_id.is_valid()) {
  282. return SemIR::TypeBlockId::Invalid;
  283. }
  284. auto types = eval_context.type_blocks().Get(type_block_id);
  285. llvm::SmallVector<SemIR::TypeId> new_types;
  286. for (auto type_id : types) {
  287. auto new_type_id = GetConstantValue(eval_context, type_id, phase);
  288. if (!new_type_id.is_valid()) {
  289. return SemIR::TypeBlockId::Invalid;
  290. }
  291. // Once we leave the small buffer, we know the first few elements are all
  292. // constant, so it's likely that the entire block is constant. Resize to the
  293. // target size given that we're going to allocate memory now anyway.
  294. if (new_types.size() == new_types.capacity()) {
  295. new_types.reserve(types.size());
  296. }
  297. new_types.push_back(new_type_id);
  298. }
  299. // TODO: If the new block is identical to the original block, and we know the
  300. // old ID was canonical, return the original ID.
  301. return eval_context.type_blocks().AddCanonical(new_types);
  302. }
  303. // The constant value of a specific is the specific with the corresponding
  304. // constant values for its arguments.
  305. static auto GetConstantValue(EvalContext& eval_context,
  306. SemIR::SpecificId specific_id, Phase* phase)
  307. -> SemIR::SpecificId {
  308. if (!specific_id.is_valid()) {
  309. return SemIR::SpecificId::Invalid;
  310. }
  311. const auto& specific = eval_context.specifics().Get(specific_id);
  312. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  313. if (!args_id.is_valid()) {
  314. return SemIR::SpecificId::Invalid;
  315. }
  316. if (args_id == specific.args_id) {
  317. return specific_id;
  318. }
  319. return MakeSpecific(eval_context.context(), specific.generic_id, args_id);
  320. }
  321. // Replaces the specified field of the given typed instruction with its constant
  322. // value, if it has constant phase. Returns true on success, false if the value
  323. // has runtime phase.
  324. template <typename InstT, typename FieldIdT>
  325. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  326. InstT* inst, FieldIdT InstT::*field,
  327. Phase* phase) -> bool {
  328. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  329. if (!unwrapped.is_valid() && (inst->*field).is_valid()) {
  330. return false;
  331. }
  332. inst->*field = unwrapped;
  333. return true;
  334. }
  335. // If the specified fields of the given typed instruction have constant values,
  336. // replaces the fields with their constant values and builds a corresponding
  337. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  338. // `ConstantId::Error` if any subexpression is an error.
  339. //
  340. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  341. // which should return a `bool` indicating whether the new constant is valid. If
  342. // validation passes, `transform_fn(typed_inst)` is called to produce the final
  343. // constant instruction, and a corresponding ConstantId for the new constant is
  344. // returned. If validation fails, it should produce a suitable error message.
  345. // `ConstantId::Error` is returned.
  346. template <typename InstT, typename ValidateFn, typename TransformFn,
  347. typename... EachFieldIdT>
  348. static auto RebuildIfFieldsAreConstantImpl(
  349. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  350. TransformFn transform_fn, EachFieldIdT InstT::*... each_field_id)
  351. -> SemIR::ConstantId {
  352. // Build a constant instruction by replacing each non-constant operand with
  353. // its constant value.
  354. auto typed_inst = inst.As<InstT>();
  355. Phase phase = Phase::Template;
  356. if ((ReplaceFieldWithConstantValue(eval_context, &typed_inst, each_field_id,
  357. &phase) &&
  358. ...)) {
  359. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  360. return SemIR::ConstantId::Error;
  361. }
  362. return MakeConstantResult(eval_context.context(), transform_fn(typed_inst),
  363. phase);
  364. }
  365. return MakeNonConstantResult(phase);
  366. }
  367. // Same as above but with an identity transform function.
  368. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  369. static auto RebuildAndValidateIfFieldsAreConstant(
  370. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  371. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  372. return RebuildIfFieldsAreConstantImpl(eval_context, inst, validate_fn,
  373. std::identity{}, each_field_id...);
  374. }
  375. // Same as above but with no validation step.
  376. template <typename InstT, typename TransformFn, typename... EachFieldIdT>
  377. static auto TransformIfFieldsAreConstant(EvalContext& eval_context,
  378. SemIR::Inst inst,
  379. TransformFn transform_fn,
  380. EachFieldIdT InstT::*... each_field_id)
  381. -> SemIR::ConstantId {
  382. return RebuildIfFieldsAreConstantImpl(
  383. eval_context, inst, [](...) { return true; }, transform_fn,
  384. each_field_id...);
  385. }
  386. // Same as above but with no validation or transform step.
  387. template <typename InstT, typename... EachFieldIdT>
  388. static auto RebuildIfFieldsAreConstant(EvalContext& eval_context,
  389. SemIR::Inst inst,
  390. EachFieldIdT InstT::*... each_field_id)
  391. -> SemIR::ConstantId {
  392. return RebuildIfFieldsAreConstantImpl(
  393. eval_context, inst, [](...) { return true; }, std::identity{},
  394. each_field_id...);
  395. }
  396. // Rebuilds the given aggregate initialization instruction as a corresponding
  397. // constant aggregate value, if its elements are all constants.
  398. static auto RebuildInitAsValue(EvalContext& eval_context, SemIR::Inst inst,
  399. SemIR::InstKind value_kind)
  400. -> SemIR::ConstantId {
  401. return TransformIfFieldsAreConstant(
  402. eval_context, inst,
  403. [&](SemIR::AnyAggregateInit result) {
  404. return SemIR::AnyAggregateValue{.kind = value_kind,
  405. .type_id = result.type_id,
  406. .elements_id = result.elements_id};
  407. },
  408. &SemIR::AnyAggregateInit::type_id, &SemIR::AnyAggregateInit::elements_id);
  409. }
  410. // Performs an access into an aggregate, retrieving the specified element.
  411. static auto PerformAggregateAccess(EvalContext& eval_context, SemIR::Inst inst)
  412. -> SemIR::ConstantId {
  413. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  414. Phase phase = Phase::Template;
  415. if (auto aggregate_id =
  416. GetConstantValue(eval_context, access_inst.aggregate_id, &phase);
  417. aggregate_id.is_valid()) {
  418. if (auto aggregate =
  419. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(
  420. aggregate_id)) {
  421. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  422. auto index = static_cast<size_t>(access_inst.index.index);
  423. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  424. // `Phase` is not used here. If this element is a template constant, then
  425. // so is the result of indexing, even if the aggregate also contains a
  426. // symbolic context.
  427. return eval_context.GetConstantValue(elements[index]);
  428. } else {
  429. CARBON_CHECK(phase != Phase::Template,
  430. "Failed to evaluate template constant {0}", inst);
  431. }
  432. }
  433. return MakeNonConstantResult(phase);
  434. }
  435. // Performs an index into a homogeneous aggregate, retrieving the specified
  436. // element.
  437. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  438. -> SemIR::ConstantId {
  439. Phase phase = Phase::Template;
  440. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  441. if (!index_id.is_valid()) {
  442. return MakeNonConstantResult(phase);
  443. }
  444. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  445. if (!index) {
  446. CARBON_CHECK(phase != Phase::Template,
  447. "Template constant integer should be a literal");
  448. return MakeNonConstantResult(phase);
  449. }
  450. // Array indexing is invalid if the index is constant and out of range,
  451. // regardless of whether the array itself is constant.
  452. const auto& index_val = eval_context.ints().Get(index->int_id);
  453. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  454. eval_context.insts().Get(inst.array_id).type_id());
  455. if (auto array_type =
  456. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  457. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  458. array_type->bound_id)) {
  459. // This awkward call to `getZExtValue` is a workaround for APInt not
  460. // supporting comparisons between integers of different bit widths.
  461. if (index_val.getActiveBits() > 64 ||
  462. eval_context.ints()
  463. .Get(bound->int_id)
  464. .ule(index_val.getZExtValue())) {
  465. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  466. "array index `{0}` is past the end of type {1}",
  467. TypedInt, SemIR::TypeId);
  468. eval_context.emitter().Emit(
  469. inst.index_id, ArrayIndexOutOfBounds,
  470. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  471. return SemIR::ConstantId::Error;
  472. }
  473. }
  474. }
  475. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  476. if (!aggregate_id.is_valid()) {
  477. return MakeNonConstantResult(phase);
  478. }
  479. auto aggregate =
  480. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  481. if (!aggregate) {
  482. CARBON_CHECK(phase != Phase::Template,
  483. "Unexpected representation for template constant aggregate");
  484. return MakeNonConstantResult(phase);
  485. }
  486. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  487. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  488. }
  489. // Enforces that an integer type has a valid bit width.
  490. static auto ValidateIntType(Context& context, SemIRLoc loc,
  491. SemIR::IntType result) -> bool {
  492. auto bit_width =
  493. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  494. if (!bit_width) {
  495. // Symbolic bit width.
  496. return true;
  497. }
  498. const auto& bit_width_val = context.ints().Get(bit_width->int_id);
  499. if (bit_width_val.isZero() ||
  500. (context.types().IsSignedInt(bit_width->type_id) &&
  501. bit_width_val.isNegative())) {
  502. CARBON_DIAGNOSTIC(IntWidthNotPositive, Error,
  503. "integer type width of {0} is not positive", TypedInt);
  504. context.emitter().Emit(
  505. loc, IntWidthNotPositive,
  506. {.type = bit_width->type_id, .value = bit_width_val});
  507. return false;
  508. }
  509. // TODO: Pick a maximum size and document it in the design. For now
  510. // we use 2^^23, because that's the largest size that LLVM supports.
  511. constexpr int MaxIntWidth = 1 << 23;
  512. if (bit_width_val.ugt(MaxIntWidth)) {
  513. CARBON_DIAGNOSTIC(IntWidthTooLarge, Error,
  514. "integer type width of {0} is greater than the "
  515. "maximum supported width of {1}",
  516. TypedInt, int);
  517. context.emitter().Emit(loc, IntWidthTooLarge,
  518. {.type = bit_width->type_id, .value = bit_width_val},
  519. MaxIntWidth);
  520. return false;
  521. }
  522. return true;
  523. }
  524. // Forms a constant int type as an evaluation result. Requires that width_id is
  525. // constant.
  526. static auto MakeIntTypeResult(Context& context, SemIRLoc loc,
  527. SemIR::IntKind int_kind, SemIR::InstId width_id,
  528. Phase phase) -> SemIR::ConstantId {
  529. auto result = SemIR::IntType{
  530. .type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::TypeType),
  531. .int_kind = int_kind,
  532. .bit_width_id = width_id};
  533. if (!ValidateIntType(context, loc, result)) {
  534. return SemIR::ConstantId::Error;
  535. }
  536. return MakeConstantResult(context, result, phase);
  537. }
  538. // Enforces that the bit width is 64 for a float.
  539. static auto ValidateFloatBitWidth(Context& context, SemIRLoc loc,
  540. SemIR::InstId inst_id) -> bool {
  541. auto inst = context.insts().GetAs<SemIR::IntValue>(inst_id);
  542. if (context.ints().Get(inst.int_id) == 64) {
  543. return true;
  544. }
  545. CARBON_DIAGNOSTIC(CompileTimeFloatBitWidth, Error, "bit width must be 64");
  546. context.emitter().Emit(loc, CompileTimeFloatBitWidth);
  547. return false;
  548. }
  549. // Enforces that a float type has a valid bit width.
  550. static auto ValidateFloatType(Context& context, SemIRLoc loc,
  551. SemIR::FloatType result) -> bool {
  552. auto bit_width =
  553. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  554. if (!bit_width) {
  555. // Symbolic bit width.
  556. return true;
  557. }
  558. return ValidateFloatBitWidth(context, loc, result.bit_width_id);
  559. }
  560. // Issues a diagnostic for a compile-time division by zero.
  561. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  562. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  563. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  564. }
  565. // Performs a builtin unary integer -> integer operation.
  566. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  567. SemIR::BuiltinFunctionKind builtin_kind,
  568. SemIR::InstId arg_id)
  569. -> SemIR::ConstantId {
  570. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  571. auto op_val = context.ints().Get(op.int_id);
  572. switch (builtin_kind) {
  573. case SemIR::BuiltinFunctionKind::IntSNegate:
  574. if (context.types().IsSignedInt(op.type_id) &&
  575. op_val.isMinSignedValue()) {
  576. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  577. "integer overflow in negation of {0}", TypedInt);
  578. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  579. {.type = op.type_id, .value = op_val});
  580. }
  581. op_val.negate();
  582. break;
  583. case SemIR::BuiltinFunctionKind::IntUNegate:
  584. op_val.negate();
  585. break;
  586. case SemIR::BuiltinFunctionKind::IntComplement:
  587. op_val.flipAllBits();
  588. break;
  589. default:
  590. CARBON_FATAL("Unexpected builtin kind");
  591. }
  592. return MakeIntResult(context, op.type_id, std::move(op_val));
  593. }
  594. // Performs a builtin binary integer -> integer operation.
  595. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  596. SemIR::BuiltinFunctionKind builtin_kind,
  597. SemIR::InstId lhs_id,
  598. SemIR::InstId rhs_id)
  599. -> SemIR::ConstantId {
  600. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  601. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  602. const auto& lhs_val = context.ints().Get(lhs.int_id);
  603. const auto& rhs_val = context.ints().Get(rhs.int_id);
  604. // Check for division by zero.
  605. switch (builtin_kind) {
  606. case SemIR::BuiltinFunctionKind::IntSDiv:
  607. case SemIR::BuiltinFunctionKind::IntSMod:
  608. case SemIR::BuiltinFunctionKind::IntUDiv:
  609. case SemIR::BuiltinFunctionKind::IntUMod:
  610. if (rhs_val.isZero()) {
  611. DiagnoseDivisionByZero(context, loc);
  612. return SemIR::ConstantId::Error;
  613. }
  614. break;
  615. default:
  616. break;
  617. }
  618. bool overflow = false;
  619. llvm::APInt result_val;
  620. Lex::TokenKind op_token = Lex::TokenKind::Not;
  621. switch (builtin_kind) {
  622. // Arithmetic.
  623. case SemIR::BuiltinFunctionKind::IntSAdd:
  624. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  625. op_token = Lex::TokenKind::Plus;
  626. break;
  627. case SemIR::BuiltinFunctionKind::IntSSub:
  628. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  629. op_token = Lex::TokenKind::Minus;
  630. break;
  631. case SemIR::BuiltinFunctionKind::IntSMul:
  632. result_val = lhs_val.smul_ov(rhs_val, overflow);
  633. op_token = Lex::TokenKind::Star;
  634. break;
  635. case SemIR::BuiltinFunctionKind::IntSDiv:
  636. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  637. op_token = Lex::TokenKind::Slash;
  638. break;
  639. case SemIR::BuiltinFunctionKind::IntSMod:
  640. result_val = lhs_val.srem(rhs_val);
  641. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  642. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  643. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  644. op_token = Lex::TokenKind::Percent;
  645. break;
  646. case SemIR::BuiltinFunctionKind::IntUAdd:
  647. result_val = lhs_val + rhs_val;
  648. op_token = Lex::TokenKind::Plus;
  649. break;
  650. case SemIR::BuiltinFunctionKind::IntUSub:
  651. result_val = lhs_val - rhs_val;
  652. op_token = Lex::TokenKind::Minus;
  653. break;
  654. case SemIR::BuiltinFunctionKind::IntUMul:
  655. result_val = lhs_val * rhs_val;
  656. op_token = Lex::TokenKind::Star;
  657. break;
  658. case SemIR::BuiltinFunctionKind::IntUDiv:
  659. result_val = lhs_val.udiv(rhs_val);
  660. op_token = Lex::TokenKind::Slash;
  661. break;
  662. case SemIR::BuiltinFunctionKind::IntUMod:
  663. result_val = lhs_val.urem(rhs_val);
  664. op_token = Lex::TokenKind::Percent;
  665. break;
  666. // Bitwise.
  667. case SemIR::BuiltinFunctionKind::IntAnd:
  668. result_val = lhs_val & rhs_val;
  669. op_token = Lex::TokenKind::And;
  670. break;
  671. case SemIR::BuiltinFunctionKind::IntOr:
  672. result_val = lhs_val | rhs_val;
  673. op_token = Lex::TokenKind::Pipe;
  674. break;
  675. case SemIR::BuiltinFunctionKind::IntXor:
  676. result_val = lhs_val ^ rhs_val;
  677. op_token = Lex::TokenKind::Caret;
  678. break;
  679. // Bit shift.
  680. case SemIR::BuiltinFunctionKind::IntLeftShift:
  681. case SemIR::BuiltinFunctionKind::IntRightShift:
  682. if (rhs_val.uge(lhs_val.getBitWidth()) ||
  683. (rhs_val.isNegative() && context.types().IsSignedInt(rhs.type_id))) {
  684. CARBON_DIAGNOSTIC(
  685. CompileTimeShiftOutOfRange, Error,
  686. "shift distance not in range [0, {0}) in {1} {2:<<|>>} {3}",
  687. unsigned, TypedInt, BoolAsSelect, TypedInt);
  688. context.emitter().Emit(
  689. loc, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  690. {.type = lhs.type_id, .value = lhs_val},
  691. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  692. {.type = rhs.type_id, .value = rhs_val});
  693. // TODO: Is it useful to recover by returning 0 or -1?
  694. return SemIR::ConstantId::Error;
  695. }
  696. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  697. result_val = lhs_val.shl(rhs_val);
  698. } else if (context.types().IsSignedInt(lhs.type_id)) {
  699. result_val = lhs_val.ashr(rhs_val);
  700. } else {
  701. result_val = lhs_val.lshr(rhs_val);
  702. }
  703. break;
  704. default:
  705. CARBON_FATAL("Unexpected operation kind.");
  706. }
  707. if (overflow) {
  708. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  709. "integer overflow in calculation {0} {1} {2}", TypedInt,
  710. Lex::TokenKind, TypedInt);
  711. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  712. {.type = lhs.type_id, .value = lhs_val}, op_token,
  713. {.type = rhs.type_id, .value = rhs_val});
  714. }
  715. return MakeIntResult(context, lhs.type_id, std::move(result_val));
  716. }
  717. // Performs a builtin integer comparison.
  718. static auto PerformBuiltinIntComparison(Context& context,
  719. SemIR::BuiltinFunctionKind builtin_kind,
  720. SemIR::InstId lhs_id,
  721. SemIR::InstId rhs_id,
  722. SemIR::TypeId bool_type_id)
  723. -> SemIR::ConstantId {
  724. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  725. const auto& lhs_val = context.ints().Get(lhs.int_id);
  726. const auto& rhs_val =
  727. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(rhs_id).int_id);
  728. bool is_signed = context.types().IsSignedInt(lhs.type_id);
  729. bool result;
  730. switch (builtin_kind) {
  731. case SemIR::BuiltinFunctionKind::IntEq:
  732. result = (lhs_val == rhs_val);
  733. break;
  734. case SemIR::BuiltinFunctionKind::IntNeq:
  735. result = (lhs_val != rhs_val);
  736. break;
  737. case SemIR::BuiltinFunctionKind::IntLess:
  738. result = is_signed ? lhs_val.slt(rhs_val) : lhs_val.ult(rhs_val);
  739. break;
  740. case SemIR::BuiltinFunctionKind::IntLessEq:
  741. result = is_signed ? lhs_val.sle(rhs_val) : lhs_val.ule(rhs_val);
  742. break;
  743. case SemIR::BuiltinFunctionKind::IntGreater:
  744. result = is_signed ? lhs_val.sgt(rhs_val) : lhs_val.sgt(rhs_val);
  745. break;
  746. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  747. result = is_signed ? lhs_val.sge(rhs_val) : lhs_val.sge(rhs_val);
  748. break;
  749. default:
  750. CARBON_FATAL("Unexpected operation kind.");
  751. }
  752. return MakeBoolResult(context, bool_type_id, result);
  753. }
  754. // Performs a builtin unary float -> float operation.
  755. static auto PerformBuiltinUnaryFloatOp(Context& context,
  756. SemIR::BuiltinFunctionKind builtin_kind,
  757. SemIR::InstId arg_id)
  758. -> SemIR::ConstantId {
  759. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  760. auto op_val = context.floats().Get(op.float_id);
  761. switch (builtin_kind) {
  762. case SemIR::BuiltinFunctionKind::FloatNegate:
  763. op_val.changeSign();
  764. break;
  765. default:
  766. CARBON_FATAL("Unexpected builtin kind");
  767. }
  768. return MakeFloatResult(context, op.type_id, std::move(op_val));
  769. }
  770. // Performs a builtin binary float -> float operation.
  771. static auto PerformBuiltinBinaryFloatOp(Context& context,
  772. SemIR::BuiltinFunctionKind builtin_kind,
  773. SemIR::InstId lhs_id,
  774. SemIR::InstId rhs_id)
  775. -> SemIR::ConstantId {
  776. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  777. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  778. auto lhs_val = context.floats().Get(lhs.float_id);
  779. auto rhs_val = context.floats().Get(rhs.float_id);
  780. llvm::APFloat result_val(lhs_val.getSemantics());
  781. switch (builtin_kind) {
  782. case SemIR::BuiltinFunctionKind::FloatAdd:
  783. result_val = lhs_val + rhs_val;
  784. break;
  785. case SemIR::BuiltinFunctionKind::FloatSub:
  786. result_val = lhs_val - rhs_val;
  787. break;
  788. case SemIR::BuiltinFunctionKind::FloatMul:
  789. result_val = lhs_val * rhs_val;
  790. break;
  791. case SemIR::BuiltinFunctionKind::FloatDiv:
  792. result_val = lhs_val / rhs_val;
  793. break;
  794. default:
  795. CARBON_FATAL("Unexpected operation kind.");
  796. }
  797. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  798. }
  799. // Performs a builtin float comparison.
  800. static auto PerformBuiltinFloatComparison(
  801. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  802. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  803. -> SemIR::ConstantId {
  804. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  805. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  806. const auto& lhs_val = context.floats().Get(lhs.float_id);
  807. const auto& rhs_val = context.floats().Get(rhs.float_id);
  808. bool result;
  809. switch (builtin_kind) {
  810. case SemIR::BuiltinFunctionKind::FloatEq:
  811. result = (lhs_val == rhs_val);
  812. break;
  813. case SemIR::BuiltinFunctionKind::FloatNeq:
  814. result = (lhs_val != rhs_val);
  815. break;
  816. case SemIR::BuiltinFunctionKind::FloatLess:
  817. result = lhs_val < rhs_val;
  818. break;
  819. case SemIR::BuiltinFunctionKind::FloatLessEq:
  820. result = lhs_val <= rhs_val;
  821. break;
  822. case SemIR::BuiltinFunctionKind::FloatGreater:
  823. result = lhs_val > rhs_val;
  824. break;
  825. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  826. result = lhs_val >= rhs_val;
  827. break;
  828. default:
  829. CARBON_FATAL("Unexpected operation kind.");
  830. }
  831. return MakeBoolResult(context, bool_type_id, result);
  832. }
  833. // Returns a constant for a call to a builtin function.
  834. static auto MakeConstantForBuiltinCall(Context& context, SemIRLoc loc,
  835. SemIR::Call call,
  836. SemIR::BuiltinFunctionKind builtin_kind,
  837. llvm::ArrayRef<SemIR::InstId> arg_ids,
  838. Phase phase) -> SemIR::ConstantId {
  839. switch (builtin_kind) {
  840. case SemIR::BuiltinFunctionKind::None:
  841. CARBON_FATAL("Not a builtin function.");
  842. case SemIR::BuiltinFunctionKind::PrintInt: {
  843. // Providing a constant result would allow eliding the function call.
  844. return SemIR::ConstantId::NotConstant;
  845. }
  846. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  847. return context.constant_values().Get(
  848. SemIR::InstId::BuiltinIntLiteralType);
  849. }
  850. case SemIR::BuiltinFunctionKind::IntMakeType32: {
  851. return context.constant_values().Get(SemIR::InstId::BuiltinIntType);
  852. }
  853. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  854. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  855. phase);
  856. }
  857. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  858. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  859. arg_ids[0], phase);
  860. }
  861. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  862. // TODO: Support a symbolic constant width.
  863. if (phase != Phase::Template) {
  864. break;
  865. }
  866. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  867. return SemIR::ConstantId::Error;
  868. }
  869. return context.constant_values().Get(SemIR::InstId::BuiltinFloatType);
  870. }
  871. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  872. return context.constant_values().Get(SemIR::InstId::BuiltinBoolType);
  873. }
  874. // Unary integer -> integer operations.
  875. case SemIR::BuiltinFunctionKind::IntSNegate:
  876. case SemIR::BuiltinFunctionKind::IntUNegate:
  877. case SemIR::BuiltinFunctionKind::IntComplement: {
  878. if (phase != Phase::Template) {
  879. break;
  880. }
  881. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  882. }
  883. // Binary integer -> integer operations.
  884. case SemIR::BuiltinFunctionKind::IntSAdd:
  885. case SemIR::BuiltinFunctionKind::IntSSub:
  886. case SemIR::BuiltinFunctionKind::IntSMul:
  887. case SemIR::BuiltinFunctionKind::IntSDiv:
  888. case SemIR::BuiltinFunctionKind::IntSMod:
  889. case SemIR::BuiltinFunctionKind::IntUAdd:
  890. case SemIR::BuiltinFunctionKind::IntUSub:
  891. case SemIR::BuiltinFunctionKind::IntUMul:
  892. case SemIR::BuiltinFunctionKind::IntUDiv:
  893. case SemIR::BuiltinFunctionKind::IntUMod:
  894. case SemIR::BuiltinFunctionKind::IntAnd:
  895. case SemIR::BuiltinFunctionKind::IntOr:
  896. case SemIR::BuiltinFunctionKind::IntXor:
  897. case SemIR::BuiltinFunctionKind::IntLeftShift:
  898. case SemIR::BuiltinFunctionKind::IntRightShift: {
  899. if (phase != Phase::Template) {
  900. break;
  901. }
  902. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  903. arg_ids[1]);
  904. }
  905. // Integer comparisons.
  906. case SemIR::BuiltinFunctionKind::IntEq:
  907. case SemIR::BuiltinFunctionKind::IntNeq:
  908. case SemIR::BuiltinFunctionKind::IntLess:
  909. case SemIR::BuiltinFunctionKind::IntLessEq:
  910. case SemIR::BuiltinFunctionKind::IntGreater:
  911. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  912. if (phase != Phase::Template) {
  913. break;
  914. }
  915. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  916. arg_ids[1], call.type_id);
  917. }
  918. // Unary float -> float operations.
  919. case SemIR::BuiltinFunctionKind::FloatNegate: {
  920. if (phase != Phase::Template) {
  921. break;
  922. }
  923. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  924. }
  925. // Binary float -> float operations.
  926. case SemIR::BuiltinFunctionKind::FloatAdd:
  927. case SemIR::BuiltinFunctionKind::FloatSub:
  928. case SemIR::BuiltinFunctionKind::FloatMul:
  929. case SemIR::BuiltinFunctionKind::FloatDiv: {
  930. if (phase != Phase::Template) {
  931. break;
  932. }
  933. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  934. arg_ids[1]);
  935. }
  936. // Float comparisons.
  937. case SemIR::BuiltinFunctionKind::FloatEq:
  938. case SemIR::BuiltinFunctionKind::FloatNeq:
  939. case SemIR::BuiltinFunctionKind::FloatLess:
  940. case SemIR::BuiltinFunctionKind::FloatLessEq:
  941. case SemIR::BuiltinFunctionKind::FloatGreater:
  942. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  943. if (phase != Phase::Template) {
  944. break;
  945. }
  946. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  947. arg_ids[1], call.type_id);
  948. }
  949. }
  950. return SemIR::ConstantId::NotConstant;
  951. }
  952. // Makes a constant for a call instruction.
  953. static auto MakeConstantForCall(EvalContext& eval_context, SemIRLoc loc,
  954. SemIR::Call call) -> SemIR::ConstantId {
  955. Phase phase = Phase::Template;
  956. // A call with an invalid argument list is used to represent an erroneous
  957. // call.
  958. //
  959. // TODO: Use a better representation for this.
  960. if (call.args_id == SemIR::InstBlockId::Invalid) {
  961. return SemIR::ConstantId::Error;
  962. }
  963. // If the callee or return type isn't constant, this is not a constant call.
  964. if (!ReplaceFieldWithConstantValue(eval_context, &call,
  965. &SemIR::Call::callee_id, &phase) ||
  966. !ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  967. &phase)) {
  968. return SemIR::ConstantId::NotConstant;
  969. }
  970. auto callee_function =
  971. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  972. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  973. if (callee_function.function_id.is_valid()) {
  974. // Calls to builtins might be constant.
  975. builtin_kind = eval_context.functions()
  976. .Get(callee_function.function_id)
  977. .builtin_function_kind;
  978. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  979. // TODO: Eventually we'll want to treat some kinds of non-builtin
  980. // functions as producing constants.
  981. return SemIR::ConstantId::NotConstant;
  982. }
  983. } else {
  984. // Calls to non-functions, such as calls to generic entity names, might be
  985. // constant.
  986. }
  987. // If the arguments aren't constant, this is not a constant call.
  988. if (!ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  989. &phase)) {
  990. return SemIR::ConstantId::NotConstant;
  991. }
  992. if (phase == Phase::UnknownDueToError) {
  993. return SemIR::ConstantId::Error;
  994. }
  995. // Handle calls to builtins.
  996. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  997. return MakeConstantForBuiltinCall(
  998. eval_context.context(), loc, call, builtin_kind,
  999. eval_context.inst_blocks().Get(call.args_id), phase);
  1000. }
  1001. return SemIR::ConstantId::NotConstant;
  1002. }
  1003. // Creates a FacetType constant.
  1004. static auto MakeFacetTypeResult(Context& context,
  1005. SemIR::TypeId base_facet_type_id,
  1006. SemIR::InstBlockId requirement_block_id,
  1007. Phase phase) -> SemIR::ConstantId {
  1008. SemIR::FacetTypeId facet_type_id = context.sem_ir().facet_types().Add(
  1009. SemIR::FacetTypeInfo{.base_facet_type_id = base_facet_type_id,
  1010. .requirement_block_id = requirement_block_id});
  1011. return MakeConstantResult(context,
  1012. SemIR::FacetType{.type_id = SemIR::TypeId::TypeType,
  1013. .facet_type_id = facet_type_id},
  1014. phase);
  1015. }
  1016. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1017. static auto TryEvalInstInContext(EvalContext& eval_context,
  1018. SemIR::InstId inst_id, SemIR::Inst inst)
  1019. -> SemIR::ConstantId {
  1020. // TODO: Ensure we have test coverage for each of these cases that can result
  1021. // in a constant, once those situations are all reachable.
  1022. CARBON_KIND_SWITCH(inst) {
  1023. // These cases are constants if their operands are.
  1024. case SemIR::AddrOf::Kind:
  1025. return RebuildIfFieldsAreConstant(eval_context, inst,
  1026. &SemIR::AddrOf::type_id,
  1027. &SemIR::AddrOf::lvalue_id);
  1028. case CARBON_KIND(SemIR::ArrayType array_type): {
  1029. return RebuildAndValidateIfFieldsAreConstant(
  1030. eval_context, inst,
  1031. [&](SemIR::ArrayType result) {
  1032. auto bound_id = array_type.bound_id;
  1033. auto int_bound =
  1034. eval_context.insts().TryGetAs<SemIR::IntValue>(result.bound_id);
  1035. if (!int_bound) {
  1036. // TODO: Permit symbolic array bounds. This will require fixing
  1037. // callers of `GetArrayBoundValue`.
  1038. eval_context.context().TODO(bound_id, "symbolic array bound");
  1039. return false;
  1040. }
  1041. // TODO: We should check that the size of the resulting array type
  1042. // fits in 64 bits, not just that the bound does. Should we use a
  1043. // 32-bit limit for 32-bit targets?
  1044. const auto& bound_val = eval_context.ints().Get(int_bound->int_id);
  1045. if (eval_context.types().IsSignedInt(int_bound->type_id) &&
  1046. bound_val.isNegative()) {
  1047. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  1048. "array bound of {0} is negative", TypedInt);
  1049. eval_context.emitter().Emit(
  1050. bound_id, ArrayBoundNegative,
  1051. {.type = int_bound->type_id, .value = bound_val});
  1052. return false;
  1053. }
  1054. if (bound_val.getActiveBits() > 64) {
  1055. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  1056. "array bound of {0} is too large", TypedInt);
  1057. eval_context.emitter().Emit(
  1058. bound_id, ArrayBoundTooLarge,
  1059. {.type = int_bound->type_id, .value = bound_val});
  1060. return false;
  1061. }
  1062. return true;
  1063. },
  1064. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  1065. }
  1066. case SemIR::AssociatedEntity::Kind:
  1067. return RebuildIfFieldsAreConstant(eval_context, inst,
  1068. &SemIR::AssociatedEntity::type_id);
  1069. case SemIR::AssociatedEntityType::Kind:
  1070. return RebuildIfFieldsAreConstant(
  1071. eval_context, inst, &SemIR::AssociatedEntityType::interface_type_id,
  1072. &SemIR::AssociatedEntityType::entity_type_id);
  1073. case SemIR::BoundMethod::Kind:
  1074. return RebuildIfFieldsAreConstant(
  1075. eval_context, inst, &SemIR::BoundMethod::type_id,
  1076. &SemIR::BoundMethod::object_id, &SemIR::BoundMethod::function_id);
  1077. case SemIR::ClassType::Kind:
  1078. return RebuildIfFieldsAreConstant(eval_context, inst,
  1079. &SemIR::ClassType::specific_id);
  1080. case SemIR::CompleteTypeWitness::Kind:
  1081. return RebuildIfFieldsAreConstant(
  1082. eval_context, inst, &SemIR::CompleteTypeWitness::object_repr_id);
  1083. case SemIR::FunctionType::Kind:
  1084. return RebuildIfFieldsAreConstant(eval_context, inst,
  1085. &SemIR::FunctionType::specific_id);
  1086. case SemIR::GenericClassType::Kind:
  1087. return RebuildIfFieldsAreConstant(
  1088. eval_context, inst, &SemIR::GenericClassType::enclosing_specific_id);
  1089. case SemIR::GenericInterfaceType::Kind:
  1090. return RebuildIfFieldsAreConstant(
  1091. eval_context, inst,
  1092. &SemIR::GenericInterfaceType::enclosing_specific_id);
  1093. case SemIR::InterfaceType::Kind:
  1094. return RebuildIfFieldsAreConstant(eval_context, inst,
  1095. &SemIR::InterfaceType::specific_id);
  1096. case SemIR::InterfaceWitness::Kind:
  1097. return RebuildIfFieldsAreConstant(eval_context, inst,
  1098. &SemIR::InterfaceWitness::elements_id);
  1099. case CARBON_KIND(SemIR::IntType int_type): {
  1100. return RebuildAndValidateIfFieldsAreConstant(
  1101. eval_context, inst,
  1102. [&](SemIR::IntType result) {
  1103. return ValidateIntType(
  1104. eval_context.context(),
  1105. inst_id.is_valid() ? inst_id : int_type.bit_width_id, result);
  1106. },
  1107. &SemIR::IntType::bit_width_id);
  1108. }
  1109. case SemIR::PointerType::Kind:
  1110. return RebuildIfFieldsAreConstant(eval_context, inst,
  1111. &SemIR::PointerType::pointee_id);
  1112. case CARBON_KIND(SemIR::FloatType float_type): {
  1113. return RebuildAndValidateIfFieldsAreConstant(
  1114. eval_context, inst,
  1115. [&](SemIR::FloatType result) {
  1116. return ValidateFloatType(eval_context.context(),
  1117. float_type.bit_width_id, result);
  1118. },
  1119. &SemIR::FloatType::bit_width_id);
  1120. }
  1121. case SemIR::SpecificFunction::Kind:
  1122. return RebuildIfFieldsAreConstant(eval_context, inst,
  1123. &SemIR::SpecificFunction::callee_id,
  1124. &SemIR::SpecificFunction::specific_id);
  1125. case SemIR::StructType::Kind:
  1126. return RebuildIfFieldsAreConstant(eval_context, inst,
  1127. &SemIR::StructType::fields_id);
  1128. case SemIR::StructTypeField::Kind:
  1129. return RebuildIfFieldsAreConstant(eval_context, inst,
  1130. &SemIR::StructTypeField::field_type_id);
  1131. case SemIR::StructValue::Kind:
  1132. return RebuildIfFieldsAreConstant(eval_context, inst,
  1133. &SemIR::StructValue::type_id,
  1134. &SemIR::StructValue::elements_id);
  1135. case SemIR::TupleType::Kind:
  1136. return RebuildIfFieldsAreConstant(eval_context, inst,
  1137. &SemIR::TupleType::elements_id);
  1138. case SemIR::TupleValue::Kind:
  1139. return RebuildIfFieldsAreConstant(eval_context, inst,
  1140. &SemIR::TupleValue::type_id,
  1141. &SemIR::TupleValue::elements_id);
  1142. case SemIR::UnboundElementType::Kind:
  1143. return RebuildIfFieldsAreConstant(
  1144. eval_context, inst, &SemIR::UnboundElementType::class_type_id,
  1145. &SemIR::UnboundElementType::element_type_id);
  1146. // Initializers evaluate to a value of the object representation.
  1147. case SemIR::ArrayInit::Kind:
  1148. // TODO: Add an `ArrayValue` to represent a constant array object
  1149. // representation instead of using a `TupleValue`.
  1150. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1151. case SemIR::ClassInit::Kind:
  1152. // TODO: Add a `ClassValue` to represent a constant class object
  1153. // representation instead of using a `StructValue`.
  1154. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1155. case SemIR::StructInit::Kind:
  1156. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1157. case SemIR::TupleInit::Kind:
  1158. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1159. case SemIR::BuiltinInst::Kind:
  1160. // Builtins are always template constants.
  1161. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1162. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  1163. return TransformIfFieldsAreConstant(
  1164. eval_context, fn_decl,
  1165. [&](SemIR::FunctionDecl result) {
  1166. return SemIR::StructValue{.type_id = result.type_id,
  1167. .elements_id = SemIR::InstBlockId::Empty};
  1168. },
  1169. &SemIR::FunctionDecl::type_id);
  1170. }
  1171. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  1172. // If the class has generic parameters, we don't produce a class type, but
  1173. // a callable whose return value is a class type.
  1174. if (eval_context.classes().Get(class_decl.class_id).has_parameters()) {
  1175. return TransformIfFieldsAreConstant(
  1176. eval_context, class_decl,
  1177. [&](SemIR::ClassDecl result) {
  1178. return SemIR::StructValue{
  1179. .type_id = result.type_id,
  1180. .elements_id = SemIR::InstBlockId::Empty};
  1181. },
  1182. &SemIR::ClassDecl::type_id);
  1183. }
  1184. // A non-generic class declaration evaluates to the class type.
  1185. return MakeConstantResult(
  1186. eval_context.context(),
  1187. SemIR::ClassType{.type_id = SemIR::TypeId::TypeType,
  1188. .class_id = class_decl.class_id,
  1189. .specific_id = SemIR::SpecificId::Invalid},
  1190. Phase::Template);
  1191. }
  1192. case CARBON_KIND(SemIR::FacetType facet_type): {
  1193. SemIR::FacetTypeInfo info =
  1194. eval_context.facet_types().Get(facet_type.facet_type_id);
  1195. Phase phase = Phase::Template;
  1196. SemIR::TypeId base_facet_type_id =
  1197. GetConstantValue(eval_context, info.base_facet_type_id, &phase);
  1198. // TODO: process & canonicalize requirements
  1199. SemIR::InstBlockId requirement_block_id = info.requirement_block_id;
  1200. // If nothing changed, can reuse this instruction.
  1201. if (base_facet_type_id == info.base_facet_type_id &&
  1202. requirement_block_id == info.requirement_block_id) {
  1203. return MakeConstantResult(eval_context.context(), inst, phase);
  1204. }
  1205. return MakeFacetTypeResult(eval_context.context(), base_facet_type_id,
  1206. requirement_block_id, phase);
  1207. }
  1208. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  1209. // If the interface has generic parameters, we don't produce an interface
  1210. // type, but a callable whose return value is an interface type.
  1211. if (eval_context.interfaces()
  1212. .Get(interface_decl.interface_id)
  1213. .has_parameters()) {
  1214. return TransformIfFieldsAreConstant(
  1215. eval_context, interface_decl,
  1216. [&](SemIR::InterfaceDecl result) {
  1217. return SemIR::StructValue{
  1218. .type_id = result.type_id,
  1219. .elements_id = SemIR::InstBlockId::Empty};
  1220. },
  1221. &SemIR::InterfaceDecl::type_id);
  1222. }
  1223. // A non-generic interface declaration evaluates to the interface type.
  1224. return MakeConstantResult(
  1225. eval_context.context(),
  1226. SemIR::InterfaceType{.type_id = SemIR::TypeId::TypeType,
  1227. .interface_id = interface_decl.interface_id,
  1228. .specific_id = SemIR::SpecificId::Invalid},
  1229. Phase::Template);
  1230. }
  1231. case CARBON_KIND(SemIR::SpecificConstant specific): {
  1232. // Pull the constant value out of the specific.
  1233. return SemIR::GetConstantValueInSpecific(
  1234. eval_context.sem_ir(), specific.specific_id, specific.inst_id);
  1235. }
  1236. // These cases are treated as being the unique canonical definition of the
  1237. // corresponding constant value.
  1238. // TODO: This doesn't properly handle redeclarations. Consider adding a
  1239. // corresponding `Value` inst for each of these cases, or returning the
  1240. // first declaration.
  1241. case SemIR::AssociatedConstantDecl::Kind:
  1242. case SemIR::BaseDecl::Kind:
  1243. case SemIR::FieldDecl::Kind:
  1244. case SemIR::ImplDecl::Kind:
  1245. case SemIR::Namespace::Kind:
  1246. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  1247. case SemIR::BoolLiteral::Kind:
  1248. case SemIR::FloatLiteral::Kind:
  1249. case SemIR::IntValue::Kind:
  1250. case SemIR::StringLiteral::Kind:
  1251. // Promote literals to the constant block.
  1252. // TODO: Convert literals into a canonical form. Currently we can form two
  1253. // different `i32` constants with the same value if they are represented
  1254. // by `APInt`s with different bit widths.
  1255. // TODO: Can the type of an IntValue or FloatLiteral be symbolic? If so,
  1256. // we may need to rebuild.
  1257. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1258. // The elements of a constant aggregate can be accessed.
  1259. case SemIR::ClassElementAccess::Kind:
  1260. case SemIR::InterfaceWitnessAccess::Kind:
  1261. case SemIR::StructAccess::Kind:
  1262. case SemIR::TupleAccess::Kind:
  1263. return PerformAggregateAccess(eval_context, inst);
  1264. case CARBON_KIND(SemIR::ArrayIndex index): {
  1265. return PerformArrayIndex(eval_context, index);
  1266. }
  1267. case CARBON_KIND(SemIR::Call call): {
  1268. return MakeConstantForCall(eval_context, inst_id, call);
  1269. }
  1270. // TODO: These need special handling.
  1271. case SemIR::BindValue::Kind:
  1272. case SemIR::Deref::Kind:
  1273. case SemIR::ImportRefLoaded::Kind:
  1274. case SemIR::ReturnSlot::Kind:
  1275. case SemIR::Temporary::Kind:
  1276. case SemIR::TemporaryStorage::Kind:
  1277. case SemIR::ValueAsRef::Kind:
  1278. break;
  1279. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  1280. // TODO: disable constant evaluation of SymbolicBindingPattern once
  1281. // DeduceGenericCallArguments no longer needs implicit params to have
  1282. // constant values.
  1283. const auto& bind_name =
  1284. eval_context.entity_names().Get(bind.entity_name_id);
  1285. // If we know which specific we're evaluating within and this is an
  1286. // argument of that specific, its constant value is the corresponding
  1287. // argument value.
  1288. if (auto value =
  1289. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1290. value.is_valid()) {
  1291. return value;
  1292. }
  1293. // The constant form of a symbolic binding is an idealized form of the
  1294. // original, with no equivalent value.
  1295. bind.entity_name_id =
  1296. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1297. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1298. }
  1299. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  1300. const auto& bind_name =
  1301. eval_context.entity_names().Get(bind.entity_name_id);
  1302. // If we know which specific we're evaluating within and this is an
  1303. // argument of that specific, its constant value is the corresponding
  1304. // argument value.
  1305. if (auto value =
  1306. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1307. value.is_valid()) {
  1308. return value;
  1309. }
  1310. // The constant form of a symbolic binding is an idealized form of the
  1311. // original, with no equivalent value.
  1312. bind.entity_name_id =
  1313. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1314. bind.value_id = SemIR::InstId::Invalid;
  1315. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1316. }
  1317. // These semantic wrappers don't change the constant value.
  1318. case CARBON_KIND(SemIR::AsCompatible inst): {
  1319. return eval_context.GetConstantValue(inst.source_id);
  1320. }
  1321. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  1322. return eval_context.GetConstantValue(typed_inst.value_id);
  1323. }
  1324. case CARBON_KIND(SemIR::ExportDecl typed_inst): {
  1325. return eval_context.GetConstantValue(typed_inst.value_id);
  1326. }
  1327. case CARBON_KIND(SemIR::NameRef typed_inst): {
  1328. return eval_context.GetConstantValue(typed_inst.value_id);
  1329. }
  1330. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  1331. // TODO: treat this as a non-expression (here and in GetExprCategory)
  1332. // once generic deduction doesn't need patterns to have constant values.
  1333. return eval_context.GetConstantValue(param_pattern.subpattern_id);
  1334. }
  1335. case CARBON_KIND(SemIR::Converted typed_inst): {
  1336. return eval_context.GetConstantValue(typed_inst.result_id);
  1337. }
  1338. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  1339. return eval_context.GetConstantValue(typed_inst.src_id);
  1340. }
  1341. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  1342. return eval_context.GetConstantValue(typed_inst.result_id);
  1343. }
  1344. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  1345. return eval_context.GetConstantValue(typed_inst.init_id);
  1346. }
  1347. case CARBON_KIND(SemIR::FacetTypeAccess typed_inst): {
  1348. // TODO: Once we start tracking the witness in the facet value, remove it
  1349. // here. For now, we model a facet value as just a type.
  1350. return eval_context.GetConstantValue(typed_inst.facet_id);
  1351. }
  1352. case CARBON_KIND(SemIR::WhereExpr typed_inst): {
  1353. SemIR::TypeId base_facet_type_id =
  1354. eval_context.insts().Get(typed_inst.period_self_id).type_id();
  1355. Phase phase = Phase::Template;
  1356. base_facet_type_id =
  1357. GetConstantValue(eval_context, base_facet_type_id, &phase);
  1358. SemIR::InstBlockId requirement_block_id = typed_inst.requirements_id;
  1359. // TODO: process & canonicalize requirements
  1360. return MakeFacetTypeResult(eval_context.context(), base_facet_type_id,
  1361. requirement_block_id, phase);
  1362. }
  1363. // `not true` -> `false`, `not false` -> `true`.
  1364. // All other uses of unary `not` are non-constant.
  1365. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  1366. auto const_id = eval_context.GetConstantValue(typed_inst.operand_id);
  1367. auto phase = GetPhase(const_id);
  1368. if (phase == Phase::Template) {
  1369. auto value = eval_context.insts().GetAs<SemIR::BoolLiteral>(
  1370. eval_context.constant_values().GetInstId(const_id));
  1371. return MakeBoolResult(eval_context.context(), value.type_id,
  1372. !value.value.ToBool());
  1373. }
  1374. if (phase == Phase::UnknownDueToError) {
  1375. return SemIR::ConstantId::Error;
  1376. }
  1377. break;
  1378. }
  1379. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1380. // to itself.
  1381. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1382. auto phase = Phase::Template;
  1383. auto inner_id =
  1384. GetConstantValue(eval_context, typed_inst.inner_id, &phase);
  1385. if (eval_context.context().types().Is<SemIR::ConstType>(inner_id)) {
  1386. return eval_context.context().types().GetConstantId(inner_id);
  1387. }
  1388. typed_inst.inner_id = inner_id;
  1389. return MakeConstantResult(eval_context.context(), typed_inst, phase);
  1390. }
  1391. // These cases are either not expressions or not constant.
  1392. case SemIR::AdaptDecl::Kind:
  1393. case SemIR::AddrPattern::Kind:
  1394. case SemIR::Assign::Kind:
  1395. case SemIR::BindName::Kind:
  1396. case SemIR::BindingPattern::Kind:
  1397. case SemIR::BlockArg::Kind:
  1398. case SemIR::Branch::Kind:
  1399. case SemIR::BranchIf::Kind:
  1400. case SemIR::BranchWithArg::Kind:
  1401. case SemIR::ImportDecl::Kind:
  1402. case SemIR::OutParam::Kind:
  1403. case SemIR::OutParamPattern::Kind:
  1404. case SemIR::RequirementEquivalent::Kind:
  1405. case SemIR::RequirementImpls::Kind:
  1406. case SemIR::RequirementRewrite::Kind:
  1407. case SemIR::Return::Kind:
  1408. case SemIR::ReturnExpr::Kind:
  1409. case SemIR::ReturnSlotPattern::Kind:
  1410. case SemIR::StructLiteral::Kind:
  1411. case SemIR::TupleLiteral::Kind:
  1412. case SemIR::ValueParam::Kind:
  1413. case SemIR::VarStorage::Kind:
  1414. break;
  1415. case SemIR::ImportRefUnloaded::Kind:
  1416. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  1417. inst);
  1418. }
  1419. return SemIR::ConstantId::NotConstant;
  1420. }
  1421. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  1422. -> SemIR::ConstantId {
  1423. EvalContext eval_context(context);
  1424. return TryEvalInstInContext(eval_context, inst_id, inst);
  1425. }
  1426. auto TryEvalBlockForSpecific(Context& context, SemIR::SpecificId specific_id,
  1427. SemIR::GenericInstIndex::Region region)
  1428. -> SemIR::InstBlockId {
  1429. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1430. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1431. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1432. llvm::SmallVector<SemIR::InstId> result;
  1433. result.resize(eval_block.size(), SemIR::InstId::Invalid);
  1434. EvalContext eval_context(context, specific_id,
  1435. SpecificEvalInfo{
  1436. .region = region,
  1437. .values = result,
  1438. });
  1439. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1440. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1441. context.insts().Get(inst_id));
  1442. result[i] = context.constant_values().GetInstId(const_id);
  1443. // TODO: If this becomes possible through monomorphization failure, produce
  1444. // a diagnostic and put `SemIR::InstId::BuiltinError` in the table entry.
  1445. CARBON_CHECK(result[i].is_valid());
  1446. }
  1447. return context.inst_blocks().Add(result);
  1448. }
  1449. } // namespace Carbon::Check