eval.cpp 78 KB

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