eval.cpp 89 KB

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