eval.cpp 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334
  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 GetCompileTimeBindValue(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& interface : orig.extend_constraints) {
  565. info.extend_constraints.push_back(
  566. {.interface_id = interface.interface_id,
  567. .specific_id =
  568. GetConstantValue(eval_context, interface.specific_id, phase)});
  569. }
  570. info.self_impls_constraints.reserve(orig.self_impls_constraints.size());
  571. for (const auto& interface : orig.self_impls_constraints) {
  572. info.self_impls_constraints.push_back(
  573. {.interface_id = interface.interface_id,
  574. .specific_id =
  575. GetConstantValue(eval_context, interface.specific_id, phase)});
  576. }
  577. // Rewrite constraints are resolved first before replacing them with their
  578. // canonical instruction, so that in a `WhereExpr` we can work with the
  579. // `ImplWitnessAccess` references to `.Self` on the LHS of the constraints
  580. // rather than the value of the associated constant they reference.
  581. //
  582. // This also implies that we may find `ImplWitnessAccessSubstituted`
  583. // instructions in the LHS and RHS of these constraints, which are preserved
  584. // to maintain them as an unresolved reference to an associated constant, but
  585. // which must be handled gracefully during resolution. They will be replaced
  586. // with the constant value of the `ImplWitnessAccess` below when they are
  587. // substituted with a constant value.
  588. info.rewrite_constraints = orig.rewrite_constraints;
  589. if (!ResolveFacetTypeRewriteConstraints(eval_context.context(), loc_id,
  590. info.rewrite_constraints)) {
  591. *phase = Phase::UnknownDueToError;
  592. }
  593. for (auto& rewrite : info.rewrite_constraints) {
  594. // `where` requirements using `.Self` should not be considered symbolic.
  595. auto lhs_id = RequireConstantValueIgnoringPeriodSelf(eval_context,
  596. rewrite.lhs_id, phase);
  597. auto rhs_id = RequireConstantValueIgnoringPeriodSelf(eval_context,
  598. rewrite.rhs_id, phase);
  599. rewrite = {.lhs_id = lhs_id, .rhs_id = rhs_id};
  600. }
  601. info.Canonicalize();
  602. return info;
  603. }
  604. static auto GetConstantValue(EvalContext& eval_context,
  605. SemIR::FacetTypeId facet_type_id, Phase* phase)
  606. -> SemIR::FacetTypeId {
  607. SemIR::FacetTypeInfo info = GetConstantFacetTypeInfo(
  608. eval_context, SemIR::LocId::None,
  609. eval_context.facet_types().Get(facet_type_id), phase);
  610. // TODO: Return `facet_type_id` if we can detect nothing has changed.
  611. return eval_context.facet_types().Add(info);
  612. }
  613. static auto GetConstantValue(EvalContext& eval_context,
  614. SemIR::EntityNameId entity_name_id, Phase* phase)
  615. -> SemIR::EntityNameId {
  616. const auto& bind_name = eval_context.entity_names().Get(entity_name_id);
  617. Phase name_phase;
  618. if (bind_name.name_id == SemIR::NameId::PeriodSelf) {
  619. name_phase = Phase::PeriodSelfSymbolic;
  620. } else if (!bind_name.bind_index().has_value()) {
  621. name_phase = Phase::Concrete;
  622. } else if (bind_name.is_template) {
  623. name_phase = Phase::TemplateSymbolic;
  624. } else {
  625. name_phase = Phase::CheckedSymbolic;
  626. }
  627. *phase = LatestPhase(*phase, name_phase);
  628. return eval_context.entity_names().MakeCanonical(entity_name_id);
  629. }
  630. // Replaces the specified field of the given typed instruction with its constant
  631. // value, if it has constant phase. Returns true on success, false if the value
  632. // has runtime phase.
  633. template <typename InstT, typename FieldIdT>
  634. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  635. InstT* inst, FieldIdT InstT::* field,
  636. Phase* phase) -> bool {
  637. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  638. if (!unwrapped.has_value() && (inst->*field).has_value()) {
  639. return false;
  640. }
  641. inst->*field = unwrapped;
  642. return IsConstantOrError(*phase);
  643. }
  644. // Function template that can be called with an argument of type `T`. Used below
  645. // to detect which overloads of `GetConstantValue` exist.
  646. template <typename T>
  647. static void Accept(T /*arg*/) {}
  648. // Determines whether a `GetConstantValue` overload exists for a given ID type.
  649. // Note that we do not check whether `GetConstantValue` is *callable* with a
  650. // given ID type, because that would use the `InstId` overload for
  651. // `AbsoluteInstId` and similar wrapper types, which should be left alone.
  652. template <typename IdT>
  653. static constexpr bool HasGetConstantValueOverload = requires {
  654. Accept<auto (*)(EvalContext&, IdT, Phase*)->IdT>(GetConstantValue);
  655. };
  656. using ArgHandlerFnT = auto(EvalContext& context, int32_t arg, Phase* phase)
  657. -> int32_t;
  658. // Returns the arg handler for an `IdKind`.
  659. template <typename... Types>
  660. static auto GetArgHandlerFn(TypeEnum<Types...> id_kind) -> ArgHandlerFnT* {
  661. static constexpr std::array<ArgHandlerFnT*, SemIR::IdKind::NumValues> Table =
  662. {
  663. [](EvalContext& eval_context, int32_t arg, Phase* phase) -> int32_t {
  664. auto id = SemIR::Inst::FromRaw<Types>(arg);
  665. if constexpr (HasGetConstantValueOverload<Types>) {
  666. // If we have a custom `GetConstantValue` overload, call it.
  667. return SemIR::Inst::ToRaw(
  668. GetConstantValue(eval_context, id, phase));
  669. } else {
  670. // Otherwise, we assume the value is already constant.
  671. return arg;
  672. }
  673. }...,
  674. // Invalid and None handling (ordering-sensitive).
  675. [](auto...) -> int32_t { CARBON_FATAL("Unexpected invalid IdKind"); },
  676. [](EvalContext& /*context*/, int32_t arg,
  677. Phase* /*phase*/) -> int32_t { return arg; },
  678. };
  679. return Table[id_kind.ToIndex()];
  680. }
  681. // Given the stored value `arg` of an instruction field and its corresponding
  682. // kind `kind`, returns the constant value to use for that field, if it has a
  683. // constant phase. `*phase` is updated to include the new constant value. If
  684. // the resulting phase is not constant, the returned value is not useful and
  685. // will typically be `NoneIndex`.
  686. static auto GetConstantValueForArg(EvalContext& eval_context,
  687. SemIR::Inst::ArgAndKind arg_and_kind,
  688. Phase* phase) -> int32_t {
  689. return GetArgHandlerFn(arg_and_kind.kind())(eval_context,
  690. arg_and_kind.value(), phase);
  691. }
  692. // Given an instruction, replaces its operands with their constant values from
  693. // the specified evaluation context. `*phase` is updated to describe the
  694. // constant phase of the result. Returns whether `*phase` is a constant phase;
  695. // if not, `inst` may not be fully updated and should not be used.
  696. static auto ReplaceAllFieldsWithConstantValues(EvalContext& eval_context,
  697. SemIR::Inst* inst, Phase* phase)
  698. -> bool {
  699. auto arg0 =
  700. GetConstantValueForArg(eval_context, inst->arg0_and_kind(), phase);
  701. if (!IsConstantOrError(*phase)) {
  702. return false;
  703. }
  704. auto arg1 =
  705. GetConstantValueForArg(eval_context, inst->arg1_and_kind(), phase);
  706. if (!IsConstantOrError(*phase)) {
  707. return false;
  708. }
  709. inst->SetArgs(arg0, arg1);
  710. return true;
  711. }
  712. // Given an instruction and its ID, replaces its type with the corresponding
  713. // value in this evaluation context. Updates `*phase` to describe the phase of
  714. // the result, and returns whether `*phase` is a constant phase.
  715. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  716. SemIR::InstId inst_id,
  717. SemIR::Inst* inst, Phase* phase)
  718. -> bool {
  719. inst->SetType(GetTypeOfInst(eval_context, inst_id, *inst, phase));
  720. return IsConstantOrError(*phase);
  721. }
  722. template <typename InstT>
  723. static auto ReplaceTypeWithConstantValue(EvalContext& eval_context,
  724. SemIR::InstId inst_id, InstT* inst,
  725. Phase* phase) -> bool {
  726. inst->type_id = GetTypeOfInst(eval_context, inst_id, *inst, phase);
  727. return IsConstantOrError(*phase);
  728. }
  729. template <typename... Types>
  730. static auto KindHasGetConstantValueOverload(TypeEnum<Types...> e) -> bool {
  731. static constexpr std::array<bool, SemIR::IdKind::NumTypes> Values = {
  732. (HasGetConstantValueOverload<Types>)...};
  733. return Values[e.ToIndex()];
  734. }
  735. static auto ResolveSpecificDeclForSpecificId(EvalContext& eval_context,
  736. SemIR::SpecificId specific_id)
  737. -> void {
  738. if (!specific_id.has_value()) {
  739. return;
  740. }
  741. const auto& specific = eval_context.specifics().Get(specific_id);
  742. const auto& generic = eval_context.generics().Get(specific.generic_id);
  743. if (specific_id == generic.self_specific_id) {
  744. // Impl witness table construction happens before its generic decl is
  745. // finish, in order to make the table's instructions dependent
  746. // instructions of the Impl's generic. But those instructions can refer to
  747. // the generic's self specific. We can not resolve the specific
  748. // declaration for the self specific until the generic is finished, but it
  749. // is explicitly resolved at that time in `FinishGenericDecl()`.
  750. return;
  751. }
  752. ResolveSpecificDecl(eval_context.context(), eval_context.fallback_loc_id(),
  753. specific_id);
  754. }
  755. // Resolves the specific declarations for a specific id in any field of the
  756. // `inst` instruction.
  757. static auto ResolveSpecificDeclForInst(EvalContext& eval_context,
  758. const SemIR::Inst& inst) -> void {
  759. for (auto arg_and_kind : {inst.arg0_and_kind(), inst.arg1_and_kind()}) {
  760. // This switch must handle any field type that has a GetConstantValue()
  761. // overload which canonicalizes a specific (and thus potentially forms a new
  762. // specific) as part of forming its constant value.
  763. CARBON_KIND_SWITCH(arg_and_kind) {
  764. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  765. const auto& info =
  766. eval_context.context().facet_types().Get(facet_type_id);
  767. for (const auto& interface : info.extend_constraints) {
  768. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  769. }
  770. for (const auto& interface : info.self_impls_constraints) {
  771. ResolveSpecificDeclForSpecificId(eval_context, interface.specific_id);
  772. }
  773. break;
  774. }
  775. case CARBON_KIND(SemIR::SpecificId specific_id): {
  776. ResolveSpecificDeclForSpecificId(eval_context, specific_id);
  777. break;
  778. }
  779. case CARBON_KIND(SemIR::SpecificInterfaceId specific_interface_id): {
  780. ResolveSpecificDeclForSpecificId(eval_context,
  781. eval_context.specific_interfaces()
  782. .Get(specific_interface_id)
  783. .specific_id);
  784. break;
  785. }
  786. // These id types have a GetConstantValue() overload but that overload
  787. // does not canonicalize any SpecificId in the value type.
  788. case SemIR::IdKind::For<SemIR::DestInstId>:
  789. case SemIR::IdKind::For<SemIR::EntityNameId>:
  790. case SemIR::IdKind::For<SemIR::InstBlockId>:
  791. case SemIR::IdKind::For<SemIR::InstId>:
  792. case SemIR::IdKind::For<SemIR::MetaInstId>:
  793. case SemIR::IdKind::For<SemIR::StructTypeFieldsId>:
  794. case SemIR::IdKind::For<SemIR::TypeInstId>:
  795. break;
  796. case SemIR::IdKind::None:
  797. // No arg.
  798. break;
  799. default:
  800. CARBON_CHECK(
  801. !KindHasGetConstantValueOverload(arg_and_kind.kind()),
  802. "Missing case for {0} which has a GetConstantValue() overload",
  803. arg_and_kind.kind());
  804. break;
  805. }
  806. }
  807. }
  808. auto AddImportedConstant(Context& context, SemIR::Inst inst)
  809. -> SemIR::ConstantId {
  810. EvalContext eval_context(&context, SemIR::LocId::None);
  811. CARBON_CHECK(inst.kind().has_type(), "Can't import untyped instructions: {0}",
  812. inst.kind());
  813. Phase phase = GetPhase(context.constant_values(),
  814. context.types().GetConstantId(inst.type_id()));
  815. // We ignore the return value of ReplaceAllFieldsWithConstantValues and just
  816. // propagate runtime and error constant values into the resulting ConstantId.
  817. ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase);
  818. return MakeConstantResult(context, inst, phase);
  819. }
  820. // Performs an index into a homogeneous aggregate, retrieving the specified
  821. // element.
  822. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  823. -> SemIR::ConstantId {
  824. Phase phase = Phase::Concrete;
  825. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  826. if (!index_id.has_value()) {
  827. return MakeNonConstantResult(phase);
  828. }
  829. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  830. if (!index) {
  831. CARBON_CHECK(phase != Phase::Concrete,
  832. "Concrete constant integer should be a literal");
  833. return MakeNonConstantResult(phase);
  834. }
  835. // Array indexing is invalid if the index is constant and out of range,
  836. // regardless of whether the array itself is constant.
  837. const auto& index_val = eval_context.ints().Get(index->int_id);
  838. auto aggregate_type_id = eval_context.GetTypeOfInst(inst.array_id);
  839. if (auto array_type =
  840. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  841. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  842. array_type->bound_id)) {
  843. // This awkward call to `getZExtValue` is a workaround for APInt not
  844. // supporting comparisons between integers of different bit widths.
  845. if (index_val.getActiveBits() > 64 ||
  846. eval_context.ints()
  847. .Get(bound->int_id)
  848. .ule(index_val.getZExtValue())) {
  849. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  850. "array index `{0}` is past the end of type {1}",
  851. TypedInt, SemIR::TypeId);
  852. eval_context.emitter().Emit(
  853. eval_context.GetDiagnosticLoc(inst.index_id), ArrayIndexOutOfBounds,
  854. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  855. return SemIR::ErrorInst::ConstantId;
  856. }
  857. }
  858. }
  859. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  860. if (!aggregate_id.has_value()) {
  861. return MakeNonConstantResult(phase);
  862. }
  863. auto aggregate =
  864. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  865. if (!aggregate) {
  866. // TODO: Consider forming a symbolic constant or reference constant array
  867. // index in this case.
  868. return MakeNonConstantResult(phase);
  869. }
  870. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  871. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  872. }
  873. // Performs a conversion between character types, diagnosing if the value
  874. // doesn't fit in the destination type.
  875. static auto PerformCheckedCharConvert(Context& context, SemIR::LocId loc_id,
  876. SemIR::InstId arg_id,
  877. SemIR::TypeId dest_type_id)
  878. -> SemIR::ConstantId {
  879. auto arg = context.insts().GetAs<SemIR::CharLiteralValue>(arg_id);
  880. // Values over 0x80 require multiple code units in UTF-8.
  881. if (arg.value.index >= 0x80) {
  882. CARBON_DIAGNOSTIC(CharTooLargeForType, Error,
  883. "character value {0} too large for type {1}",
  884. SemIR::CharId, SemIR::TypeId);
  885. context.emitter().Emit(loc_id, CharTooLargeForType, arg.value,
  886. dest_type_id);
  887. return SemIR::ErrorInst::ConstantId;
  888. }
  889. llvm::APInt int_val(8, arg.value.index, /*isSigned=*/false);
  890. return MakeIntResult(context, dest_type_id, /*is_signed=*/false, int_val);
  891. }
  892. // Forms a constant int type as an evaluation result. Requires that width_id is
  893. // constant.
  894. static auto MakeIntTypeResult(Context& context, SemIR::LocId loc_id,
  895. SemIR::IntKind int_kind, SemIR::InstId width_id,
  896. Phase phase) -> SemIR::ConstantId {
  897. auto result = SemIR::IntType{
  898. .type_id = GetSingletonType(context, SemIR::TypeType::TypeInstId),
  899. .int_kind = int_kind,
  900. .bit_width_id = width_id};
  901. if (!ValidateIntType(context, loc_id, result)) {
  902. return SemIR::ErrorInst::ConstantId;
  903. }
  904. return MakeConstantResult(context, result, phase);
  905. }
  906. // Forms a constant float type as an evaluation result. Requires that width_id
  907. // is constant.
  908. static auto MakeFloatTypeResult(Context& context, SemIR::LocId loc_id,
  909. SemIR::InstId width_id, Phase phase)
  910. -> SemIR::ConstantId {
  911. auto result = SemIR::FloatType{
  912. .type_id = GetSingletonType(context, SemIR::TypeType::TypeInstId),
  913. .bit_width_id = width_id,
  914. .float_kind = SemIR::FloatKind::None};
  915. if (!ValidateFloatTypeAndSetKind(context, loc_id, result)) {
  916. return SemIR::ErrorInst::ConstantId;
  917. }
  918. return MakeConstantResult(context, result, phase);
  919. }
  920. // Performs a conversion between integer types, truncating if the value doesn't
  921. // fit in the destination type.
  922. static auto PerformIntConvert(Context& context, SemIR::InstId arg_id,
  923. SemIR::TypeId dest_type_id) -> SemIR::ConstantId {
  924. auto arg_val =
  925. context.ints().Get(context.insts().GetAs<SemIR::IntValue>(arg_id).int_id);
  926. auto [dest_is_signed, bit_width_id] =
  927. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  928. if (bit_width_id.has_value()) {
  929. // TODO: If the value fits in the destination type, reuse the existing
  930. // int_id rather than recomputing it. This is probably the most common case.
  931. bool src_is_signed = context.sem_ir().types().IsSignedInt(
  932. context.insts().Get(arg_id).type_id());
  933. unsigned width = context.ints().Get(bit_width_id).getZExtValue();
  934. arg_val =
  935. src_is_signed ? arg_val.sextOrTrunc(width) : arg_val.zextOrTrunc(width);
  936. }
  937. return MakeIntResult(context, dest_type_id, dest_is_signed, arg_val);
  938. }
  939. // Performs a conversion between integer types, diagnosing if the value doesn't
  940. // fit in the destination type.
  941. static auto PerformCheckedIntConvert(Context& context, SemIR::LocId loc_id,
  942. SemIR::InstId arg_id,
  943. SemIR::TypeId dest_type_id)
  944. -> SemIR::ConstantId {
  945. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  946. auto arg_val = context.ints().Get(arg.int_id);
  947. auto [is_signed, bit_width_id] =
  948. context.sem_ir().types().GetIntTypeInfo(dest_type_id);
  949. auto width = bit_width_id.has_value()
  950. ? context.ints().Get(bit_width_id).getZExtValue()
  951. : arg_val.getBitWidth();
  952. if (!is_signed && arg_val.isNegative()) {
  953. CARBON_DIAGNOSTIC(
  954. NegativeIntInUnsignedType, Error,
  955. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  956. SemIR::TypeId);
  957. context.emitter().Emit(loc_id, NegativeIntInUnsignedType,
  958. {.type = arg.type_id, .value = arg_val},
  959. dest_type_id);
  960. }
  961. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  962. if (arg_non_sign_bits + is_signed > width) {
  963. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  964. "integer value {0} too large for type {1}", TypedInt,
  965. SemIR::TypeId);
  966. context.emitter().Emit(loc_id, IntTooLargeForType,
  967. {.type = arg.type_id, .value = arg_val},
  968. dest_type_id);
  969. }
  970. return MakeConstantResult(
  971. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  972. Phase::Concrete);
  973. }
  974. // Performs a conversion between floating-point types, diagnosing if the value
  975. // doesn't fit in the destination type.
  976. static auto PerformCheckedFloatConvert(Context& context, SemIR::LocId loc_id,
  977. SemIR::InstId arg_id,
  978. SemIR::TypeId dest_type_id)
  979. -> SemIR::ConstantId {
  980. auto dest_type_object_rep_id = context.types().GetObjectRepr(dest_type_id);
  981. CARBON_CHECK(dest_type_object_rep_id.has_value(),
  982. "Conversion to incomplete type");
  983. auto dest_float_type =
  984. context.types().TryGetAs<SemIR::FloatType>(dest_type_object_rep_id);
  985. CARBON_CHECK(dest_float_type || context.types().Is<SemIR::FloatLiteralType>(
  986. dest_type_object_rep_id));
  987. if (auto literal =
  988. context.insts().TryGetAs<SemIR::FloatLiteralValue>(arg_id)) {
  989. if (!dest_float_type) {
  990. return MakeConstantResult(
  991. context,
  992. SemIR::FloatLiteralValue{.type_id = dest_type_id,
  993. .real_id = literal->real_id},
  994. Phase::Concrete);
  995. }
  996. // Convert the real literal to an llvm::APFloat and add it to the floats
  997. // ValueStore. In the future this would use an arbitrary precision Rational
  998. // type.
  999. //
  1000. // TODO: Implement Carbon's actual implicit conversion rules for
  1001. // floating-point constants, as per the design
  1002. // docs/design/expressions/implicit_conversions.md
  1003. auto real_value = context.sem_ir().reals().Get(literal->real_id);
  1004. // Convert the real value to a string.
  1005. llvm::SmallString<64> str;
  1006. real_value.mantissa.toString(str, real_value.is_decimal ? 10 : 16,
  1007. /*signed=*/false, /*formatAsCLiteral=*/true);
  1008. str += real_value.is_decimal ? "e" : "p";
  1009. real_value.exponent.toStringSigned(str);
  1010. // Convert the string to an APFloat.
  1011. llvm::APFloat result(dest_float_type->float_kind.Semantics());
  1012. // TODO: The implementation of this conversion effectively converts back to
  1013. // APInts, but unfortunately the conversion from integer mantissa and
  1014. // exponent in IEEEFloat::roundSignificandWithExponent is not part of the
  1015. // public API.
  1016. auto status =
  1017. result.convertFromString(str, llvm::APFloat::rmNearestTiesToEven);
  1018. if (auto error = status.takeError()) {
  1019. // The literal we create should always successfully parse.
  1020. CARBON_FATAL("Float literal parsing failed: {0}",
  1021. toString(std::move(error)));
  1022. }
  1023. if (status.get() & llvm::APFloat::opOverflow) {
  1024. CARBON_DIAGNOSTIC(FloatLiteralTooLargeForType, Error,
  1025. "value {0} too large for floating-point type {1}",
  1026. RealId, SemIR::TypeId);
  1027. context.emitter().Emit(loc_id, FloatLiteralTooLargeForType,
  1028. literal->real_id, dest_type_id);
  1029. return SemIR::ErrorInst::ConstantId;
  1030. }
  1031. return MakeFloatResult(context, dest_type_id, std::move(result));
  1032. }
  1033. if (!dest_float_type) {
  1034. context.TODO(loc_id, "conversion from float to float literal");
  1035. return SemIR::ErrorInst::ConstantId;
  1036. }
  1037. // Convert to the destination float semantics.
  1038. auto arg = context.insts().GetAs<SemIR::FloatValue>(arg_id);
  1039. llvm::APFloat result = context.floats().Get(arg.float_id);
  1040. bool loses_info;
  1041. auto status = result.convert(dest_float_type->float_kind.Semantics(),
  1042. llvm::APFloat::rmNearestTiesToEven, &loses_info);
  1043. if (status & llvm::APFloat::opOverflow) {
  1044. CARBON_DIAGNOSTIC(FloatTooLargeForType, Error,
  1045. "value {0} too large for floating-point type {1}",
  1046. llvm::APFloat, SemIR::TypeId);
  1047. context.emitter().Emit(loc_id, FloatTooLargeForType,
  1048. context.floats().Get(arg.float_id), dest_type_id);
  1049. return SemIR::ErrorInst::ConstantId;
  1050. }
  1051. return MakeFloatResult(context, dest_type_id, std::move(result));
  1052. }
  1053. // Issues a diagnostic for a compile-time division by zero.
  1054. static auto DiagnoseDivisionByZero(Context& context, SemIR::LocId loc_id)
  1055. -> void {
  1056. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  1057. context.emitter().Emit(loc_id, CompileTimeDivisionByZero);
  1058. }
  1059. // Get an integer at a suitable bit-width: either `bit_width_id` if it has a
  1060. // value, or the canonical width from the value store if not.
  1061. static auto GetIntAtSuitableWidth(Context& context, IntId int_id,
  1062. IntId bit_width_id) -> llvm::APInt {
  1063. return bit_width_id.has_value()
  1064. ? context.ints().GetAtWidth(int_id, bit_width_id)
  1065. : context.ints().Get(int_id);
  1066. }
  1067. // Performs a builtin unary integer -> integer operation.
  1068. static auto PerformBuiltinUnaryIntOp(Context& context, SemIR::LocId loc_id,
  1069. SemIR::BuiltinFunctionKind builtin_kind,
  1070. SemIR::InstId arg_id)
  1071. -> SemIR::ConstantId {
  1072. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  1073. auto [is_signed, bit_width_id] =
  1074. context.sem_ir().types().GetIntTypeInfo(op.type_id);
  1075. llvm::APInt op_val = GetIntAtSuitableWidth(context, op.int_id, bit_width_id);
  1076. switch (builtin_kind) {
  1077. case SemIR::BuiltinFunctionKind::IntSNegate:
  1078. if (op_val.isMinSignedValue()) {
  1079. if (bit_width_id.has_value()) {
  1080. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  1081. "integer overflow in negation of {0}", TypedInt);
  1082. context.emitter().Emit(loc_id, CompileTimeIntegerNegateOverflow,
  1083. {.type = op.type_id, .value = op_val});
  1084. } else {
  1085. // Widen the integer so we don't overflow into the sign bit.
  1086. op_val = op_val.sext(op_val.getBitWidth() +
  1087. llvm::APInt::APINT_BITS_PER_WORD);
  1088. }
  1089. }
  1090. op_val.negate();
  1091. break;
  1092. case SemIR::BuiltinFunctionKind::IntUNegate:
  1093. CARBON_CHECK(bit_width_id.has_value(), "Unsigned negate on unsized int");
  1094. op_val.negate();
  1095. break;
  1096. case SemIR::BuiltinFunctionKind::IntComplement:
  1097. // TODO: Should we have separate builtins for signed and unsigned
  1098. // complement? Like with signed/unsigned negate, these operations do
  1099. // different things to the integer value, even though they do the same
  1100. // thing to the bits. We treat IntLiteral complement as signed complement,
  1101. // given that the result of unsigned complement depends on the bit width.
  1102. op_val.flipAllBits();
  1103. break;
  1104. default:
  1105. CARBON_FATAL("Unexpected builtin kind");
  1106. }
  1107. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  1108. }
  1109. namespace {
  1110. // A pair of APInts that are the operands of a binary operator. We use an
  1111. // aggregate rather than `std::pair` to allow RVO of the individual ints.
  1112. struct APIntBinaryOperands {
  1113. llvm::APInt lhs;
  1114. llvm::APInt rhs;
  1115. };
  1116. } // namespace
  1117. // Get a pair of integers at the same suitable bit-width: either their actual
  1118. // width if they have a fixed width, or the smallest canonical width in which
  1119. // they both fit otherwise.
  1120. static auto GetIntsAtSuitableWidth(Context& context, IntId lhs_id, IntId rhs_id,
  1121. IntId bit_width_id) -> APIntBinaryOperands {
  1122. // Unsized operands: take the wider of the bit widths.
  1123. if (!bit_width_id.has_value()) {
  1124. APIntBinaryOperands result = {.lhs = context.ints().Get(lhs_id),
  1125. .rhs = context.ints().Get(rhs_id)};
  1126. if (result.lhs.getBitWidth() != result.rhs.getBitWidth()) {
  1127. if (result.lhs.getBitWidth() > result.rhs.getBitWidth()) {
  1128. result.rhs = result.rhs.sext(result.lhs.getBitWidth());
  1129. } else {
  1130. result.lhs = result.lhs.sext(result.rhs.getBitWidth());
  1131. }
  1132. }
  1133. return result;
  1134. }
  1135. return {.lhs = context.ints().GetAtWidth(lhs_id, bit_width_id),
  1136. .rhs = context.ints().GetAtWidth(rhs_id, bit_width_id)};
  1137. }
  1138. namespace {
  1139. // The result of performing a binary int operation.
  1140. struct BinaryIntOpResult {
  1141. llvm::APInt result_val;
  1142. bool overflow;
  1143. Lex::TokenKind op_token;
  1144. };
  1145. } // namespace
  1146. // Computes the result of a homogeneous binary (int, int) -> int operation.
  1147. static auto ComputeBinaryIntOpResult(SemIR::BuiltinFunctionKind builtin_kind,
  1148. const llvm::APInt& lhs_val,
  1149. const llvm::APInt& rhs_val)
  1150. -> BinaryIntOpResult {
  1151. llvm::APInt result_val;
  1152. bool overflow = false;
  1153. Lex::TokenKind op_token = Lex::TokenKind::Not;
  1154. switch (builtin_kind) {
  1155. // Arithmetic.
  1156. case SemIR::BuiltinFunctionKind::IntSAdd:
  1157. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  1158. op_token = Lex::TokenKind::Plus;
  1159. break;
  1160. case SemIR::BuiltinFunctionKind::IntSSub:
  1161. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  1162. op_token = Lex::TokenKind::Minus;
  1163. break;
  1164. case SemIR::BuiltinFunctionKind::IntSMul:
  1165. result_val = lhs_val.smul_ov(rhs_val, overflow);
  1166. op_token = Lex::TokenKind::Star;
  1167. break;
  1168. case SemIR::BuiltinFunctionKind::IntSDiv:
  1169. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  1170. op_token = Lex::TokenKind::Slash;
  1171. break;
  1172. case SemIR::BuiltinFunctionKind::IntSMod:
  1173. result_val = lhs_val.srem(rhs_val);
  1174. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  1175. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  1176. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  1177. op_token = Lex::TokenKind::Percent;
  1178. break;
  1179. case SemIR::BuiltinFunctionKind::IntUAdd:
  1180. result_val = lhs_val + rhs_val;
  1181. op_token = Lex::TokenKind::Plus;
  1182. break;
  1183. case SemIR::BuiltinFunctionKind::IntUSub:
  1184. result_val = lhs_val - rhs_val;
  1185. op_token = Lex::TokenKind::Minus;
  1186. break;
  1187. case SemIR::BuiltinFunctionKind::IntUMul:
  1188. result_val = lhs_val * rhs_val;
  1189. op_token = Lex::TokenKind::Star;
  1190. break;
  1191. case SemIR::BuiltinFunctionKind::IntUDiv:
  1192. result_val = lhs_val.udiv(rhs_val);
  1193. op_token = Lex::TokenKind::Slash;
  1194. break;
  1195. case SemIR::BuiltinFunctionKind::IntUMod:
  1196. result_val = lhs_val.urem(rhs_val);
  1197. op_token = Lex::TokenKind::Percent;
  1198. break;
  1199. // Bitwise.
  1200. case SemIR::BuiltinFunctionKind::IntAnd:
  1201. result_val = lhs_val & rhs_val;
  1202. op_token = Lex::TokenKind::And;
  1203. break;
  1204. case SemIR::BuiltinFunctionKind::IntOr:
  1205. result_val = lhs_val | rhs_val;
  1206. op_token = Lex::TokenKind::Pipe;
  1207. break;
  1208. case SemIR::BuiltinFunctionKind::IntXor:
  1209. result_val = lhs_val ^ rhs_val;
  1210. op_token = Lex::TokenKind::Caret;
  1211. break;
  1212. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1213. case SemIR::BuiltinFunctionKind::IntRightShift:
  1214. CARBON_FATAL("Non-homogeneous operation handled separately.");
  1215. default:
  1216. CARBON_FATAL("Unexpected operation kind.");
  1217. }
  1218. return {.result_val = std::move(result_val),
  1219. .overflow = overflow,
  1220. .op_token = op_token};
  1221. }
  1222. // Performs a builtin integer bit shift operation.
  1223. static auto PerformBuiltinIntShiftOp(Context& context, SemIR::LocId loc_id,
  1224. SemIR::BuiltinFunctionKind builtin_kind,
  1225. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  1226. -> SemIR::ConstantId {
  1227. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1228. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1229. auto [lhs_is_signed, lhs_bit_width_id] =
  1230. context.sem_ir().types().GetIntTypeInfo(lhs.type_id);
  1231. llvm::APInt lhs_val =
  1232. GetIntAtSuitableWidth(context, lhs.int_id, lhs_bit_width_id);
  1233. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  1234. if (lhs_bit_width_id.has_value() && rhs_orig_val.uge(lhs_val.getBitWidth())) {
  1235. CARBON_DIAGNOSTIC(
  1236. CompileTimeShiftOutOfRange, Error,
  1237. "shift distance >= type width of {0} in `{1} {2:<<|>>} {3}`", unsigned,
  1238. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1239. context.emitter().Emit(
  1240. loc_id, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  1241. {.type = lhs.type_id, .value = lhs_val},
  1242. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1243. {.type = rhs.type_id, .value = rhs_orig_val});
  1244. // TODO: Is it useful to recover by returning 0 or -1?
  1245. return SemIR::ErrorInst::ConstantId;
  1246. }
  1247. if (rhs_orig_val.isNegative() &&
  1248. context.sem_ir().types().IsSignedInt(rhs.type_id)) {
  1249. CARBON_DIAGNOSTIC(CompileTimeShiftNegative, Error,
  1250. "shift distance negative in `{0} {1:<<|>>} {2}`",
  1251. TypedInt, Diagnostics::BoolAsSelect, TypedInt);
  1252. context.emitter().Emit(
  1253. loc_id, CompileTimeShiftNegative,
  1254. {.type = lhs.type_id, .value = lhs_val},
  1255. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  1256. {.type = rhs.type_id, .value = rhs_orig_val});
  1257. // TODO: Is it useful to recover by returning 0 or -1?
  1258. return SemIR::ErrorInst::ConstantId;
  1259. }
  1260. llvm::APInt result_val;
  1261. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  1262. if (!lhs_bit_width_id.has_value() && !lhs_val.isZero()) {
  1263. // Ensure we don't generate a ridiculously large integer through a bit
  1264. // shift.
  1265. auto width = rhs_orig_val.trySExtValue();
  1266. if (!width ||
  1267. *width > IntStore::MaxIntWidth - lhs_val.getSignificantBits()) {
  1268. CARBON_DIAGNOSTIC(CompileTimeUnsizedShiftOutOfRange, Error,
  1269. "shift distance of {0} would result in an "
  1270. "integer whose width is greater than the "
  1271. "maximum supported width of {1}",
  1272. TypedInt, int);
  1273. context.emitter().Emit(loc_id, CompileTimeUnsizedShiftOutOfRange,
  1274. {.type = rhs.type_id, .value = rhs_orig_val},
  1275. IntStore::MaxIntWidth);
  1276. return SemIR::ErrorInst::ConstantId;
  1277. }
  1278. lhs_val = lhs_val.sext(
  1279. IntStore::CanonicalBitWidth(lhs_val.getSignificantBits() + *width));
  1280. }
  1281. result_val =
  1282. lhs_val.shl(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1283. } else if (lhs_is_signed) {
  1284. result_val =
  1285. lhs_val.ashr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1286. } else {
  1287. CARBON_CHECK(lhs_bit_width_id.has_value(), "Logical shift on unsized int");
  1288. result_val =
  1289. lhs_val.lshr(rhs_orig_val.getLimitedValue(lhs_val.getBitWidth()));
  1290. }
  1291. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  1292. std::move(result_val));
  1293. }
  1294. // Performs a homogeneous builtin binary integer -> integer operation.
  1295. static auto PerformBuiltinBinaryIntOp(Context& context, SemIR::LocId loc_id,
  1296. SemIR::BuiltinFunctionKind builtin_kind,
  1297. SemIR::InstId lhs_id,
  1298. SemIR::InstId rhs_id)
  1299. -> SemIR::ConstantId {
  1300. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1301. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1302. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  1303. auto type_id = lhs.type_id;
  1304. auto [is_signed, bit_width_id] =
  1305. context.sem_ir().types().GetIntTypeInfo(type_id);
  1306. auto [lhs_val, rhs_val] =
  1307. GetIntsAtSuitableWidth(context, lhs.int_id, rhs.int_id, bit_width_id);
  1308. // Check for division by zero.
  1309. switch (builtin_kind) {
  1310. case SemIR::BuiltinFunctionKind::IntSDiv:
  1311. case SemIR::BuiltinFunctionKind::IntSMod:
  1312. case SemIR::BuiltinFunctionKind::IntUDiv:
  1313. case SemIR::BuiltinFunctionKind::IntUMod:
  1314. if (rhs_val.isZero()) {
  1315. DiagnoseDivisionByZero(context, loc_id);
  1316. return SemIR::ErrorInst::ConstantId;
  1317. }
  1318. break;
  1319. default:
  1320. break;
  1321. }
  1322. BinaryIntOpResult result =
  1323. ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1324. if (result.overflow && !bit_width_id.has_value()) {
  1325. // Retry with a larger bit width. Most operations can only overflow by one
  1326. // bit, but signed n-bit multiplication can overflow to 2n-1 bits. We don't
  1327. // need to handle unsigned multiplication here because it's not permitted
  1328. // for unsized integers.
  1329. //
  1330. // Note that we speculatively first perform the calculation in the width of
  1331. // the wider operand: smaller operations are faster and overflow to a wider
  1332. // integer is unlikely to be needed, especially given that the width will
  1333. // have been rounded up to a multiple of 64 bits by the int store.
  1334. CARBON_CHECK(builtin_kind != SemIR::BuiltinFunctionKind::IntUMul,
  1335. "Unsigned arithmetic requires a fixed bitwidth");
  1336. int new_width =
  1337. builtin_kind == SemIR::BuiltinFunctionKind::IntSMul
  1338. ? lhs_val.getBitWidth() * 2
  1339. : IntStore::CanonicalBitWidth(lhs_val.getBitWidth() + 1);
  1340. new_width = std::min(new_width, IntStore::MaxIntWidth);
  1341. lhs_val = context.ints().GetAtWidth(lhs.int_id, new_width);
  1342. rhs_val = context.ints().GetAtWidth(rhs.int_id, new_width);
  1343. // Note that this can in theory still overflow if we limited `new_width` to
  1344. // `MaxIntWidth`. In that case we fall through to the signed overflow
  1345. // diagnostic below.
  1346. result = ComputeBinaryIntOpResult(builtin_kind, lhs_val, rhs_val);
  1347. CARBON_CHECK(!result.overflow || new_width == IntStore::MaxIntWidth);
  1348. }
  1349. if (result.overflow) {
  1350. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  1351. "integer overflow in calculation `{0} {1} {2}`", TypedInt,
  1352. Lex::TokenKind, TypedInt);
  1353. context.emitter().Emit(loc_id, CompileTimeIntegerOverflow,
  1354. {.type = type_id, .value = lhs_val}, result.op_token,
  1355. {.type = type_id, .value = rhs_val});
  1356. }
  1357. return MakeIntResult(context, type_id, is_signed,
  1358. std::move(result.result_val));
  1359. }
  1360. // Performs a builtin integer comparison.
  1361. static auto PerformBuiltinIntComparison(Context& context,
  1362. SemIR::BuiltinFunctionKind builtin_kind,
  1363. SemIR::InstId lhs_id,
  1364. SemIR::InstId rhs_id,
  1365. SemIR::TypeId bool_type_id)
  1366. -> SemIR::ConstantId {
  1367. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  1368. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  1369. llvm::APInt lhs_val = context.ints().Get(lhs.int_id);
  1370. llvm::APInt rhs_val = context.ints().Get(rhs.int_id);
  1371. bool result;
  1372. switch (builtin_kind) {
  1373. case SemIR::BuiltinFunctionKind::IntEq:
  1374. result = (lhs_val == rhs_val);
  1375. break;
  1376. case SemIR::BuiltinFunctionKind::IntNeq:
  1377. result = (lhs_val != rhs_val);
  1378. break;
  1379. case SemIR::BuiltinFunctionKind::IntLess:
  1380. result = lhs_val.slt(rhs_val);
  1381. break;
  1382. case SemIR::BuiltinFunctionKind::IntLessEq:
  1383. result = lhs_val.sle(rhs_val);
  1384. break;
  1385. case SemIR::BuiltinFunctionKind::IntGreater:
  1386. result = lhs_val.sgt(rhs_val);
  1387. break;
  1388. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  1389. result = lhs_val.sge(rhs_val);
  1390. break;
  1391. default:
  1392. CARBON_FATAL("Unexpected operation kind.");
  1393. }
  1394. return MakeBoolResult(context, bool_type_id, result);
  1395. }
  1396. // Performs a builtin unary float -> float operation.
  1397. static auto PerformBuiltinUnaryFloatOp(Context& context,
  1398. SemIR::BuiltinFunctionKind builtin_kind,
  1399. SemIR::InstId arg_id)
  1400. -> SemIR::ConstantId {
  1401. auto op = context.insts().GetAs<SemIR::FloatValue>(arg_id);
  1402. auto op_val = context.floats().Get(op.float_id);
  1403. switch (builtin_kind) {
  1404. case SemIR::BuiltinFunctionKind::FloatNegate:
  1405. op_val.changeSign();
  1406. break;
  1407. default:
  1408. CARBON_FATAL("Unexpected builtin kind");
  1409. }
  1410. return MakeFloatResult(context, op.type_id, std::move(op_val));
  1411. }
  1412. // Performs a builtin binary float -> float operation.
  1413. static auto PerformBuiltinBinaryFloatOp(Context& context,
  1414. SemIR::BuiltinFunctionKind builtin_kind,
  1415. SemIR::InstId lhs_id,
  1416. SemIR::InstId rhs_id)
  1417. -> SemIR::ConstantId {
  1418. auto lhs = context.insts().GetAs<SemIR::FloatValue>(lhs_id);
  1419. auto rhs = context.insts().GetAs<SemIR::FloatValue>(rhs_id);
  1420. auto lhs_val = context.floats().Get(lhs.float_id);
  1421. auto rhs_val = context.floats().Get(rhs.float_id);
  1422. llvm::APFloat result_val(lhs_val.getSemantics());
  1423. switch (builtin_kind) {
  1424. case SemIR::BuiltinFunctionKind::FloatAdd:
  1425. result_val = lhs_val + rhs_val;
  1426. break;
  1427. case SemIR::BuiltinFunctionKind::FloatSub:
  1428. result_val = lhs_val - rhs_val;
  1429. break;
  1430. case SemIR::BuiltinFunctionKind::FloatMul:
  1431. result_val = lhs_val * rhs_val;
  1432. break;
  1433. case SemIR::BuiltinFunctionKind::FloatDiv:
  1434. result_val = lhs_val / rhs_val;
  1435. break;
  1436. default:
  1437. CARBON_FATAL("Unexpected operation kind.");
  1438. }
  1439. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  1440. }
  1441. // Performs a builtin float comparison.
  1442. static auto PerformBuiltinFloatComparison(
  1443. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1444. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  1445. -> SemIR::ConstantId {
  1446. auto lhs = context.insts().GetAs<SemIR::FloatValue>(lhs_id);
  1447. auto rhs = context.insts().GetAs<SemIR::FloatValue>(rhs_id);
  1448. const auto& lhs_val = context.floats().Get(lhs.float_id);
  1449. const auto& rhs_val = context.floats().Get(rhs.float_id);
  1450. bool result;
  1451. switch (builtin_kind) {
  1452. case SemIR::BuiltinFunctionKind::FloatEq:
  1453. result = (lhs_val == rhs_val);
  1454. break;
  1455. case SemIR::BuiltinFunctionKind::FloatNeq:
  1456. result = (lhs_val != rhs_val);
  1457. break;
  1458. case SemIR::BuiltinFunctionKind::FloatLess:
  1459. result = lhs_val < rhs_val;
  1460. break;
  1461. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1462. result = lhs_val <= rhs_val;
  1463. break;
  1464. case SemIR::BuiltinFunctionKind::FloatGreater:
  1465. result = lhs_val > rhs_val;
  1466. break;
  1467. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  1468. result = lhs_val >= rhs_val;
  1469. break;
  1470. default:
  1471. CARBON_FATAL("Unexpected operation kind.");
  1472. }
  1473. return MakeBoolResult(context, bool_type_id, result);
  1474. }
  1475. // Performs a builtin boolean comparison.
  1476. static auto PerformBuiltinBoolComparison(
  1477. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  1478. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id) {
  1479. bool lhs = context.insts().GetAs<SemIR::BoolLiteral>(lhs_id).value.ToBool();
  1480. bool rhs = context.insts().GetAs<SemIR::BoolLiteral>(rhs_id).value.ToBool();
  1481. return MakeBoolResult(context, bool_type_id,
  1482. builtin_kind == SemIR::BuiltinFunctionKind::BoolEq
  1483. ? lhs == rhs
  1484. : lhs != rhs);
  1485. }
  1486. // Returns a constant for a call to a builtin function.
  1487. static auto MakeConstantForBuiltinCall(EvalContext& eval_context,
  1488. SemIR::LocId loc_id, SemIR::Call call,
  1489. SemIR::BuiltinFunctionKind builtin_kind,
  1490. llvm::ArrayRef<SemIR::InstId> arg_ids,
  1491. Phase phase) -> SemIR::ConstantId {
  1492. auto& context = eval_context.context();
  1493. switch (builtin_kind) {
  1494. case SemIR::BuiltinFunctionKind::None:
  1495. CARBON_FATAL("Not a builtin function.");
  1496. case SemIR::BuiltinFunctionKind::NoOp:
  1497. case SemIR::BuiltinFunctionKind::TypeAggregateDestroy: {
  1498. // Return an empty tuple value.
  1499. auto type_id = GetTupleType(eval_context.context(), {});
  1500. return MakeConstantResult(
  1501. eval_context.context(),
  1502. SemIR::TupleValue{.type_id = type_id,
  1503. .elements_id = SemIR::InstBlockId::Empty},
  1504. phase);
  1505. }
  1506. case SemIR::BuiltinFunctionKind::TypeCanAggregateDestroy: {
  1507. CARBON_CHECK(arg_ids.empty());
  1508. auto id = eval_context.facet_types().Add(
  1509. {.builtin_constraint_mask =
  1510. SemIR::BuiltinConstraintMask::TypeCanAggregateDestroy});
  1511. return MakeConstantResult(
  1512. eval_context.context(),
  1513. SemIR::FacetType{.type_id = SemIR::TypeType::TypeId,
  1514. .facet_type_id = id},
  1515. phase);
  1516. }
  1517. case SemIR::BuiltinFunctionKind::PrimitiveCopy: {
  1518. return context.constant_values().Get(arg_ids[0]);
  1519. }
  1520. case SemIR::BuiltinFunctionKind::PrintChar:
  1521. case SemIR::BuiltinFunctionKind::PrintInt:
  1522. case SemIR::BuiltinFunctionKind::ReadChar:
  1523. case SemIR::BuiltinFunctionKind::FloatAddAssign:
  1524. case SemIR::BuiltinFunctionKind::FloatSubAssign:
  1525. case SemIR::BuiltinFunctionKind::FloatMulAssign:
  1526. case SemIR::BuiltinFunctionKind::FloatDivAssign:
  1527. case SemIR::BuiltinFunctionKind::IntSAddAssign:
  1528. case SemIR::BuiltinFunctionKind::IntSSubAssign:
  1529. case SemIR::BuiltinFunctionKind::IntSMulAssign:
  1530. case SemIR::BuiltinFunctionKind::IntSDivAssign:
  1531. case SemIR::BuiltinFunctionKind::IntSModAssign:
  1532. case SemIR::BuiltinFunctionKind::IntUAddAssign:
  1533. case SemIR::BuiltinFunctionKind::IntUSubAssign:
  1534. case SemIR::BuiltinFunctionKind::IntUMulAssign:
  1535. case SemIR::BuiltinFunctionKind::IntUDivAssign:
  1536. case SemIR::BuiltinFunctionKind::IntUModAssign:
  1537. case SemIR::BuiltinFunctionKind::IntAndAssign:
  1538. case SemIR::BuiltinFunctionKind::IntOrAssign:
  1539. case SemIR::BuiltinFunctionKind::IntXorAssign:
  1540. case SemIR::BuiltinFunctionKind::IntLeftShiftAssign:
  1541. case SemIR::BuiltinFunctionKind::IntRightShiftAssign: {
  1542. // These are runtime-only builtins.
  1543. // TODO: Consider tracking this on the `BuiltinFunctionKind`.
  1544. return SemIR::ConstantId::NotConstant;
  1545. }
  1546. case SemIR::BuiltinFunctionKind::TypeAnd: {
  1547. CARBON_CHECK(arg_ids.size() == 2);
  1548. auto lhs_facet_type_id = SemIR::FacetTypeId::None;
  1549. auto rhs_facet_type_id = SemIR::FacetTypeId::None;
  1550. for (auto [facet_type_id, type_arg_id] :
  1551. llvm::zip(std::to_array({&lhs_facet_type_id, &rhs_facet_type_id}),
  1552. context.types().GetBlockAsTypeInstIds(arg_ids))) {
  1553. if (auto facet_type =
  1554. context.insts().TryGetAs<SemIR::FacetType>(type_arg_id)) {
  1555. *facet_type_id = facet_type->facet_type_id;
  1556. } else {
  1557. CARBON_DIAGNOSTIC(FacetTypeRequiredForTypeAndOperator, Error,
  1558. "non-facet type {0} combined with `&` operator",
  1559. SemIR::TypeId);
  1560. // TODO: Find a location for the lhs or rhs specifically, instead of
  1561. // the whole thing. If that's not possible we can change the text to
  1562. // say if it's referring to the left or the right side for the error.
  1563. // The `arg_id` instruction has no location in it for some reason.
  1564. context.emitter().Emit(
  1565. loc_id, FacetTypeRequiredForTypeAndOperator,
  1566. context.types().GetTypeIdForTypeInstId(type_arg_id));
  1567. }
  1568. }
  1569. // Allow errors to be diagnosed for both sides of the operator before
  1570. // returning here if any error occurred on either side.
  1571. if (!lhs_facet_type_id.has_value() || !rhs_facet_type_id.has_value()) {
  1572. return SemIR::ErrorInst::ConstantId;
  1573. }
  1574. // Reuse one of the argument instructions if nothing has changed.
  1575. if (lhs_facet_type_id == rhs_facet_type_id) {
  1576. return context.types().GetConstantId(
  1577. context.types().GetTypeIdForTypeInstId(arg_ids[0]));
  1578. }
  1579. auto combined_info = SemIR::FacetTypeInfo::Combine(
  1580. context.facet_types().Get(lhs_facet_type_id),
  1581. context.facet_types().Get(rhs_facet_type_id));
  1582. if (!ResolveFacetTypeRewriteConstraints(
  1583. eval_context.context(), loc_id,
  1584. combined_info.rewrite_constraints)) {
  1585. phase = Phase::UnknownDueToError;
  1586. }
  1587. combined_info.Canonicalize();
  1588. return MakeFacetTypeResult(eval_context.context(), combined_info, phase);
  1589. }
  1590. case SemIR::BuiltinFunctionKind::CharLiteralMakeType: {
  1591. return context.constant_values().Get(SemIR::CharLiteralType::TypeInstId);
  1592. }
  1593. case SemIR::BuiltinFunctionKind::FloatLiteralMakeType: {
  1594. return context.constant_values().Get(SemIR::FloatLiteralType::TypeInstId);
  1595. }
  1596. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  1597. return context.constant_values().Get(SemIR::IntLiteralType::TypeInstId);
  1598. }
  1599. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  1600. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Signed,
  1601. arg_ids[0], phase);
  1602. }
  1603. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  1604. return MakeIntTypeResult(context, loc_id, SemIR::IntKind::Unsigned,
  1605. arg_ids[0], phase);
  1606. }
  1607. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  1608. return MakeFloatTypeResult(context, loc_id, arg_ids[0], phase);
  1609. }
  1610. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  1611. return context.constant_values().Get(SemIR::BoolType::TypeInstId);
  1612. }
  1613. case SemIR::BuiltinFunctionKind::MaybeUnformedMakeType: {
  1614. return MakeConstantResult(
  1615. context,
  1616. SemIR::MaybeUnformedType{
  1617. .type_id = SemIR::TypeType::TypeId,
  1618. .inner_id = context.types().GetAsTypeInstId(arg_ids[0])},
  1619. phase);
  1620. }
  1621. // Character conversions.
  1622. case SemIR::BuiltinFunctionKind::CharConvertChecked: {
  1623. if (phase != Phase::Concrete) {
  1624. return MakeConstantResult(context, call, phase);
  1625. }
  1626. return PerformCheckedCharConvert(context, loc_id, arg_ids[0],
  1627. call.type_id);
  1628. }
  1629. // Integer conversions.
  1630. case SemIR::BuiltinFunctionKind::IntConvert: {
  1631. if (phase != Phase::Concrete) {
  1632. return MakeConstantResult(context, call, phase);
  1633. }
  1634. return PerformIntConvert(context, arg_ids[0], call.type_id);
  1635. }
  1636. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  1637. if (phase != Phase::Concrete) {
  1638. return MakeConstantResult(context, call, phase);
  1639. }
  1640. return PerformCheckedIntConvert(context, loc_id, arg_ids[0],
  1641. call.type_id);
  1642. }
  1643. // Unary integer -> integer operations.
  1644. case SemIR::BuiltinFunctionKind::IntSNegate:
  1645. case SemIR::BuiltinFunctionKind::IntUNegate:
  1646. case SemIR::BuiltinFunctionKind::IntComplement: {
  1647. if (phase != Phase::Concrete) {
  1648. break;
  1649. }
  1650. return PerformBuiltinUnaryIntOp(context, loc_id, builtin_kind,
  1651. arg_ids[0]);
  1652. }
  1653. // Homogeneous binary integer -> integer operations.
  1654. case SemIR::BuiltinFunctionKind::IntSAdd:
  1655. case SemIR::BuiltinFunctionKind::IntSSub:
  1656. case SemIR::BuiltinFunctionKind::IntSMul:
  1657. case SemIR::BuiltinFunctionKind::IntSDiv:
  1658. case SemIR::BuiltinFunctionKind::IntSMod:
  1659. case SemIR::BuiltinFunctionKind::IntUAdd:
  1660. case SemIR::BuiltinFunctionKind::IntUSub:
  1661. case SemIR::BuiltinFunctionKind::IntUMul:
  1662. case SemIR::BuiltinFunctionKind::IntUDiv:
  1663. case SemIR::BuiltinFunctionKind::IntUMod:
  1664. case SemIR::BuiltinFunctionKind::IntAnd:
  1665. case SemIR::BuiltinFunctionKind::IntOr:
  1666. case SemIR::BuiltinFunctionKind::IntXor: {
  1667. if (phase != Phase::Concrete) {
  1668. break;
  1669. }
  1670. return PerformBuiltinBinaryIntOp(context, loc_id, builtin_kind,
  1671. arg_ids[0], arg_ids[1]);
  1672. }
  1673. // Bit shift operations.
  1674. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1675. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1676. if (phase != Phase::Concrete) {
  1677. break;
  1678. }
  1679. return PerformBuiltinIntShiftOp(context, loc_id, builtin_kind, arg_ids[0],
  1680. arg_ids[1]);
  1681. }
  1682. // Integer comparisons.
  1683. case SemIR::BuiltinFunctionKind::IntEq:
  1684. case SemIR::BuiltinFunctionKind::IntNeq:
  1685. case SemIR::BuiltinFunctionKind::IntLess:
  1686. case SemIR::BuiltinFunctionKind::IntLessEq:
  1687. case SemIR::BuiltinFunctionKind::IntGreater:
  1688. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1689. if (phase != Phase::Concrete) {
  1690. break;
  1691. }
  1692. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1693. arg_ids[1], call.type_id);
  1694. }
  1695. // Floating-point conversions.
  1696. case SemIR::BuiltinFunctionKind::FloatConvertChecked: {
  1697. if (phase != Phase::Concrete) {
  1698. return MakeConstantResult(context, call, phase);
  1699. }
  1700. return PerformCheckedFloatConvert(context, loc_id, arg_ids[0],
  1701. call.type_id);
  1702. }
  1703. // Unary float -> float operations.
  1704. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1705. if (phase != Phase::Concrete) {
  1706. break;
  1707. }
  1708. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1709. }
  1710. // Binary float -> float operations.
  1711. case SemIR::BuiltinFunctionKind::FloatAdd:
  1712. case SemIR::BuiltinFunctionKind::FloatSub:
  1713. case SemIR::BuiltinFunctionKind::FloatMul:
  1714. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1715. if (phase != Phase::Concrete) {
  1716. break;
  1717. }
  1718. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1719. arg_ids[1]);
  1720. }
  1721. // Float comparisons.
  1722. case SemIR::BuiltinFunctionKind::FloatEq:
  1723. case SemIR::BuiltinFunctionKind::FloatNeq:
  1724. case SemIR::BuiltinFunctionKind::FloatLess:
  1725. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1726. case SemIR::BuiltinFunctionKind::FloatGreater:
  1727. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1728. if (phase != Phase::Concrete) {
  1729. break;
  1730. }
  1731. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1732. arg_ids[1], call.type_id);
  1733. }
  1734. // Bool comparisons.
  1735. case SemIR::BuiltinFunctionKind::BoolEq:
  1736. case SemIR::BuiltinFunctionKind::BoolNeq: {
  1737. if (phase != Phase::Concrete) {
  1738. break;
  1739. }
  1740. return PerformBuiltinBoolComparison(context, builtin_kind, arg_ids[0],
  1741. arg_ids[1], call.type_id);
  1742. }
  1743. }
  1744. return SemIR::ConstantId::NotConstant;
  1745. }
  1746. // Makes a constant for a call instruction.
  1747. static auto MakeConstantForCall(EvalContext& eval_context,
  1748. SemIR::InstId inst_id, SemIR::Call call)
  1749. -> SemIR::ConstantId {
  1750. Phase phase = Phase::Concrete;
  1751. // A call with an invalid argument list is used to represent an erroneous
  1752. // call.
  1753. //
  1754. // TODO: Use a better representation for this.
  1755. if (call.args_id == SemIR::InstBlockId::None) {
  1756. return SemIR::ErrorInst::ConstantId;
  1757. }
  1758. // Find the constant value of the callee.
  1759. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1760. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1761. auto callee_function =
  1762. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1763. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1764. if (callee_function.function_id.has_value()) {
  1765. // Calls to builtins might be constant.
  1766. builtin_kind = eval_context.functions()
  1767. .Get(callee_function.function_id)
  1768. .builtin_function_kind();
  1769. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1770. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1771. // functions as producing constants.
  1772. return SemIR::ConstantId::NotConstant;
  1773. }
  1774. } else {
  1775. // Calls to non-functions, such as calls to generic entity names, might be
  1776. // constant.
  1777. }
  1778. // Find the argument values and the return type.
  1779. bool has_constant_operands =
  1780. has_constant_callee &&
  1781. ReplaceTypeWithConstantValue(eval_context, inst_id, &call, &phase) &&
  1782. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1783. &phase);
  1784. if (phase == Phase::UnknownDueToError) {
  1785. return SemIR::ErrorInst::ConstantId;
  1786. }
  1787. // If any operand of the call is non-constant, the call is non-constant.
  1788. // TODO: Some builtin calls might allow some operands to be non-constant.
  1789. if (!has_constant_operands) {
  1790. if (builtin_kind.IsCompTimeOnly(
  1791. eval_context.sem_ir(), eval_context.inst_blocks().Get(call.args_id),
  1792. call.type_id)) {
  1793. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1794. "non-constant call to compile-time-only function");
  1795. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1796. "compile-time-only function declared here");
  1797. eval_context.emitter()
  1798. .Build(inst_id, NonConstantCallToCompTimeOnlyFunction)
  1799. .Note(eval_context.functions()
  1800. .Get(callee_function.function_id)
  1801. .latest_decl_id(),
  1802. CompTimeOnlyFunctionHere)
  1803. .Emit();
  1804. }
  1805. return SemIR::ConstantId::NotConstant;
  1806. }
  1807. // Handle calls to builtins.
  1808. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1809. return MakeConstantForBuiltinCall(
  1810. eval_context, SemIR::LocId(inst_id), call, builtin_kind,
  1811. eval_context.inst_blocks().Get(call.args_id), phase);
  1812. }
  1813. return SemIR::ConstantId::NotConstant;
  1814. }
  1815. // Given an instruction, compute its phase based on its operands.
  1816. static auto ComputeInstPhase(Context& context, SemIR::Inst inst) -> Phase {
  1817. EvalContext eval_context(&context, SemIR::LocId::None);
  1818. auto phase = GetPhase(context.constant_values(),
  1819. context.types().GetConstantId(inst.type_id()));
  1820. GetConstantValueForArg(eval_context, inst.arg0_and_kind(), &phase);
  1821. GetConstantValueForArg(eval_context, inst.arg1_and_kind(), &phase);
  1822. CARBON_CHECK(IsConstantOrError(phase));
  1823. return phase;
  1824. }
  1825. // Convert a ConstantEvalResult to a ConstantId. Factored out of
  1826. // TryEvalTypedInst to avoid repeated instantiation of common code.
  1827. static auto ConvertEvalResultToConstantId(Context& context,
  1828. ConstantEvalResult result,
  1829. Phase orig_phase)
  1830. -> SemIR::ConstantId {
  1831. if (result.is_new()) {
  1832. return MakeConstantResult(
  1833. context, result.new_inst(),
  1834. result.same_phase_as_inst()
  1835. ? orig_phase
  1836. : ComputeInstPhase(context, result.new_inst()));
  1837. }
  1838. return result.existing();
  1839. }
  1840. // Evaluates an instruction of a known type in an evaluation context. The
  1841. // default behavior of this function depends on the constant kind of the
  1842. // instruction:
  1843. //
  1844. // - InstConstantKind::Never: returns ConstantId::NotConstant.
  1845. // - InstConstantKind::Indirect, SymbolicOnly, SymbolicOrReference,
  1846. // Conditional: evaluates all the operands of the instruction, and calls
  1847. // `EvalConstantInst` to evaluate the resulting constant instruction.
  1848. // - InstConstantKind::WheneverPossible, Always: evaluates all the operands of
  1849. // the instruction, and produces the resulting constant instruction as the
  1850. // result.
  1851. // - InstConstantKind::Unique: returns the `inst_id` as the resulting
  1852. // constant.
  1853. //
  1854. // Returns an error constant ID if any of the nested evaluations fail, and
  1855. // returns NotConstant if any of the nested evaluations is non-constant.
  1856. //
  1857. // This template is explicitly specialized for instructions that need special
  1858. // handling.
  1859. template <typename InstT>
  1860. static auto TryEvalTypedInst(EvalContext& eval_context, SemIR::InstId inst_id,
  1861. SemIR::Inst inst) -> SemIR::ConstantId {
  1862. constexpr auto ConstantKind = InstT::Kind.constant_kind();
  1863. if constexpr (ConstantKind == SemIR::InstConstantKind::Never) {
  1864. return SemIR::ConstantId::NotConstant;
  1865. } else if constexpr (ConstantKind == SemIR::InstConstantKind::AlwaysUnique) {
  1866. CARBON_CHECK(inst_id.has_value());
  1867. return SemIR::ConstantId::ForConcreteConstant(inst_id);
  1868. } else {
  1869. // Build a constant instruction by replacing each non-constant operand with
  1870. // its constant value.
  1871. Phase phase = Phase::Concrete;
  1872. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &inst, &phase) ||
  1873. !ReplaceAllFieldsWithConstantValues(eval_context, &inst, &phase)) {
  1874. if constexpr (ConstantKind == SemIR::InstConstantKind::Always) {
  1875. CARBON_FATAL("{0} should always be constant", InstT::Kind);
  1876. }
  1877. return SemIR::ConstantId::NotConstant;
  1878. }
  1879. // If any operand of the instruction has an error in it, the instruction
  1880. // itself evaluates to an error.
  1881. if (phase == Phase::UnknownDueToError) {
  1882. return SemIR::ErrorInst::ConstantId;
  1883. }
  1884. // When canonicalizing a SpecificId, we defer resolving the specific's
  1885. // declaration until here, to avoid resolving declarations from imported
  1886. // specifics. (Imported instructions are not evaluated.)
  1887. ResolveSpecificDeclForInst(eval_context, inst);
  1888. if constexpr (ConstantKind == SemIR::InstConstantKind::Always ||
  1889. ConstantKind == SemIR::InstConstantKind::WheneverPossible) {
  1890. return MakeConstantResult(eval_context.context(), inst, phase);
  1891. } else if constexpr (ConstantKind == SemIR::InstConstantKind::InstAction) {
  1892. auto result_inst_id = PerformDelayedAction(
  1893. eval_context.context(), SemIR::LocId(inst_id), inst.As<InstT>());
  1894. if (result_inst_id.has_value()) {
  1895. // The result is an instruction.
  1896. return MakeConstantResult(
  1897. eval_context.context(),
  1898. SemIR::InstValue{.type_id = SemIR::InstType::TypeId,
  1899. .inst_id = result_inst_id},
  1900. Phase::Concrete);
  1901. }
  1902. // Couldn't perform the action because it's still dependent.
  1903. return MakeConstantResult(eval_context.context(), inst,
  1904. Phase::TemplateSymbolic);
  1905. } else if constexpr (InstT::Kind.constant_needs_inst_id() !=
  1906. SemIR::InstConstantNeedsInstIdKind::No) {
  1907. CARBON_CHECK(inst_id.has_value());
  1908. return ConvertEvalResultToConstantId(
  1909. eval_context.context(),
  1910. EvalConstantInst(eval_context.context(), inst_id, inst.As<InstT>()),
  1911. phase);
  1912. } else {
  1913. return ConvertEvalResultToConstantId(
  1914. eval_context.context(),
  1915. EvalConstantInst(eval_context.context(), inst.As<InstT>()), phase);
  1916. }
  1917. }
  1918. }
  1919. // Specialize evaluation for array indexing because we want to check the index
  1920. // expression even if the array expression is non-constant.
  1921. template <>
  1922. auto TryEvalTypedInst<SemIR::ArrayIndex>(EvalContext& eval_context,
  1923. SemIR::InstId /*inst_id*/,
  1924. SemIR::Inst inst)
  1925. -> SemIR::ConstantId {
  1926. return PerformArrayIndex(eval_context, inst.As<SemIR::ArrayIndex>());
  1927. }
  1928. // Specialize evaluation for function calls because we want to check the callee
  1929. // expression even if an argument expression is non-constant, and because we
  1930. // will eventually want to perform control flow handling here.
  1931. template <>
  1932. auto TryEvalTypedInst<SemIR::Call>(EvalContext& eval_context,
  1933. SemIR::InstId inst_id, SemIR::Inst inst)
  1934. -> SemIR::ConstantId {
  1935. return MakeConstantForCall(eval_context, inst_id, inst.As<SemIR::Call>());
  1936. }
  1937. // ImportRefLoaded can have a constant value, but it's owned and maintained by
  1938. // `import_ref.cpp`, not by us.
  1939. // TODO: Rearrange how `ImportRefLoaded` instructions are created so we never
  1940. // call this.
  1941. template <>
  1942. auto TryEvalTypedInst<SemIR::ImportRefLoaded>(EvalContext& /*eval_context*/,
  1943. SemIR::InstId /*inst_id*/,
  1944. SemIR::Inst /*inst*/)
  1945. -> SemIR::ConstantId {
  1946. return SemIR::ConstantId::NotConstant;
  1947. }
  1948. // Symbolic bindings are a special case because they can reach into the eval
  1949. // context and produce a context-specific value.
  1950. template <>
  1951. auto TryEvalTypedInst<SemIR::BindSymbolicName>(EvalContext& eval_context,
  1952. SemIR::InstId inst_id,
  1953. SemIR::Inst inst)
  1954. -> SemIR::ConstantId {
  1955. auto bind = inst.As<SemIR::BindSymbolicName>();
  1956. // If we know which specific we're evaluating within and this is an argument
  1957. // of that specific, its constant value is the corresponding argument value.
  1958. const auto& bind_name = eval_context.entity_names().Get(bind.entity_name_id);
  1959. if (bind_name.bind_index().has_value()) {
  1960. if (auto value =
  1961. eval_context.GetCompileTimeBindValue(bind_name.bind_index());
  1962. value.has_value()) {
  1963. return value;
  1964. }
  1965. }
  1966. // The constant form of a symbolic binding is an idealized form of the
  1967. // original, with no equivalent value.
  1968. Phase phase = Phase::Concrete;
  1969. bind.value_id = SemIR::InstId::None;
  1970. if (!ReplaceTypeWithConstantValue(eval_context, inst_id, &bind, &phase) ||
  1971. !ReplaceFieldWithConstantValue(eval_context, &bind,
  1972. &SemIR::BindSymbolicName::entity_name_id,
  1973. &phase)) {
  1974. return SemIR::ConstantId::NotConstant;
  1975. }
  1976. // This correctly handles `Phase::UnknownDueToError`.
  1977. return MakeConstantResult(eval_context.context(), bind, phase);
  1978. }
  1979. // Returns whether `const_id` is the same constant facet value as
  1980. // `facet_value_inst_id`.
  1981. static auto IsSameFacetValue(Context& context, SemIR::ConstantId const_id,
  1982. SemIR::InstId facet_value_inst_id) -> bool {
  1983. if (auto facet_access_type = context.insts().TryGetAs<SemIR::FacetAccessType>(
  1984. context.constant_values().GetInstId(const_id))) {
  1985. const_id =
  1986. context.constant_values().Get(facet_access_type->facet_value_inst_id);
  1987. }
  1988. return const_id == context.constant_values().Get(facet_value_inst_id);
  1989. }
  1990. // TODO: Convert this to an EvalConstantInst function. This will require
  1991. // providing a `GetConstantValue` overload for a requirement block.
  1992. template <>
  1993. auto TryEvalTypedInst<SemIR::WhereExpr>(EvalContext& eval_context,
  1994. SemIR::InstId inst_id, SemIR::Inst inst)
  1995. -> SemIR::ConstantId {
  1996. auto typed_inst = inst.As<SemIR::WhereExpr>();
  1997. Phase phase = Phase::Concrete;
  1998. SemIR::FacetTypeInfo info;
  1999. // Add the constraints from the `WhereExpr` instruction into `info`.
  2000. if (typed_inst.requirements_id.has_value()) {
  2001. auto insts = eval_context.inst_blocks().Get(typed_inst.requirements_id);
  2002. for (auto inst_id : insts) {
  2003. if (auto base =
  2004. eval_context.insts().TryGetAs<SemIR::RequirementBaseFacetType>(
  2005. inst_id)) {
  2006. if (base->base_type_inst_id == SemIR::ErrorInst::TypeInstId) {
  2007. return SemIR::ErrorInst::ConstantId;
  2008. }
  2009. if (auto base_facet_type =
  2010. eval_context.insts().TryGetAs<SemIR::FacetType>(
  2011. base->base_type_inst_id)) {
  2012. const auto& base_info =
  2013. eval_context.facet_types().Get(base_facet_type->facet_type_id);
  2014. info.extend_constraints.append(base_info.extend_constraints);
  2015. info.self_impls_constraints.append(base_info.self_impls_constraints);
  2016. info.rewrite_constraints.append(base_info.rewrite_constraints);
  2017. info.builtin_constraint_mask.Add(base_info.builtin_constraint_mask);
  2018. info.other_requirements |= base_info.other_requirements;
  2019. }
  2020. } else if (auto rewrite =
  2021. eval_context.insts().TryGetAs<SemIR::RequirementRewrite>(
  2022. inst_id)) {
  2023. info.rewrite_constraints.push_back(
  2024. {.lhs_id = rewrite->lhs_id, .rhs_id = rewrite->rhs_id});
  2025. } else if (auto impls =
  2026. eval_context.insts().TryGetAs<SemIR::RequirementImpls>(
  2027. inst_id)) {
  2028. SemIR::ConstantId lhs_const_id =
  2029. eval_context.GetConstantValue(impls->lhs_id);
  2030. SemIR::ConstantId rhs_const_id =
  2031. eval_context.GetConstantValue(impls->rhs_id);
  2032. if (IsSameFacetValue(eval_context.context(), lhs_const_id,
  2033. typed_inst.period_self_id)) {
  2034. auto rhs_inst_id =
  2035. eval_context.constant_values().GetInstId(rhs_const_id);
  2036. if (rhs_inst_id == SemIR::ErrorInst::InstId) {
  2037. // `.Self impls <error>`.
  2038. return SemIR::ErrorInst::ConstantId;
  2039. } else if (rhs_inst_id == SemIR::TypeType::TypeInstId) {
  2040. // `.Self impls type` -> nothing to do.
  2041. } else {
  2042. auto facet_type = eval_context.insts().GetAs<SemIR::FacetType>(
  2043. RequireConstantValue(eval_context, impls->rhs_id, &phase));
  2044. const auto& more_info =
  2045. eval_context.facet_types().Get(facet_type.facet_type_id);
  2046. // The way to prevent lookup into the interface requirements of a
  2047. // facet type is to put it to the right of a `.Self impls`, which we
  2048. // accomplish by putting them into `self_impls_constraints`.
  2049. llvm::append_range(info.self_impls_constraints,
  2050. more_info.extend_constraints);
  2051. llvm::append_range(info.self_impls_constraints,
  2052. more_info.self_impls_constraints);
  2053. // Other requirements are copied in.
  2054. llvm::append_range(info.rewrite_constraints,
  2055. more_info.rewrite_constraints);
  2056. info.builtin_constraint_mask.Add(more_info.builtin_constraint_mask);
  2057. info.other_requirements |= more_info.other_requirements;
  2058. }
  2059. } else {
  2060. // TODO: Handle `impls` constraints beyond `.Self impls`.
  2061. info.other_requirements = true;
  2062. }
  2063. } else {
  2064. // TODO: Handle other requirements.
  2065. info.other_requirements = true;
  2066. }
  2067. }
  2068. }
  2069. auto const_info = GetConstantFacetTypeInfo(
  2070. eval_context, SemIR::LocId(inst_id), info, &phase);
  2071. return MakeFacetTypeResult(eval_context.context(), const_info, phase);
  2072. }
  2073. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  2074. static auto TryEvalInstInContext(EvalContext& eval_context,
  2075. SemIR::InstId inst_id, SemIR::Inst inst)
  2076. -> SemIR::ConstantId {
  2077. using EvalInstFn =
  2078. auto(EvalContext & eval_context, SemIR::InstId inst_id, SemIR::Inst inst)
  2079. ->SemIR::ConstantId;
  2080. static constexpr EvalInstFn* EvalInstFns[] = {
  2081. #define CARBON_SEM_IR_INST_KIND(Kind) &TryEvalTypedInst<SemIR::Kind>,
  2082. #include "toolchain/sem_ir/inst_kind.def"
  2083. };
  2084. [[clang::musttail]] return EvalInstFns[inst.kind().AsInt()](eval_context,
  2085. inst_id, inst);
  2086. }
  2087. auto TryEvalInstUnsafe(Context& context, SemIR::InstId inst_id,
  2088. SemIR::Inst inst) -> SemIR::ConstantId {
  2089. EvalContext eval_context(&context, SemIR::LocId(inst_id));
  2090. return TryEvalInstInContext(eval_context, inst_id, inst);
  2091. }
  2092. auto TryEvalBlockForSpecific(Context& context, SemIR::LocId loc_id,
  2093. SemIR::SpecificId specific_id,
  2094. SemIR::GenericInstIndex::Region region)
  2095. -> SemIR::InstBlockId {
  2096. auto generic_id = context.specifics().Get(specific_id).generic_id;
  2097. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  2098. auto eval_block = context.inst_blocks().Get(eval_block_id);
  2099. llvm::SmallVector<SemIR::InstId> result;
  2100. result.resize(eval_block.size(), SemIR::InstId::None);
  2101. EvalContext eval_context(&context, loc_id, specific_id,
  2102. SpecificEvalInfo{
  2103. .region = region,
  2104. .values = result,
  2105. });
  2106. Diagnostics::AnnotationScope annotate_diagnostics(
  2107. &context.emitter(), [&](auto& builder) {
  2108. CARBON_DIAGNOSTIC(ResolvingSpecificHere, Note, "in {0} used here",
  2109. SemIR::SpecificId);
  2110. builder.Note(loc_id, ResolvingSpecificHere, specific_id);
  2111. });
  2112. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  2113. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  2114. context.insts().Get(inst_id));
  2115. result[i] = context.constant_values().GetInstId(const_id);
  2116. CARBON_CHECK(result[i].has_value(), "Failed to evaluate {0} in eval block",
  2117. context.insts().Get(inst_id));
  2118. }
  2119. return context.inst_blocks().Add(result);
  2120. }
  2121. } // namespace Carbon::Check