eval.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728
  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. bool is_signed, llvm::APInt value)
  218. -> SemIR::ConstantId {
  219. CARBON_CHECK(is_signed == context.types().IsSignedInt(type_id));
  220. auto result = is_signed ? context.ints().AddSigned(std::move(value))
  221. : context.ints().AddUnsigned(std::move(value));
  222. return MakeConstantResult(
  223. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  224. Phase::Template);
  225. }
  226. // Converts an APFloat value into a ConstantId.
  227. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  228. llvm::APFloat value) -> SemIR::ConstantId {
  229. auto result = context.floats().Add(std::move(value));
  230. return MakeConstantResult(
  231. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  232. Phase::Template);
  233. }
  234. // `GetConstantValue` checks to see whether the provided ID describes a value
  235. // with constant phase, and if so, returns the corresponding constant value.
  236. // Overloads are provided for different kinds of ID.
  237. // If the given instruction is constant, returns its constant value.
  238. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  239. Phase* phase) -> SemIR::InstId {
  240. auto const_id = eval_context.GetConstantValue(inst_id);
  241. *phase = LatestPhase(*phase, GetPhase(const_id));
  242. return eval_context.constant_values().GetInstId(const_id);
  243. }
  244. // Given a type which may refer to a generic parameter, returns the
  245. // corresponding type in the evaluation context.
  246. static auto GetConstantValue(EvalContext& eval_context, SemIR::TypeId type_id,
  247. Phase* phase) -> SemIR::TypeId {
  248. auto const_id = eval_context.GetConstantValue(type_id);
  249. *phase = LatestPhase(*phase, GetPhase(const_id));
  250. return eval_context.context().GetTypeIdForTypeConstant(const_id);
  251. }
  252. // If the given instruction block contains only constants, returns a
  253. // corresponding block of those values.
  254. static auto GetConstantValue(EvalContext& eval_context,
  255. SemIR::InstBlockId inst_block_id, Phase* phase)
  256. -> SemIR::InstBlockId {
  257. if (!inst_block_id.is_valid()) {
  258. return SemIR::InstBlockId::Invalid;
  259. }
  260. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  261. llvm::SmallVector<SemIR::InstId> const_insts;
  262. for (auto inst_id : insts) {
  263. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  264. if (!const_inst_id.is_valid()) {
  265. return SemIR::InstBlockId::Invalid;
  266. }
  267. // Once we leave the small buffer, we know the first few elements are all
  268. // constant, so it's likely that the entire block is constant. Resize to the
  269. // target size given that we're going to allocate memory now anyway.
  270. if (const_insts.size() == const_insts.capacity()) {
  271. const_insts.reserve(insts.size());
  272. }
  273. const_insts.push_back(const_inst_id);
  274. }
  275. // TODO: If the new block is identical to the original block, and we know the
  276. // old ID was canonical, return the original ID.
  277. return eval_context.inst_blocks().AddCanonical(const_insts);
  278. }
  279. // Compute the constant value of a type block. This may be different from the
  280. // input type block if we have known generic arguments.
  281. static auto GetConstantValue(EvalContext& eval_context,
  282. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  283. -> SemIR::StructTypeFieldsId {
  284. if (!fields_id.is_valid()) {
  285. return SemIR::StructTypeFieldsId::Invalid;
  286. }
  287. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  288. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  289. for (auto field : fields) {
  290. auto new_type_id = GetConstantValue(eval_context, field.type_id, phase);
  291. if (!new_type_id.is_valid()) {
  292. return SemIR::StructTypeFieldsId::Invalid;
  293. }
  294. // Once we leave the small buffer, we know the first few elements are all
  295. // constant, so it's likely that the entire block is constant. Resize to the
  296. // target size given that we're going to allocate memory now anyway.
  297. if (new_fields.size() == new_fields.capacity()) {
  298. new_fields.reserve(fields.size());
  299. }
  300. new_fields.push_back({.name_id = field.name_id, .type_id = new_type_id});
  301. }
  302. // TODO: If the new block is identical to the original block, and we know the
  303. // old ID was canonical, return the original ID.
  304. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  305. }
  306. // Compute the constant value of a type block. This may be different from the
  307. // input type block if we have known generic arguments.
  308. static auto GetConstantValue(EvalContext& eval_context,
  309. SemIR::TypeBlockId type_block_id, Phase* phase)
  310. -> SemIR::TypeBlockId {
  311. if (!type_block_id.is_valid()) {
  312. return SemIR::TypeBlockId::Invalid;
  313. }
  314. auto types = eval_context.type_blocks().Get(type_block_id);
  315. llvm::SmallVector<SemIR::TypeId> new_types;
  316. for (auto type_id : types) {
  317. auto new_type_id = GetConstantValue(eval_context, type_id, phase);
  318. if (!new_type_id.is_valid()) {
  319. return SemIR::TypeBlockId::Invalid;
  320. }
  321. // Once we leave the small buffer, we know the first few elements are all
  322. // constant, so it's likely that the entire block is constant. Resize to the
  323. // target size given that we're going to allocate memory now anyway.
  324. if (new_types.size() == new_types.capacity()) {
  325. new_types.reserve(types.size());
  326. }
  327. new_types.push_back(new_type_id);
  328. }
  329. // TODO: If the new block is identical to the original block, and we know the
  330. // old ID was canonical, return the original ID.
  331. return eval_context.type_blocks().AddCanonical(new_types);
  332. }
  333. // The constant value of a specific is the specific with the corresponding
  334. // constant values for its arguments.
  335. static auto GetConstantValue(EvalContext& eval_context,
  336. SemIR::SpecificId specific_id, Phase* phase)
  337. -> SemIR::SpecificId {
  338. if (!specific_id.is_valid()) {
  339. return SemIR::SpecificId::Invalid;
  340. }
  341. const auto& specific = eval_context.specifics().Get(specific_id);
  342. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  343. if (!args_id.is_valid()) {
  344. return SemIR::SpecificId::Invalid;
  345. }
  346. if (args_id == specific.args_id) {
  347. return specific_id;
  348. }
  349. return MakeSpecific(eval_context.context(), specific.generic_id, args_id);
  350. }
  351. // Like `GetConstantValue` but does a `FacetTypeId` -> `FacetTypeInfo`
  352. // conversion.
  353. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  354. SemIR::FacetTypeId facet_type_id,
  355. Phase* phase) -> SemIR::FacetTypeInfo {
  356. SemIR::FacetTypeInfo info = eval_context.facet_types().Get(facet_type_id);
  357. for (auto& interface : info.impls_constraints) {
  358. interface.specific_id =
  359. GetConstantValue(eval_context, interface.specific_id, phase);
  360. }
  361. std::sort(info.impls_constraints.begin(), info.impls_constraints.end());
  362. // TODO: Process & canonicalize other requirements.
  363. return info;
  364. }
  365. // Replaces the specified field of the given typed instruction with its constant
  366. // value, if it has constant phase. Returns true on success, false if the value
  367. // has runtime phase.
  368. template <typename InstT, typename FieldIdT>
  369. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  370. InstT* inst, FieldIdT InstT::*field,
  371. Phase* phase) -> bool {
  372. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  373. if (!unwrapped.is_valid() && (inst->*field).is_valid()) {
  374. return false;
  375. }
  376. inst->*field = unwrapped;
  377. return true;
  378. }
  379. // If the specified fields of the given typed instruction have constant values,
  380. // replaces the fields with their constant values and builds a corresponding
  381. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  382. // `ConstantId::Error` if any subexpression is an error.
  383. //
  384. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  385. // which should return a `bool` indicating whether the new constant is valid. If
  386. // validation passes, `transform_fn(typed_inst)` is called to produce the final
  387. // constant instruction, and a corresponding ConstantId for the new constant is
  388. // returned. If validation fails, it should produce a suitable error message.
  389. // `ConstantId::Error` is returned.
  390. template <typename InstT, typename ValidateFn, typename TransformFn,
  391. typename... EachFieldIdT>
  392. static auto RebuildIfFieldsAreConstantImpl(
  393. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  394. TransformFn transform_fn, EachFieldIdT InstT::*... each_field_id)
  395. -> SemIR::ConstantId {
  396. // Build a constant instruction by replacing each non-constant operand with
  397. // its constant value.
  398. auto typed_inst = inst.As<InstT>();
  399. Phase phase = Phase::Template;
  400. if ((ReplaceFieldWithConstantValue(eval_context, &typed_inst, each_field_id,
  401. &phase) &&
  402. ...)) {
  403. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  404. return SemIR::ConstantId::Error;
  405. }
  406. return MakeConstantResult(eval_context.context(), transform_fn(typed_inst),
  407. phase);
  408. }
  409. return MakeNonConstantResult(phase);
  410. }
  411. // Same as above but with an identity transform function.
  412. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  413. static auto RebuildAndValidateIfFieldsAreConstant(
  414. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  415. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  416. return RebuildIfFieldsAreConstantImpl(eval_context, inst, validate_fn,
  417. std::identity{}, each_field_id...);
  418. }
  419. // Same as above but with no validation step.
  420. template <typename InstT, typename TransformFn, typename... EachFieldIdT>
  421. static auto TransformIfFieldsAreConstant(EvalContext& eval_context,
  422. SemIR::Inst inst,
  423. TransformFn transform_fn,
  424. EachFieldIdT InstT::*... each_field_id)
  425. -> SemIR::ConstantId {
  426. return RebuildIfFieldsAreConstantImpl(
  427. eval_context, inst, [](...) { return true; }, transform_fn,
  428. each_field_id...);
  429. }
  430. // Same as above but with no validation or transform step.
  431. template <typename InstT, typename... EachFieldIdT>
  432. static auto RebuildIfFieldsAreConstant(EvalContext& eval_context,
  433. SemIR::Inst inst,
  434. EachFieldIdT InstT::*... each_field_id)
  435. -> SemIR::ConstantId {
  436. return RebuildIfFieldsAreConstantImpl(
  437. eval_context, inst, [](...) { return true; }, std::identity{},
  438. each_field_id...);
  439. }
  440. // Rebuilds the given aggregate initialization instruction as a corresponding
  441. // constant aggregate value, if its elements are all constants.
  442. static auto RebuildInitAsValue(EvalContext& eval_context, SemIR::Inst inst,
  443. SemIR::InstKind value_kind)
  444. -> SemIR::ConstantId {
  445. return TransformIfFieldsAreConstant(
  446. eval_context, inst,
  447. [&](SemIR::AnyAggregateInit result) {
  448. return SemIR::AnyAggregateValue{.kind = value_kind,
  449. .type_id = result.type_id,
  450. .elements_id = result.elements_id};
  451. },
  452. &SemIR::AnyAggregateInit::type_id, &SemIR::AnyAggregateInit::elements_id);
  453. }
  454. // Performs an access into an aggregate, retrieving the specified element.
  455. static auto PerformAggregateAccess(EvalContext& eval_context, SemIR::Inst inst)
  456. -> SemIR::ConstantId {
  457. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  458. Phase phase = Phase::Template;
  459. if (auto aggregate_id =
  460. GetConstantValue(eval_context, access_inst.aggregate_id, &phase);
  461. aggregate_id.is_valid()) {
  462. if (auto aggregate =
  463. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(
  464. aggregate_id)) {
  465. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  466. auto index = static_cast<size_t>(access_inst.index.index);
  467. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  468. // `Phase` is not used here. If this element is a template constant, then
  469. // so is the result of indexing, even if the aggregate also contains a
  470. // symbolic context.
  471. return eval_context.GetConstantValue(elements[index]);
  472. } else {
  473. CARBON_CHECK(phase != Phase::Template,
  474. "Failed to evaluate template constant {0}", inst);
  475. }
  476. }
  477. return MakeNonConstantResult(phase);
  478. }
  479. // Performs an index into a homogeneous aggregate, retrieving the specified
  480. // element.
  481. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  482. -> SemIR::ConstantId {
  483. Phase phase = Phase::Template;
  484. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  485. if (!index_id.is_valid()) {
  486. return MakeNonConstantResult(phase);
  487. }
  488. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  489. if (!index) {
  490. CARBON_CHECK(phase != Phase::Template,
  491. "Template constant integer should be a literal");
  492. return MakeNonConstantResult(phase);
  493. }
  494. // Array indexing is invalid if the index is constant and out of range,
  495. // regardless of whether the array itself is constant.
  496. const auto& index_val = eval_context.ints().Get(index->int_id);
  497. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  498. eval_context.insts().Get(inst.array_id).type_id());
  499. if (auto array_type =
  500. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  501. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  502. array_type->bound_id)) {
  503. // This awkward call to `getZExtValue` is a workaround for APInt not
  504. // supporting comparisons between integers of different bit widths.
  505. if (index_val.getActiveBits() > 64 ||
  506. eval_context.ints()
  507. .Get(bound->int_id)
  508. .ule(index_val.getZExtValue())) {
  509. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  510. "array index `{0}` is past the end of type {1}",
  511. TypedInt, SemIR::TypeId);
  512. eval_context.emitter().Emit(
  513. inst.index_id, ArrayIndexOutOfBounds,
  514. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  515. return SemIR::ConstantId::Error;
  516. }
  517. }
  518. }
  519. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  520. if (!aggregate_id.is_valid()) {
  521. return MakeNonConstantResult(phase);
  522. }
  523. auto aggregate =
  524. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  525. if (!aggregate) {
  526. CARBON_CHECK(phase != Phase::Template,
  527. "Unexpected representation for template constant aggregate");
  528. return MakeNonConstantResult(phase);
  529. }
  530. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  531. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  532. }
  533. // Enforces that an integer type has a valid bit width.
  534. static auto ValidateIntType(Context& context, SemIRLoc loc,
  535. SemIR::IntType result) -> bool {
  536. auto bit_width =
  537. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  538. if (!bit_width) {
  539. // Symbolic bit width.
  540. return true;
  541. }
  542. const auto& bit_width_val = context.ints().Get(bit_width->int_id);
  543. if (bit_width_val.isZero() ||
  544. (context.types().IsSignedInt(bit_width->type_id) &&
  545. bit_width_val.isNegative())) {
  546. CARBON_DIAGNOSTIC(IntWidthNotPositive, Error,
  547. "integer type width of {0} is not positive", TypedInt);
  548. context.emitter().Emit(
  549. loc, IntWidthNotPositive,
  550. {.type = bit_width->type_id, .value = bit_width_val});
  551. return false;
  552. }
  553. // TODO: Pick a maximum size and document it in the design. For now
  554. // we use 2^^23, because that's the largest size that LLVM supports.
  555. constexpr int MaxIntWidth = 1 << 23;
  556. if (bit_width_val.ugt(MaxIntWidth)) {
  557. CARBON_DIAGNOSTIC(IntWidthTooLarge, Error,
  558. "integer type width of {0} is greater than the "
  559. "maximum supported width of {1}",
  560. TypedInt, int);
  561. context.emitter().Emit(loc, IntWidthTooLarge,
  562. {.type = bit_width->type_id, .value = bit_width_val},
  563. MaxIntWidth);
  564. return false;
  565. }
  566. return true;
  567. }
  568. // Forms a constant int type as an evaluation result. Requires that width_id is
  569. // constant.
  570. static auto MakeIntTypeResult(Context& context, SemIRLoc loc,
  571. SemIR::IntKind int_kind, SemIR::InstId width_id,
  572. Phase phase) -> SemIR::ConstantId {
  573. auto result = SemIR::IntType{
  574. .type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::TypeType),
  575. .int_kind = int_kind,
  576. .bit_width_id = width_id};
  577. if (!ValidateIntType(context, loc, result)) {
  578. return SemIR::ConstantId::Error;
  579. }
  580. return MakeConstantResult(context, result, phase);
  581. }
  582. // Enforces that the bit width is 64 for a float.
  583. static auto ValidateFloatBitWidth(Context& context, SemIRLoc loc,
  584. SemIR::InstId inst_id) -> bool {
  585. auto inst = context.insts().GetAs<SemIR::IntValue>(inst_id);
  586. if (context.ints().Get(inst.int_id) == 64) {
  587. return true;
  588. }
  589. CARBON_DIAGNOSTIC(CompileTimeFloatBitWidth, Error, "bit width must be 64");
  590. context.emitter().Emit(loc, CompileTimeFloatBitWidth);
  591. return false;
  592. }
  593. // Enforces that a float type has a valid bit width.
  594. static auto ValidateFloatType(Context& context, SemIRLoc loc,
  595. SemIR::FloatType result) -> bool {
  596. auto bit_width =
  597. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  598. if (!bit_width) {
  599. // Symbolic bit width.
  600. return true;
  601. }
  602. return ValidateFloatBitWidth(context, loc, result.bit_width_id);
  603. }
  604. // Performs a conversion between integer types, diagnosing if the value doesn't
  605. // fit in the destination type.
  606. static auto PerformCheckedIntConvert(Context& context, SemIRLoc loc,
  607. SemIR::InstId arg_id,
  608. SemIR::TypeId dest_type_id)
  609. -> SemIR::ConstantId {
  610. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  611. auto arg_val = context.ints().Get(arg.int_id);
  612. auto [is_signed, bit_width_id] =
  613. context.sem_ir().GetIntTypeInfo(dest_type_id);
  614. auto width = bit_width_id.is_valid()
  615. ? context.ints().Get(bit_width_id).getZExtValue()
  616. : arg_val.getBitWidth();
  617. if (!is_signed && arg_val.isNegative()) {
  618. CARBON_DIAGNOSTIC(
  619. NegativeIntInUnsignedType, Error,
  620. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  621. SemIR::TypeId);
  622. context.emitter().Emit(loc, NegativeIntInUnsignedType,
  623. {.type = arg.type_id, .value = arg_val},
  624. dest_type_id);
  625. }
  626. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  627. if (arg_non_sign_bits + is_signed > width) {
  628. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  629. "integer value {0} too large for type {1}", TypedInt,
  630. SemIR::TypeId);
  631. context.emitter().Emit(loc, IntTooLargeForType,
  632. {.type = arg.type_id, .value = arg_val},
  633. dest_type_id);
  634. }
  635. return MakeConstantResult(
  636. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  637. Phase::Template);
  638. }
  639. // Issues a diagnostic for a compile-time division by zero.
  640. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  641. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  642. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  643. }
  644. // Performs a builtin unary integer -> integer operation.
  645. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  646. SemIR::BuiltinFunctionKind builtin_kind,
  647. SemIR::InstId arg_id)
  648. -> SemIR::ConstantId {
  649. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  650. auto [is_signed, bit_width_id] = context.sem_ir().GetIntTypeInfo(op.type_id);
  651. CARBON_CHECK(bit_width_id != IntId::Invalid,
  652. "Cannot evaluate a generic bit width integer: {0}", op);
  653. llvm::APInt op_val = context.ints().GetAtWidth(op.int_id, bit_width_id);
  654. switch (builtin_kind) {
  655. case SemIR::BuiltinFunctionKind::IntSNegate:
  656. if (is_signed && op_val.isMinSignedValue()) {
  657. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  658. "integer overflow in negation of {0}", TypedInt);
  659. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  660. {.type = op.type_id, .value = op_val});
  661. }
  662. op_val.negate();
  663. break;
  664. case SemIR::BuiltinFunctionKind::IntUNegate:
  665. op_val.negate();
  666. break;
  667. case SemIR::BuiltinFunctionKind::IntComplement:
  668. op_val.flipAllBits();
  669. break;
  670. default:
  671. CARBON_FATAL("Unexpected builtin kind");
  672. }
  673. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  674. }
  675. // Performs a builtin binary integer -> integer operation.
  676. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  677. SemIR::BuiltinFunctionKind builtin_kind,
  678. SemIR::InstId lhs_id,
  679. SemIR::InstId rhs_id)
  680. -> SemIR::ConstantId {
  681. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  682. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  683. // Check for division by zero.
  684. switch (builtin_kind) {
  685. case SemIR::BuiltinFunctionKind::IntSDiv:
  686. case SemIR::BuiltinFunctionKind::IntSMod:
  687. case SemIR::BuiltinFunctionKind::IntUDiv:
  688. case SemIR::BuiltinFunctionKind::IntUMod:
  689. if (context.ints().Get(rhs.int_id).isZero()) {
  690. DiagnoseDivisionByZero(context, loc);
  691. return SemIR::ConstantId::Error;
  692. }
  693. break;
  694. default:
  695. break;
  696. }
  697. auto [lhs_is_signed, lhs_bit_width_id] =
  698. context.sem_ir().GetIntTypeInfo(lhs.type_id);
  699. llvm::APInt lhs_val = context.ints().GetAtWidth(lhs.int_id, lhs_bit_width_id);
  700. llvm::APInt result_val;
  701. // First handle shift, which can directly use the canonical RHS and doesn't
  702. // overflow.
  703. switch (builtin_kind) {
  704. // Bit shift.
  705. case SemIR::BuiltinFunctionKind::IntLeftShift:
  706. case SemIR::BuiltinFunctionKind::IntRightShift: {
  707. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  708. if (rhs_orig_val.uge(lhs_val.getBitWidth()) ||
  709. (rhs_orig_val.isNegative() && lhs_is_signed)) {
  710. CARBON_DIAGNOSTIC(
  711. CompileTimeShiftOutOfRange, Error,
  712. "shift distance not in range [0, {0}) in {1} {2:<<|>>} {3}",
  713. unsigned, TypedInt, BoolAsSelect, TypedInt);
  714. context.emitter().Emit(
  715. loc, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  716. {.type = lhs.type_id, .value = lhs_val},
  717. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  718. {.type = rhs.type_id, .value = rhs_orig_val});
  719. // TODO: Is it useful to recover by returning 0 or -1?
  720. return SemIR::ConstantId::Error;
  721. }
  722. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  723. result_val = lhs_val.shl(rhs_orig_val);
  724. } else if (lhs_is_signed) {
  725. result_val = lhs_val.ashr(rhs_orig_val);
  726. } else {
  727. result_val = lhs_val.lshr(rhs_orig_val);
  728. }
  729. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  730. std::move(result_val));
  731. }
  732. default:
  733. // Break to do additional setup for other builtin kinds.
  734. break;
  735. }
  736. // Other operations are already checked to be homogeneous, so we can extend
  737. // the RHS with the LHS bit width.
  738. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  739. llvm::APInt rhs_val = context.ints().GetAtWidth(rhs.int_id, lhs_bit_width_id);
  740. // We may also need to diagnose overflow for these operations.
  741. bool overflow = false;
  742. Lex::TokenKind op_token = Lex::TokenKind::Not;
  743. switch (builtin_kind) {
  744. // Arithmetic.
  745. case SemIR::BuiltinFunctionKind::IntSAdd:
  746. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  747. op_token = Lex::TokenKind::Plus;
  748. break;
  749. case SemIR::BuiltinFunctionKind::IntSSub:
  750. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  751. op_token = Lex::TokenKind::Minus;
  752. break;
  753. case SemIR::BuiltinFunctionKind::IntSMul:
  754. result_val = lhs_val.smul_ov(rhs_val, overflow);
  755. op_token = Lex::TokenKind::Star;
  756. break;
  757. case SemIR::BuiltinFunctionKind::IntSDiv:
  758. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  759. op_token = Lex::TokenKind::Slash;
  760. break;
  761. case SemIR::BuiltinFunctionKind::IntSMod:
  762. result_val = lhs_val.srem(rhs_val);
  763. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  764. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  765. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  766. op_token = Lex::TokenKind::Percent;
  767. break;
  768. case SemIR::BuiltinFunctionKind::IntUAdd:
  769. result_val = lhs_val + rhs_val;
  770. op_token = Lex::TokenKind::Plus;
  771. break;
  772. case SemIR::BuiltinFunctionKind::IntUSub:
  773. result_val = lhs_val - rhs_val;
  774. op_token = Lex::TokenKind::Minus;
  775. break;
  776. case SemIR::BuiltinFunctionKind::IntUMul:
  777. result_val = lhs_val * rhs_val;
  778. op_token = Lex::TokenKind::Star;
  779. break;
  780. case SemIR::BuiltinFunctionKind::IntUDiv:
  781. result_val = lhs_val.udiv(rhs_val);
  782. op_token = Lex::TokenKind::Slash;
  783. break;
  784. case SemIR::BuiltinFunctionKind::IntUMod:
  785. result_val = lhs_val.urem(rhs_val);
  786. op_token = Lex::TokenKind::Percent;
  787. break;
  788. // Bitwise.
  789. case SemIR::BuiltinFunctionKind::IntAnd:
  790. result_val = lhs_val & rhs_val;
  791. op_token = Lex::TokenKind::And;
  792. break;
  793. case SemIR::BuiltinFunctionKind::IntOr:
  794. result_val = lhs_val | rhs_val;
  795. op_token = Lex::TokenKind::Pipe;
  796. break;
  797. case SemIR::BuiltinFunctionKind::IntXor:
  798. result_val = lhs_val ^ rhs_val;
  799. op_token = Lex::TokenKind::Caret;
  800. break;
  801. case SemIR::BuiltinFunctionKind::IntLeftShift:
  802. case SemIR::BuiltinFunctionKind::IntRightShift:
  803. CARBON_FATAL("Handled specially above.");
  804. default:
  805. CARBON_FATAL("Unexpected operation kind.");
  806. }
  807. if (overflow) {
  808. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  809. "integer overflow in calculation {0} {1} {2}", TypedInt,
  810. Lex::TokenKind, TypedInt);
  811. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  812. {.type = lhs.type_id, .value = lhs_val}, op_token,
  813. {.type = rhs.type_id, .value = rhs_val});
  814. }
  815. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  816. std::move(result_val));
  817. }
  818. // Performs a builtin integer comparison.
  819. static auto PerformBuiltinIntComparison(Context& context,
  820. SemIR::BuiltinFunctionKind builtin_kind,
  821. SemIR::InstId lhs_id,
  822. SemIR::InstId rhs_id,
  823. SemIR::TypeId bool_type_id)
  824. -> SemIR::ConstantId {
  825. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  826. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  827. CARBON_CHECK(lhs.type_id == rhs.type_id,
  828. "Builtin comparison with mismatched types!");
  829. auto [is_signed, bit_width_id] = context.sem_ir().GetIntTypeInfo(lhs.type_id);
  830. CARBON_CHECK(bit_width_id != IntId::Invalid,
  831. "Cannot evaluate a generic bit width integer: {0}", lhs);
  832. llvm::APInt lhs_val = context.ints().GetAtWidth(lhs.int_id, bit_width_id);
  833. llvm::APInt rhs_val = context.ints().GetAtWidth(rhs.int_id, bit_width_id);
  834. bool result;
  835. switch (builtin_kind) {
  836. case SemIR::BuiltinFunctionKind::IntEq:
  837. result = (lhs_val == rhs_val);
  838. break;
  839. case SemIR::BuiltinFunctionKind::IntNeq:
  840. result = (lhs_val != rhs_val);
  841. break;
  842. case SemIR::BuiltinFunctionKind::IntLess:
  843. result = is_signed ? lhs_val.slt(rhs_val) : lhs_val.ult(rhs_val);
  844. break;
  845. case SemIR::BuiltinFunctionKind::IntLessEq:
  846. result = is_signed ? lhs_val.sle(rhs_val) : lhs_val.ule(rhs_val);
  847. break;
  848. case SemIR::BuiltinFunctionKind::IntGreater:
  849. result = is_signed ? lhs_val.sgt(rhs_val) : lhs_val.sgt(rhs_val);
  850. break;
  851. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  852. result = is_signed ? lhs_val.sge(rhs_val) : lhs_val.sge(rhs_val);
  853. break;
  854. default:
  855. CARBON_FATAL("Unexpected operation kind.");
  856. }
  857. return MakeBoolResult(context, bool_type_id, result);
  858. }
  859. // Performs a builtin unary float -> float operation.
  860. static auto PerformBuiltinUnaryFloatOp(Context& context,
  861. SemIR::BuiltinFunctionKind builtin_kind,
  862. SemIR::InstId arg_id)
  863. -> SemIR::ConstantId {
  864. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  865. auto op_val = context.floats().Get(op.float_id);
  866. switch (builtin_kind) {
  867. case SemIR::BuiltinFunctionKind::FloatNegate:
  868. op_val.changeSign();
  869. break;
  870. default:
  871. CARBON_FATAL("Unexpected builtin kind");
  872. }
  873. return MakeFloatResult(context, op.type_id, std::move(op_val));
  874. }
  875. // Performs a builtin binary float -> float operation.
  876. static auto PerformBuiltinBinaryFloatOp(Context& context,
  877. SemIR::BuiltinFunctionKind builtin_kind,
  878. SemIR::InstId lhs_id,
  879. SemIR::InstId rhs_id)
  880. -> SemIR::ConstantId {
  881. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  882. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  883. auto lhs_val = context.floats().Get(lhs.float_id);
  884. auto rhs_val = context.floats().Get(rhs.float_id);
  885. llvm::APFloat result_val(lhs_val.getSemantics());
  886. switch (builtin_kind) {
  887. case SemIR::BuiltinFunctionKind::FloatAdd:
  888. result_val = lhs_val + rhs_val;
  889. break;
  890. case SemIR::BuiltinFunctionKind::FloatSub:
  891. result_val = lhs_val - rhs_val;
  892. break;
  893. case SemIR::BuiltinFunctionKind::FloatMul:
  894. result_val = lhs_val * rhs_val;
  895. break;
  896. case SemIR::BuiltinFunctionKind::FloatDiv:
  897. result_val = lhs_val / rhs_val;
  898. break;
  899. default:
  900. CARBON_FATAL("Unexpected operation kind.");
  901. }
  902. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  903. }
  904. // Performs a builtin float comparison.
  905. static auto PerformBuiltinFloatComparison(
  906. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  907. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  908. -> SemIR::ConstantId {
  909. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  910. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  911. const auto& lhs_val = context.floats().Get(lhs.float_id);
  912. const auto& rhs_val = context.floats().Get(rhs.float_id);
  913. bool result;
  914. switch (builtin_kind) {
  915. case SemIR::BuiltinFunctionKind::FloatEq:
  916. result = (lhs_val == rhs_val);
  917. break;
  918. case SemIR::BuiltinFunctionKind::FloatNeq:
  919. result = (lhs_val != rhs_val);
  920. break;
  921. case SemIR::BuiltinFunctionKind::FloatLess:
  922. result = lhs_val < rhs_val;
  923. break;
  924. case SemIR::BuiltinFunctionKind::FloatLessEq:
  925. result = lhs_val <= rhs_val;
  926. break;
  927. case SemIR::BuiltinFunctionKind::FloatGreater:
  928. result = lhs_val > rhs_val;
  929. break;
  930. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  931. result = lhs_val >= rhs_val;
  932. break;
  933. default:
  934. CARBON_FATAL("Unexpected operation kind.");
  935. }
  936. return MakeBoolResult(context, bool_type_id, result);
  937. }
  938. // Returns a constant for a call to a builtin function.
  939. static auto MakeConstantForBuiltinCall(Context& context, SemIRLoc loc,
  940. SemIR::Call call,
  941. SemIR::BuiltinFunctionKind builtin_kind,
  942. llvm::ArrayRef<SemIR::InstId> arg_ids,
  943. Phase phase) -> SemIR::ConstantId {
  944. switch (builtin_kind) {
  945. case SemIR::BuiltinFunctionKind::None:
  946. CARBON_FATAL("Not a builtin function.");
  947. case SemIR::BuiltinFunctionKind::PrintInt: {
  948. // Providing a constant result would allow eliding the function call.
  949. return SemIR::ConstantId::NotConstant;
  950. }
  951. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  952. return context.constant_values().Get(
  953. SemIR::InstId::BuiltinIntLiteralType);
  954. }
  955. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  956. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  957. phase);
  958. }
  959. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  960. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  961. arg_ids[0], phase);
  962. }
  963. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  964. // TODO: Support a symbolic constant width.
  965. if (phase != Phase::Template) {
  966. break;
  967. }
  968. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  969. return SemIR::ConstantId::Error;
  970. }
  971. return context.constant_values().Get(
  972. SemIR::InstId::BuiltinLegacyFloatType);
  973. }
  974. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  975. return context.constant_values().Get(SemIR::InstId::BuiltinBoolType);
  976. }
  977. // Integer conversions.
  978. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  979. if (phase == Phase::Symbolic) {
  980. return MakeConstantResult(context, call, phase);
  981. }
  982. return PerformCheckedIntConvert(context, loc, arg_ids[0], call.type_id);
  983. }
  984. // Unary integer -> integer operations.
  985. case SemIR::BuiltinFunctionKind::IntSNegate:
  986. case SemIR::BuiltinFunctionKind::IntUNegate:
  987. case SemIR::BuiltinFunctionKind::IntComplement: {
  988. if (phase != Phase::Template) {
  989. break;
  990. }
  991. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  992. }
  993. // Binary integer -> integer operations.
  994. case SemIR::BuiltinFunctionKind::IntSAdd:
  995. case SemIR::BuiltinFunctionKind::IntSSub:
  996. case SemIR::BuiltinFunctionKind::IntSMul:
  997. case SemIR::BuiltinFunctionKind::IntSDiv:
  998. case SemIR::BuiltinFunctionKind::IntSMod:
  999. case SemIR::BuiltinFunctionKind::IntUAdd:
  1000. case SemIR::BuiltinFunctionKind::IntUSub:
  1001. case SemIR::BuiltinFunctionKind::IntUMul:
  1002. case SemIR::BuiltinFunctionKind::IntUDiv:
  1003. case SemIR::BuiltinFunctionKind::IntUMod:
  1004. case SemIR::BuiltinFunctionKind::IntAnd:
  1005. case SemIR::BuiltinFunctionKind::IntOr:
  1006. case SemIR::BuiltinFunctionKind::IntXor:
  1007. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1008. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1009. if (phase != Phase::Template) {
  1010. break;
  1011. }
  1012. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  1013. arg_ids[1]);
  1014. }
  1015. // Integer comparisons.
  1016. case SemIR::BuiltinFunctionKind::IntEq:
  1017. case SemIR::BuiltinFunctionKind::IntNeq:
  1018. case SemIR::BuiltinFunctionKind::IntLess:
  1019. case SemIR::BuiltinFunctionKind::IntLessEq:
  1020. case SemIR::BuiltinFunctionKind::IntGreater:
  1021. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1022. if (phase != Phase::Template) {
  1023. break;
  1024. }
  1025. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1026. arg_ids[1], call.type_id);
  1027. }
  1028. // Unary float -> float operations.
  1029. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1030. if (phase != Phase::Template) {
  1031. break;
  1032. }
  1033. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1034. }
  1035. // Binary float -> float operations.
  1036. case SemIR::BuiltinFunctionKind::FloatAdd:
  1037. case SemIR::BuiltinFunctionKind::FloatSub:
  1038. case SemIR::BuiltinFunctionKind::FloatMul:
  1039. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1040. if (phase != Phase::Template) {
  1041. break;
  1042. }
  1043. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1044. arg_ids[1]);
  1045. }
  1046. // Float comparisons.
  1047. case SemIR::BuiltinFunctionKind::FloatEq:
  1048. case SemIR::BuiltinFunctionKind::FloatNeq:
  1049. case SemIR::BuiltinFunctionKind::FloatLess:
  1050. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1051. case SemIR::BuiltinFunctionKind::FloatGreater:
  1052. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1053. if (phase != Phase::Template) {
  1054. break;
  1055. }
  1056. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1057. arg_ids[1], call.type_id);
  1058. }
  1059. }
  1060. return SemIR::ConstantId::NotConstant;
  1061. }
  1062. // Makes a constant for a call instruction.
  1063. static auto MakeConstantForCall(EvalContext& eval_context, SemIRLoc loc,
  1064. SemIR::Call call) -> SemIR::ConstantId {
  1065. Phase phase = Phase::Template;
  1066. // A call with an invalid argument list is used to represent an erroneous
  1067. // call.
  1068. //
  1069. // TODO: Use a better representation for this.
  1070. if (call.args_id == SemIR::InstBlockId::Invalid) {
  1071. return SemIR::ConstantId::Error;
  1072. }
  1073. // Find the constant value of the callee.
  1074. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1075. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1076. auto callee_function =
  1077. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1078. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1079. if (callee_function.function_id.is_valid()) {
  1080. // Calls to builtins might be constant.
  1081. builtin_kind = eval_context.functions()
  1082. .Get(callee_function.function_id)
  1083. .builtin_function_kind;
  1084. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1085. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1086. // functions as producing constants.
  1087. return SemIR::ConstantId::NotConstant;
  1088. }
  1089. } else {
  1090. // Calls to non-functions, such as calls to generic entity names, might be
  1091. // constant.
  1092. }
  1093. // Find the argument values and the return type.
  1094. bool has_constant_operands =
  1095. has_constant_callee &&
  1096. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  1097. &phase) &&
  1098. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1099. &phase);
  1100. if (phase == Phase::UnknownDueToError) {
  1101. return SemIR::ConstantId::Error;
  1102. }
  1103. // If any operand of the call is non-constant, the call is non-constant.
  1104. // TODO: Some builtin calls might allow some operands to be non-constant.
  1105. if (!has_constant_operands) {
  1106. if (builtin_kind.IsCompTimeOnly()) {
  1107. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1108. "non-constant call to compile-time-only function");
  1109. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1110. "compile-time-only function declared here");
  1111. eval_context.emitter()
  1112. .Build(loc, NonConstantCallToCompTimeOnlyFunction)
  1113. .Note(eval_context.functions()
  1114. .Get(callee_function.function_id)
  1115. .latest_decl_id(),
  1116. CompTimeOnlyFunctionHere)
  1117. .Emit();
  1118. }
  1119. return SemIR::ConstantId::NotConstant;
  1120. }
  1121. // Handle calls to builtins.
  1122. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1123. return MakeConstantForBuiltinCall(
  1124. eval_context.context(), loc, call, builtin_kind,
  1125. eval_context.inst_blocks().Get(call.args_id), phase);
  1126. }
  1127. return SemIR::ConstantId::NotConstant;
  1128. }
  1129. // Creates a FacetType constant.
  1130. static auto MakeFacetTypeResult(Context& context,
  1131. const SemIR::FacetTypeInfo& info, Phase phase)
  1132. -> SemIR::ConstantId {
  1133. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  1134. return MakeConstantResult(context,
  1135. SemIR::FacetType{.type_id = SemIR::TypeId::TypeType,
  1136. .facet_type_id = facet_type_id},
  1137. phase);
  1138. }
  1139. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1140. static auto TryEvalInstInContext(EvalContext& eval_context,
  1141. SemIR::InstId inst_id, SemIR::Inst inst)
  1142. -> SemIR::ConstantId {
  1143. // TODO: Ensure we have test coverage for each of these cases that can result
  1144. // in a constant, once those situations are all reachable.
  1145. CARBON_KIND_SWITCH(inst) {
  1146. // These cases are constants if their operands are.
  1147. case SemIR::AddrOf::Kind:
  1148. return RebuildIfFieldsAreConstant(eval_context, inst,
  1149. &SemIR::AddrOf::type_id,
  1150. &SemIR::AddrOf::lvalue_id);
  1151. case CARBON_KIND(SemIR::ArrayType array_type): {
  1152. return RebuildAndValidateIfFieldsAreConstant(
  1153. eval_context, inst,
  1154. [&](SemIR::ArrayType result) {
  1155. auto bound_id = array_type.bound_id;
  1156. auto int_bound =
  1157. eval_context.insts().TryGetAs<SemIR::IntValue>(result.bound_id);
  1158. if (!int_bound) {
  1159. // TODO: Permit symbolic array bounds. This will require fixing
  1160. // callers of `GetArrayBoundValue`.
  1161. eval_context.context().TODO(bound_id, "symbolic array bound");
  1162. return false;
  1163. }
  1164. // TODO: We should check that the size of the resulting array type
  1165. // fits in 64 bits, not just that the bound does. Should we use a
  1166. // 32-bit limit for 32-bit targets?
  1167. const auto& bound_val = eval_context.ints().Get(int_bound->int_id);
  1168. if (eval_context.types().IsSignedInt(int_bound->type_id) &&
  1169. bound_val.isNegative()) {
  1170. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  1171. "array bound of {0} is negative", TypedInt);
  1172. eval_context.emitter().Emit(
  1173. bound_id, ArrayBoundNegative,
  1174. {.type = int_bound->type_id, .value = bound_val});
  1175. return false;
  1176. }
  1177. if (bound_val.getActiveBits() > 64) {
  1178. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  1179. "array bound of {0} is too large", TypedInt);
  1180. eval_context.emitter().Emit(
  1181. bound_id, ArrayBoundTooLarge,
  1182. {.type = int_bound->type_id, .value = bound_val});
  1183. return false;
  1184. }
  1185. return true;
  1186. },
  1187. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  1188. }
  1189. case SemIR::AssociatedEntity::Kind:
  1190. return RebuildIfFieldsAreConstant(eval_context, inst,
  1191. &SemIR::AssociatedEntity::type_id);
  1192. case SemIR::AssociatedEntityType::Kind:
  1193. return RebuildIfFieldsAreConstant(
  1194. eval_context, inst, &SemIR::AssociatedEntityType::interface_type_id,
  1195. &SemIR::AssociatedEntityType::entity_type_id);
  1196. case SemIR::BoundMethod::Kind:
  1197. return RebuildIfFieldsAreConstant(
  1198. eval_context, inst, &SemIR::BoundMethod::type_id,
  1199. &SemIR::BoundMethod::object_id, &SemIR::BoundMethod::function_id);
  1200. case SemIR::ClassType::Kind:
  1201. return RebuildIfFieldsAreConstant(eval_context, inst,
  1202. &SemIR::ClassType::specific_id);
  1203. case SemIR::CompleteTypeWitness::Kind:
  1204. return RebuildIfFieldsAreConstant(
  1205. eval_context, inst, &SemIR::CompleteTypeWitness::object_repr_id);
  1206. case SemIR::FunctionType::Kind:
  1207. return RebuildIfFieldsAreConstant(eval_context, inst,
  1208. &SemIR::FunctionType::specific_id);
  1209. case SemIR::GenericClassType::Kind:
  1210. return RebuildIfFieldsAreConstant(
  1211. eval_context, inst, &SemIR::GenericClassType::enclosing_specific_id);
  1212. case SemIR::GenericInterfaceType::Kind:
  1213. return RebuildIfFieldsAreConstant(
  1214. eval_context, inst,
  1215. &SemIR::GenericInterfaceType::enclosing_specific_id);
  1216. case SemIR::InterfaceWitness::Kind:
  1217. return RebuildIfFieldsAreConstant(eval_context, inst,
  1218. &SemIR::InterfaceWitness::elements_id);
  1219. case CARBON_KIND(SemIR::IntType int_type): {
  1220. return RebuildAndValidateIfFieldsAreConstant(
  1221. eval_context, inst,
  1222. [&](SemIR::IntType result) {
  1223. return ValidateIntType(
  1224. eval_context.context(),
  1225. inst_id.is_valid() ? inst_id : int_type.bit_width_id, result);
  1226. },
  1227. &SemIR::IntType::bit_width_id);
  1228. }
  1229. case SemIR::PointerType::Kind:
  1230. return RebuildIfFieldsAreConstant(eval_context, inst,
  1231. &SemIR::PointerType::pointee_id);
  1232. case CARBON_KIND(SemIR::FloatType float_type): {
  1233. return RebuildAndValidateIfFieldsAreConstant(
  1234. eval_context, inst,
  1235. [&](SemIR::FloatType result) {
  1236. return ValidateFloatType(eval_context.context(),
  1237. float_type.bit_width_id, result);
  1238. },
  1239. &SemIR::FloatType::bit_width_id);
  1240. }
  1241. case SemIR::SpecificFunction::Kind:
  1242. return RebuildIfFieldsAreConstant(eval_context, inst,
  1243. &SemIR::SpecificFunction::callee_id,
  1244. &SemIR::SpecificFunction::specific_id);
  1245. case SemIR::StructType::Kind:
  1246. return RebuildIfFieldsAreConstant(eval_context, inst,
  1247. &SemIR::StructType::fields_id);
  1248. case SemIR::StructValue::Kind:
  1249. return RebuildIfFieldsAreConstant(eval_context, inst,
  1250. &SemIR::StructValue::type_id,
  1251. &SemIR::StructValue::elements_id);
  1252. case SemIR::TupleType::Kind:
  1253. return RebuildIfFieldsAreConstant(eval_context, inst,
  1254. &SemIR::TupleType::elements_id);
  1255. case SemIR::TupleValue::Kind:
  1256. return RebuildIfFieldsAreConstant(eval_context, inst,
  1257. &SemIR::TupleValue::type_id,
  1258. &SemIR::TupleValue::elements_id);
  1259. case SemIR::UnboundElementType::Kind:
  1260. return RebuildIfFieldsAreConstant(
  1261. eval_context, inst, &SemIR::UnboundElementType::class_type_id,
  1262. &SemIR::UnboundElementType::element_type_id);
  1263. // Initializers evaluate to a value of the object representation.
  1264. case SemIR::ArrayInit::Kind:
  1265. // TODO: Add an `ArrayValue` to represent a constant array object
  1266. // representation instead of using a `TupleValue`.
  1267. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1268. case SemIR::ClassInit::Kind:
  1269. // TODO: Add a `ClassValue` to represent a constant class object
  1270. // representation instead of using a `StructValue`.
  1271. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1272. case SemIR::StructInit::Kind:
  1273. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1274. case SemIR::TupleInit::Kind:
  1275. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1276. case SemIR::BuiltinInst::Kind:
  1277. // Builtins are always template constants.
  1278. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1279. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  1280. return TransformIfFieldsAreConstant(
  1281. eval_context, fn_decl,
  1282. [&](SemIR::FunctionDecl result) {
  1283. return SemIR::StructValue{.type_id = result.type_id,
  1284. .elements_id = SemIR::InstBlockId::Empty};
  1285. },
  1286. &SemIR::FunctionDecl::type_id);
  1287. }
  1288. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  1289. // If the class has generic parameters, we don't produce a class type, but
  1290. // a callable whose return value is a class type.
  1291. if (eval_context.classes().Get(class_decl.class_id).has_parameters()) {
  1292. return TransformIfFieldsAreConstant(
  1293. eval_context, class_decl,
  1294. [&](SemIR::ClassDecl result) {
  1295. return SemIR::StructValue{
  1296. .type_id = result.type_id,
  1297. .elements_id = SemIR::InstBlockId::Empty};
  1298. },
  1299. &SemIR::ClassDecl::type_id);
  1300. }
  1301. // A non-generic class declaration evaluates to the class type.
  1302. return MakeConstantResult(
  1303. eval_context.context(),
  1304. SemIR::ClassType{.type_id = SemIR::TypeId::TypeType,
  1305. .class_id = class_decl.class_id,
  1306. .specific_id = SemIR::SpecificId::Invalid},
  1307. Phase::Template);
  1308. }
  1309. case CARBON_KIND(SemIR::FacetType facet_type): {
  1310. Phase phase = Phase::Template;
  1311. SemIR::FacetTypeInfo info = GetConstantFacetTypeInfo(
  1312. eval_context, facet_type.facet_type_id, &phase);
  1313. // TODO: Reuse `inst` if we can detect that nothing has changed.
  1314. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1315. }
  1316. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  1317. // If the interface has generic parameters, we don't produce an interface
  1318. // type, but a callable whose return value is an interface type.
  1319. if (eval_context.interfaces()
  1320. .Get(interface_decl.interface_id)
  1321. .has_parameters()) {
  1322. return TransformIfFieldsAreConstant(
  1323. eval_context, interface_decl,
  1324. [&](SemIR::InterfaceDecl result) {
  1325. return SemIR::StructValue{
  1326. .type_id = result.type_id,
  1327. .elements_id = SemIR::InstBlockId::Empty};
  1328. },
  1329. &SemIR::InterfaceDecl::type_id);
  1330. }
  1331. // A non-generic interface declaration evaluates to a facet type.
  1332. return MakeConstantResult(
  1333. eval_context.context(),
  1334. eval_context.context().FacetTypeFromInterface(
  1335. interface_decl.interface_id, SemIR::SpecificId::Invalid),
  1336. Phase::Template);
  1337. }
  1338. case CARBON_KIND(SemIR::SpecificConstant specific): {
  1339. // Pull the constant value out of the specific.
  1340. return SemIR::GetConstantValueInSpecific(
  1341. eval_context.sem_ir(), specific.specific_id, specific.inst_id);
  1342. }
  1343. // These cases are treated as being the unique canonical definition of the
  1344. // corresponding constant value.
  1345. // TODO: This doesn't properly handle redeclarations. Consider adding a
  1346. // corresponding `Value` inst for each of these cases, or returning the
  1347. // first declaration.
  1348. case SemIR::AssociatedConstantDecl::Kind:
  1349. case SemIR::BaseDecl::Kind:
  1350. case SemIR::FieldDecl::Kind:
  1351. case SemIR::ImplDecl::Kind:
  1352. case SemIR::Namespace::Kind:
  1353. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  1354. case SemIR::BoolLiteral::Kind:
  1355. case SemIR::FloatLiteral::Kind:
  1356. case SemIR::IntValue::Kind:
  1357. case SemIR::StringLiteral::Kind:
  1358. // Promote literals to the constant block.
  1359. // TODO: Convert literals into a canonical form. Currently we can form two
  1360. // different `i32` constants with the same value if they are represented
  1361. // by `APInt`s with different bit widths.
  1362. // TODO: Can the type of an IntValue or FloatLiteral be symbolic? If so,
  1363. // we may need to rebuild.
  1364. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1365. // The elements of a constant aggregate can be accessed.
  1366. case SemIR::ClassElementAccess::Kind:
  1367. case SemIR::InterfaceWitnessAccess::Kind:
  1368. case SemIR::StructAccess::Kind:
  1369. case SemIR::TupleAccess::Kind:
  1370. return PerformAggregateAccess(eval_context, inst);
  1371. case CARBON_KIND(SemIR::ArrayIndex index): {
  1372. return PerformArrayIndex(eval_context, index);
  1373. }
  1374. case CARBON_KIND(SemIR::Call call): {
  1375. return MakeConstantForCall(eval_context, inst_id, call);
  1376. }
  1377. // TODO: These need special handling.
  1378. case SemIR::BindValue::Kind:
  1379. case SemIR::Deref::Kind:
  1380. case SemIR::ImportRefLoaded::Kind:
  1381. case SemIR::ReturnSlot::Kind:
  1382. case SemIR::Temporary::Kind:
  1383. case SemIR::TemporaryStorage::Kind:
  1384. case SemIR::ValueAsRef::Kind:
  1385. break;
  1386. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  1387. // TODO: Disable constant evaluation of SymbolicBindingPattern once
  1388. // DeduceGenericCallArguments no longer needs implicit params to have
  1389. // constant values.
  1390. const auto& bind_name =
  1391. eval_context.entity_names().Get(bind.entity_name_id);
  1392. // If we know which specific we're evaluating within and this is an
  1393. // argument of that specific, its constant value is the corresponding
  1394. // argument value.
  1395. if (auto value =
  1396. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1397. value.is_valid()) {
  1398. return value;
  1399. }
  1400. // The constant form of a symbolic binding is an idealized form of the
  1401. // original, with no equivalent value.
  1402. bind.entity_name_id =
  1403. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1404. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1405. }
  1406. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  1407. const auto& bind_name =
  1408. eval_context.entity_names().Get(bind.entity_name_id);
  1409. // If we know which specific we're evaluating within and this is an
  1410. // argument of that specific, its constant value is the corresponding
  1411. // argument value.
  1412. if (auto value =
  1413. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1414. value.is_valid()) {
  1415. return value;
  1416. }
  1417. // The constant form of a symbolic binding is an idealized form of the
  1418. // original, with no equivalent value.
  1419. bind.entity_name_id =
  1420. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1421. bind.value_id = SemIR::InstId::Invalid;
  1422. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1423. }
  1424. // These semantic wrappers don't change the constant value.
  1425. case CARBON_KIND(SemIR::AsCompatible inst): {
  1426. return eval_context.GetConstantValue(inst.source_id);
  1427. }
  1428. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  1429. return eval_context.GetConstantValue(typed_inst.value_id);
  1430. }
  1431. case CARBON_KIND(SemIR::ExportDecl typed_inst): {
  1432. return eval_context.GetConstantValue(typed_inst.value_id);
  1433. }
  1434. case CARBON_KIND(SemIR::NameRef typed_inst): {
  1435. return eval_context.GetConstantValue(typed_inst.value_id);
  1436. }
  1437. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  1438. // TODO: Treat this as a non-expression (here and in GetExprCategory)
  1439. // once generic deduction doesn't need patterns to have constant values.
  1440. return eval_context.GetConstantValue(param_pattern.subpattern_id);
  1441. }
  1442. case CARBON_KIND(SemIR::Converted typed_inst): {
  1443. return eval_context.GetConstantValue(typed_inst.result_id);
  1444. }
  1445. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  1446. return eval_context.GetConstantValue(typed_inst.src_id);
  1447. }
  1448. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  1449. return eval_context.GetConstantValue(typed_inst.result_id);
  1450. }
  1451. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  1452. return eval_context.GetConstantValue(typed_inst.init_id);
  1453. }
  1454. case CARBON_KIND(SemIR::FacetTypeAccess typed_inst): {
  1455. // TODO: Once we start tracking the witness in the facet value, remove it
  1456. // here. For now, we model a facet value as just a type.
  1457. return eval_context.GetConstantValue(typed_inst.facet_id);
  1458. }
  1459. case CARBON_KIND(SemIR::WhereExpr typed_inst): {
  1460. Phase phase = Phase::Template;
  1461. SemIR::TypeId base_facet_type_id =
  1462. eval_context.insts().Get(typed_inst.period_self_id).type_id();
  1463. SemIR::Inst base_facet_inst =
  1464. eval_context.GetConstantValueAsInst(base_facet_type_id);
  1465. SemIR::FacetTypeInfo info = {.requirement_block_id =
  1466. SemIR::InstBlockId::Invalid};
  1467. // `where` provides that the base facet is an error, `type`, or a facet
  1468. // type.
  1469. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1470. info = GetConstantFacetTypeInfo(eval_context, facet_type->facet_type_id,
  1471. &phase);
  1472. } else if (base_facet_type_id == SemIR::TypeId::Error) {
  1473. return SemIR::ConstantId::Error;
  1474. } else {
  1475. CARBON_CHECK(base_facet_type_id == SemIR::TypeId::TypeType,
  1476. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1477. base_facet_inst);
  1478. }
  1479. // TODO: Combine other requirements, and then process & canonicalize them.
  1480. info.requirement_block_id = typed_inst.requirements_id;
  1481. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1482. }
  1483. // `not true` -> `false`, `not false` -> `true`.
  1484. // All other uses of unary `not` are non-constant.
  1485. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  1486. auto const_id = eval_context.GetConstantValue(typed_inst.operand_id);
  1487. auto phase = GetPhase(const_id);
  1488. if (phase == Phase::Template) {
  1489. auto value = eval_context.insts().GetAs<SemIR::BoolLiteral>(
  1490. eval_context.constant_values().GetInstId(const_id));
  1491. return MakeBoolResult(eval_context.context(), value.type_id,
  1492. !value.value.ToBool());
  1493. }
  1494. if (phase == Phase::UnknownDueToError) {
  1495. return SemIR::ConstantId::Error;
  1496. }
  1497. break;
  1498. }
  1499. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1500. // to itself.
  1501. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1502. auto phase = Phase::Template;
  1503. auto inner_id =
  1504. GetConstantValue(eval_context, typed_inst.inner_id, &phase);
  1505. if (eval_context.context().types().Is<SemIR::ConstType>(inner_id)) {
  1506. return eval_context.context().types().GetConstantId(inner_id);
  1507. }
  1508. typed_inst.inner_id = inner_id;
  1509. return MakeConstantResult(eval_context.context(), typed_inst, phase);
  1510. }
  1511. // These cases are either not expressions or not constant.
  1512. case SemIR::AdaptDecl::Kind:
  1513. case SemIR::AddrPattern::Kind:
  1514. case SemIR::Assign::Kind:
  1515. case SemIR::BindName::Kind:
  1516. case SemIR::BindingPattern::Kind:
  1517. case SemIR::BlockArg::Kind:
  1518. case SemIR::Branch::Kind:
  1519. case SemIR::BranchIf::Kind:
  1520. case SemIR::BranchWithArg::Kind:
  1521. case SemIR::ImportDecl::Kind:
  1522. case SemIR::OutParam::Kind:
  1523. case SemIR::OutParamPattern::Kind:
  1524. case SemIR::RequirementEquivalent::Kind:
  1525. case SemIR::RequirementImpls::Kind:
  1526. case SemIR::RequirementRewrite::Kind:
  1527. case SemIR::Return::Kind:
  1528. case SemIR::ReturnExpr::Kind:
  1529. case SemIR::ReturnSlotPattern::Kind:
  1530. case SemIR::StructLiteral::Kind:
  1531. case SemIR::TupleLiteral::Kind:
  1532. case SemIR::ValueParam::Kind:
  1533. case SemIR::VarStorage::Kind:
  1534. break;
  1535. case SemIR::ImportRefUnloaded::Kind:
  1536. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  1537. inst);
  1538. }
  1539. return SemIR::ConstantId::NotConstant;
  1540. }
  1541. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  1542. -> SemIR::ConstantId {
  1543. EvalContext eval_context(context);
  1544. return TryEvalInstInContext(eval_context, inst_id, inst);
  1545. }
  1546. auto TryEvalBlockForSpecific(Context& context, SemIR::SpecificId specific_id,
  1547. SemIR::GenericInstIndex::Region region)
  1548. -> SemIR::InstBlockId {
  1549. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1550. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1551. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1552. llvm::SmallVector<SemIR::InstId> result;
  1553. result.resize(eval_block.size(), SemIR::InstId::Invalid);
  1554. EvalContext eval_context(context, specific_id,
  1555. SpecificEvalInfo{
  1556. .region = region,
  1557. .values = result,
  1558. });
  1559. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1560. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1561. context.insts().Get(inst_id));
  1562. result[i] = context.constant_values().GetInstId(const_id);
  1563. // TODO: If this becomes possible through monomorphization failure, produce
  1564. // a diagnostic and put `SemIR::InstId::BuiltinErrorInst` in the table
  1565. // entry.
  1566. CARBON_CHECK(result[i].is_valid());
  1567. }
  1568. return context.inst_blocks().Add(result);
  1569. }
  1570. } // namespace Carbon::Check