eval.cpp 74 KB

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