eval.cpp 99 KB

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