eval.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  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/generic.h"
  8. #include "toolchain/diagnostics/diagnostic_emitter.h"
  9. #include "toolchain/diagnostics/format_providers.h"
  10. #include "toolchain/sem_ir/builtin_function_kind.h"
  11. #include "toolchain/sem_ir/function.h"
  12. #include "toolchain/sem_ir/generic.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/inst_kind.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Check {
  17. namespace {
  18. // Information about an eval block of a specific that we are currently building.
  19. struct SpecificEvalInfo {
  20. // The region within the specific whose eval block we are building.
  21. SemIR::GenericInstIndex::Region region;
  22. // The work-in-progress contents of the eval block.
  23. llvm::ArrayRef<SemIR::InstId> values;
  24. };
  25. // Information about the context within which we are performing evaluation.
  26. class EvalContext {
  27. public:
  28. explicit EvalContext(
  29. Context& context,
  30. SemIR::SpecificId specific_id = SemIR::SpecificId::Invalid,
  31. std::optional<SpecificEvalInfo> specific_eval_info = std::nullopt)
  32. : context_(context),
  33. specific_id_(specific_id),
  34. specific_eval_info_(specific_eval_info) {}
  35. // Gets the value of the specified compile-time binding in this context.
  36. // Returns `Invalid` if the value is not fixed in this context.
  37. auto GetCompileTimeBindValue(SemIR::CompileTimeBindIndex bind_index)
  38. -> SemIR::ConstantId {
  39. if (!bind_index.is_valid() || !specific_id_.is_valid()) {
  40. return SemIR::ConstantId::Invalid;
  41. }
  42. const auto& specific = specifics().Get(specific_id_);
  43. auto args = inst_blocks().Get(specific.args_id);
  44. // Bindings past the ones with known arguments can appear as local
  45. // bindings of entities declared within this generic.
  46. if (static_cast<size_t>(bind_index.index) >= args.size()) {
  47. return SemIR::ConstantId::Invalid;
  48. }
  49. return constant_values().Get(args[bind_index.index]);
  50. }
  51. // Given a constant value from the SemIR we're evaluating, finds the
  52. // corresponding constant value to use in the context of this evaluation.
  53. // This can be different if the original SemIR is for a generic and we are
  54. // evaluating with specific arguments for the generic parameters.
  55. auto GetInContext(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  56. if (!const_id.is_symbolic()) {
  57. return const_id;
  58. }
  59. // While resolving a specific, map from previous instructions in the eval
  60. // block into their evaluated values. These values won't be present on the
  61. // specific itself yet, so `GetConstantInSpecific` won't be able to find
  62. // them.
  63. if (specific_eval_info_) {
  64. const auto& symbolic_info =
  65. constant_values().GetSymbolicConstant(const_id);
  66. if (symbolic_info.index.is_valid() &&
  67. symbolic_info.generic_id ==
  68. specifics().Get(specific_id_).generic_id &&
  69. symbolic_info.index.region() == specific_eval_info_->region) {
  70. auto inst_id = specific_eval_info_->values[symbolic_info.index.index()];
  71. CARBON_CHECK(inst_id.is_valid(),
  72. "Forward reference in eval block: index {0} referenced "
  73. "before evaluation",
  74. symbolic_info.index.index());
  75. return constant_values().Get(inst_id);
  76. }
  77. }
  78. // Map from a specific constant value to the canonical value.
  79. return GetConstantInSpecific(sem_ir(), specific_id_, const_id);
  80. }
  81. // Gets the constant value of the specified instruction in this context.
  82. auto GetConstantValue(SemIR::InstId inst_id) -> SemIR::ConstantId {
  83. return GetInContext(constant_values().Get(inst_id));
  84. }
  85. // Gets the constant value of the specified type in this context.
  86. auto GetConstantValue(SemIR::TypeId type_id) -> SemIR::ConstantId {
  87. return GetInContext(types().GetConstantId(type_id));
  88. }
  89. // Gets the constant value of the specified type in this context.
  90. auto GetConstantValueAsType(SemIR::TypeId id) -> SemIR::TypeId {
  91. return context().GetTypeIdForTypeConstant(GetConstantValue(id));
  92. }
  93. // Gets the instruction describing the constant value of the specified type in
  94. // this context.
  95. auto GetConstantValueAsInst(SemIR::TypeId id) -> SemIR::Inst {
  96. return insts().Get(
  97. context().constant_values().GetInstId(GetConstantValue(id)));
  98. }
  99. auto ints() -> SharedValueStores::IntStore& { return sem_ir().ints(); }
  100. auto floats() -> SharedValueStores::FloatStore& { return sem_ir().floats(); }
  101. auto entity_names() -> SemIR::EntityNameStore& {
  102. return sem_ir().entity_names();
  103. }
  104. auto functions() -> const ValueStore<SemIR::FunctionId>& {
  105. return sem_ir().functions();
  106. }
  107. auto classes() -> const ValueStore<SemIR::ClassId>& {
  108. return sem_ir().classes();
  109. }
  110. auto interfaces() -> const ValueStore<SemIR::InterfaceId>& {
  111. return sem_ir().interfaces();
  112. }
  113. auto facet_types() -> CanonicalValueStore<SemIR::FacetTypeId>& {
  114. return sem_ir().facet_types();
  115. }
  116. auto specifics() -> const SemIR::SpecificStore& {
  117. return sem_ir().specifics();
  118. }
  119. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  120. return sem_ir().type_blocks();
  121. }
  122. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  123. auto inst_blocks() -> SemIR::InstBlockStore& {
  124. return sem_ir().inst_blocks();
  125. }
  126. // Gets the constant value store. Note that this does not provide the constant
  127. // values that should be used from this evaluation context, and so should be
  128. // used with caution.
  129. auto constant_values() -> const SemIR::ConstantValueStore& {
  130. return sem_ir().constant_values();
  131. }
  132. // Gets the types store. Note that this does not provide the type values that
  133. // should be used from this evaluation context, and so should be used with
  134. // caution.
  135. auto types() -> const SemIR::TypeStore& { return sem_ir().types(); }
  136. auto context() -> Context& { return context_; }
  137. auto sem_ir() -> SemIR::File& { return context().sem_ir(); }
  138. auto emitter() -> Context::DiagnosticEmitter& { return context().emitter(); }
  139. private:
  140. // The type-checking context in which we're performing evaluation.
  141. Context& context_;
  142. // The specific that we are evaluating within.
  143. SemIR::SpecificId specific_id_;
  144. // If we are currently evaluating an eval block for `specific_id_`,
  145. // information about that evaluation.
  146. std::optional<SpecificEvalInfo> specific_eval_info_;
  147. };
  148. } // namespace
  149. namespace {
  150. // The evaluation phase for an expression, computed by evaluation. These are
  151. // ordered so that the phase of an expression is the numerically highest phase
  152. // of its constituent evaluations. Note that an expression with any runtime
  153. // component is known to have Runtime phase even if it involves an evaluation
  154. // with UnknownDueToError phase.
  155. enum class Phase : uint8_t {
  156. // Value could be entirely and concretely computed.
  157. Template,
  158. // Evaluation phase is symbolic because the expression involves a reference to
  159. // a symbolic binding.
  160. Symbolic,
  161. // The evaluation phase is unknown because evaluation encountered an
  162. // already-diagnosed semantic or syntax error. This is treated as being
  163. // potentially constant, but with an unknown phase.
  164. UnknownDueToError,
  165. // The expression has runtime phase because of a non-constant subexpression.
  166. Runtime,
  167. };
  168. } // namespace
  169. // Gets the phase in which the value of a constant will become available.
  170. static auto GetPhase(SemIR::ConstantId constant_id) -> Phase {
  171. if (!constant_id.is_constant()) {
  172. return Phase::Runtime;
  173. } else if (constant_id == SemIR::ConstantId::Error) {
  174. return Phase::UnknownDueToError;
  175. } else if (constant_id.is_template()) {
  176. return Phase::Template;
  177. } else {
  178. CARBON_CHECK(constant_id.is_symbolic());
  179. return Phase::Symbolic;
  180. }
  181. }
  182. // Returns the later of two phases.
  183. static auto LatestPhase(Phase a, Phase b) -> Phase {
  184. return static_cast<Phase>(
  185. std::max(static_cast<uint8_t>(a), static_cast<uint8_t>(b)));
  186. }
  187. // Forms a `constant_id` describing a given evaluation result.
  188. static auto MakeConstantResult(Context& context, SemIR::Inst inst, Phase phase)
  189. -> SemIR::ConstantId {
  190. switch (phase) {
  191. case Phase::Template:
  192. return context.AddConstant(inst, /*is_symbolic=*/false);
  193. case Phase::Symbolic:
  194. return context.AddConstant(inst, /*is_symbolic=*/true);
  195. case Phase::UnknownDueToError:
  196. return SemIR::ConstantId::Error;
  197. case Phase::Runtime:
  198. return SemIR::ConstantId::NotConstant;
  199. }
  200. }
  201. // Forms a `constant_id` describing why an evaluation was not constant.
  202. static auto MakeNonConstantResult(Phase phase) -> SemIR::ConstantId {
  203. return phase == Phase::UnknownDueToError ? SemIR::ConstantId::Error
  204. : SemIR::ConstantId::NotConstant;
  205. }
  206. // Converts a bool value into a ConstantId.
  207. static auto MakeBoolResult(Context& context, SemIR::TypeId bool_type_id,
  208. bool result) -> SemIR::ConstantId {
  209. return MakeConstantResult(
  210. context,
  211. SemIR::BoolLiteral{.type_id = bool_type_id,
  212. .value = SemIR::BoolValue::From(result)},
  213. Phase::Template);
  214. }
  215. // Converts an APInt value into a ConstantId.
  216. static auto MakeIntResult(Context& context, SemIR::TypeId type_id,
  217. bool is_signed, llvm::APInt value)
  218. -> SemIR::ConstantId {
  219. CARBON_CHECK(is_signed == context.types().IsSignedInt(type_id));
  220. auto result = is_signed ? context.ints().AddSigned(std::move(value))
  221. : context.ints().AddUnsigned(std::move(value));
  222. return MakeConstantResult(
  223. context, SemIR::IntValue{.type_id = type_id, .int_id = result},
  224. Phase::Template);
  225. }
  226. // Converts an APFloat value into a ConstantId.
  227. static auto MakeFloatResult(Context& context, SemIR::TypeId type_id,
  228. llvm::APFloat value) -> SemIR::ConstantId {
  229. auto result = context.floats().Add(std::move(value));
  230. return MakeConstantResult(
  231. context, SemIR::FloatLiteral{.type_id = type_id, .float_id = result},
  232. Phase::Template);
  233. }
  234. // `GetConstantValue` checks to see whether the provided ID describes a value
  235. // with constant phase, and if so, returns the corresponding constant value.
  236. // Overloads are provided for different kinds of ID.
  237. // If the given instruction is constant, returns its constant value.
  238. static auto GetConstantValue(EvalContext& eval_context, SemIR::InstId inst_id,
  239. Phase* phase) -> SemIR::InstId {
  240. auto const_id = eval_context.GetConstantValue(inst_id);
  241. *phase = LatestPhase(*phase, GetPhase(const_id));
  242. return eval_context.constant_values().GetInstId(const_id);
  243. }
  244. // Given a type which may refer to a generic parameter, returns the
  245. // corresponding type in the evaluation context.
  246. static auto GetConstantValue(EvalContext& eval_context, SemIR::TypeId type_id,
  247. Phase* phase) -> SemIR::TypeId {
  248. auto const_id = eval_context.GetConstantValue(type_id);
  249. *phase = LatestPhase(*phase, GetPhase(const_id));
  250. return eval_context.context().GetTypeIdForTypeConstant(const_id);
  251. }
  252. // If the given instruction block contains only constants, returns a
  253. // corresponding block of those values.
  254. static auto GetConstantValue(EvalContext& eval_context,
  255. SemIR::InstBlockId inst_block_id, Phase* phase)
  256. -> SemIR::InstBlockId {
  257. if (!inst_block_id.is_valid()) {
  258. return SemIR::InstBlockId::Invalid;
  259. }
  260. auto insts = eval_context.inst_blocks().Get(inst_block_id);
  261. llvm::SmallVector<SemIR::InstId> const_insts;
  262. for (auto inst_id : insts) {
  263. auto const_inst_id = GetConstantValue(eval_context, inst_id, phase);
  264. if (!const_inst_id.is_valid()) {
  265. return SemIR::InstBlockId::Invalid;
  266. }
  267. // Once we leave the small buffer, we know the first few elements are all
  268. // constant, so it's likely that the entire block is constant. Resize to the
  269. // target size given that we're going to allocate memory now anyway.
  270. if (const_insts.size() == const_insts.capacity()) {
  271. const_insts.reserve(insts.size());
  272. }
  273. const_insts.push_back(const_inst_id);
  274. }
  275. // TODO: If the new block is identical to the original block, and we know the
  276. // old ID was canonical, return the original ID.
  277. return eval_context.inst_blocks().AddCanonical(const_insts);
  278. }
  279. // Compute the constant value of a type block. This may be different from the
  280. // input type block if we have known generic arguments.
  281. static auto GetConstantValue(EvalContext& eval_context,
  282. SemIR::StructTypeFieldsId fields_id, Phase* phase)
  283. -> SemIR::StructTypeFieldsId {
  284. if (!fields_id.is_valid()) {
  285. return SemIR::StructTypeFieldsId::Invalid;
  286. }
  287. auto fields = eval_context.context().struct_type_fields().Get(fields_id);
  288. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  289. for (auto field : fields) {
  290. auto new_type_id = GetConstantValue(eval_context, field.type_id, phase);
  291. if (!new_type_id.is_valid()) {
  292. return SemIR::StructTypeFieldsId::Invalid;
  293. }
  294. // Once we leave the small buffer, we know the first few elements are all
  295. // constant, so it's likely that the entire block is constant. Resize to the
  296. // target size given that we're going to allocate memory now anyway.
  297. if (new_fields.size() == new_fields.capacity()) {
  298. new_fields.reserve(fields.size());
  299. }
  300. new_fields.push_back({.name_id = field.name_id, .type_id = new_type_id});
  301. }
  302. // TODO: If the new block is identical to the original block, and we know the
  303. // old ID was canonical, return the original ID.
  304. return eval_context.context().struct_type_fields().AddCanonical(new_fields);
  305. }
  306. // Compute the constant value of a type block. This may be different from the
  307. // input type block if we have known generic arguments.
  308. static auto GetConstantValue(EvalContext& eval_context,
  309. SemIR::TypeBlockId type_block_id, Phase* phase)
  310. -> SemIR::TypeBlockId {
  311. if (!type_block_id.is_valid()) {
  312. return SemIR::TypeBlockId::Invalid;
  313. }
  314. auto types = eval_context.type_blocks().Get(type_block_id);
  315. llvm::SmallVector<SemIR::TypeId> new_types;
  316. for (auto type_id : types) {
  317. auto new_type_id = GetConstantValue(eval_context, type_id, phase);
  318. if (!new_type_id.is_valid()) {
  319. return SemIR::TypeBlockId::Invalid;
  320. }
  321. // Once we leave the small buffer, we know the first few elements are all
  322. // constant, so it's likely that the entire block is constant. Resize to the
  323. // target size given that we're going to allocate memory now anyway.
  324. if (new_types.size() == new_types.capacity()) {
  325. new_types.reserve(types.size());
  326. }
  327. new_types.push_back(new_type_id);
  328. }
  329. // TODO: If the new block is identical to the original block, and we know the
  330. // old ID was canonical, return the original ID.
  331. return eval_context.type_blocks().AddCanonical(new_types);
  332. }
  333. // The constant value of a specific is the specific with the corresponding
  334. // constant values for its arguments.
  335. static auto GetConstantValue(EvalContext& eval_context,
  336. SemIR::SpecificId specific_id, Phase* phase)
  337. -> SemIR::SpecificId {
  338. if (!specific_id.is_valid()) {
  339. return SemIR::SpecificId::Invalid;
  340. }
  341. const auto& specific = eval_context.specifics().Get(specific_id);
  342. auto args_id = GetConstantValue(eval_context, specific.args_id, phase);
  343. if (!args_id.is_valid()) {
  344. return SemIR::SpecificId::Invalid;
  345. }
  346. if (args_id == specific.args_id) {
  347. return specific_id;
  348. }
  349. return MakeSpecific(eval_context.context(), specific.generic_id, args_id);
  350. }
  351. // Like `GetConstantValue` but does a `FacetTypeId` -> `FacetTypeInfo`
  352. // conversion.
  353. static auto GetConstantFacetTypeInfo(EvalContext& eval_context,
  354. SemIR::FacetTypeId facet_type_id,
  355. Phase* phase) -> SemIR::FacetTypeInfo {
  356. SemIR::FacetTypeInfo info = eval_context.facet_types().Get(facet_type_id);
  357. for (auto& interface : info.impls_constraints) {
  358. interface.specific_id =
  359. GetConstantValue(eval_context, interface.specific_id, phase);
  360. }
  361. std::sort(info.impls_constraints.begin(), info.impls_constraints.end());
  362. // TODO: Process & canonicalize other requirements.
  363. return info;
  364. }
  365. // Replaces the specified field of the given typed instruction with its constant
  366. // value, if it has constant phase. Returns true on success, false if the value
  367. // has runtime phase.
  368. template <typename InstT, typename FieldIdT>
  369. static auto ReplaceFieldWithConstantValue(EvalContext& eval_context,
  370. InstT* inst, FieldIdT InstT::*field,
  371. Phase* phase) -> bool {
  372. auto unwrapped = GetConstantValue(eval_context, inst->*field, phase);
  373. if (!unwrapped.is_valid() && (inst->*field).is_valid()) {
  374. return false;
  375. }
  376. inst->*field = unwrapped;
  377. return true;
  378. }
  379. // If the specified fields of the given typed instruction have constant values,
  380. // replaces the fields with their constant values and builds a corresponding
  381. // constant value. Otherwise returns `ConstantId::NotConstant`. Returns
  382. // `ConstantId::Error` if any subexpression is an error.
  383. //
  384. // The constant value is then checked by calling `validate_fn(typed_inst)`,
  385. // which should return a `bool` indicating whether the new constant is valid. If
  386. // validation passes, `transform_fn(typed_inst)` is called to produce the final
  387. // constant instruction, and a corresponding ConstantId for the new constant is
  388. // returned. If validation fails, it should produce a suitable error message.
  389. // `ConstantId::Error` is returned.
  390. template <typename InstT, typename ValidateFn, typename TransformFn,
  391. typename... EachFieldIdT>
  392. static auto RebuildIfFieldsAreConstantImpl(
  393. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  394. TransformFn transform_fn, EachFieldIdT InstT::*... each_field_id)
  395. -> SemIR::ConstantId {
  396. // Build a constant instruction by replacing each non-constant operand with
  397. // its constant value.
  398. auto typed_inst = inst.As<InstT>();
  399. Phase phase = Phase::Template;
  400. if ((ReplaceFieldWithConstantValue(eval_context, &typed_inst, each_field_id,
  401. &phase) &&
  402. ...)) {
  403. if (phase == Phase::UnknownDueToError || !validate_fn(typed_inst)) {
  404. return SemIR::ConstantId::Error;
  405. }
  406. return MakeConstantResult(eval_context.context(), transform_fn(typed_inst),
  407. phase);
  408. }
  409. return MakeNonConstantResult(phase);
  410. }
  411. // Same as above but with an identity transform function.
  412. template <typename InstT, typename ValidateFn, typename... EachFieldIdT>
  413. static auto RebuildAndValidateIfFieldsAreConstant(
  414. EvalContext& eval_context, SemIR::Inst inst, ValidateFn validate_fn,
  415. EachFieldIdT InstT::*... each_field_id) -> SemIR::ConstantId {
  416. return RebuildIfFieldsAreConstantImpl(eval_context, inst, validate_fn,
  417. std::identity{}, each_field_id...);
  418. }
  419. // Same as above but with no validation step.
  420. template <typename InstT, typename TransformFn, typename... EachFieldIdT>
  421. static auto TransformIfFieldsAreConstant(EvalContext& eval_context,
  422. SemIR::Inst inst,
  423. TransformFn transform_fn,
  424. EachFieldIdT InstT::*... each_field_id)
  425. -> SemIR::ConstantId {
  426. return RebuildIfFieldsAreConstantImpl(
  427. eval_context, inst, [](...) { return true; }, transform_fn,
  428. each_field_id...);
  429. }
  430. // Same as above but with no validation or transform step.
  431. template <typename InstT, typename... EachFieldIdT>
  432. static auto RebuildIfFieldsAreConstant(EvalContext& eval_context,
  433. SemIR::Inst inst,
  434. EachFieldIdT InstT::*... each_field_id)
  435. -> SemIR::ConstantId {
  436. return RebuildIfFieldsAreConstantImpl(
  437. eval_context, inst, [](...) { return true; }, std::identity{},
  438. each_field_id...);
  439. }
  440. // Rebuilds the given aggregate initialization instruction as a corresponding
  441. // constant aggregate value, if its elements are all constants.
  442. static auto RebuildInitAsValue(EvalContext& eval_context, SemIR::Inst inst,
  443. SemIR::InstKind value_kind)
  444. -> SemIR::ConstantId {
  445. return TransformIfFieldsAreConstant(
  446. eval_context, inst,
  447. [&](SemIR::AnyAggregateInit result) {
  448. return SemIR::AnyAggregateValue{.kind = value_kind,
  449. .type_id = result.type_id,
  450. .elements_id = result.elements_id};
  451. },
  452. &SemIR::AnyAggregateInit::type_id, &SemIR::AnyAggregateInit::elements_id);
  453. }
  454. // Performs an access into an aggregate, retrieving the specified element.
  455. static auto PerformAggregateAccess(EvalContext& eval_context, SemIR::Inst inst)
  456. -> SemIR::ConstantId {
  457. auto access_inst = inst.As<SemIR::AnyAggregateAccess>();
  458. Phase phase = Phase::Template;
  459. if (auto aggregate_id =
  460. GetConstantValue(eval_context, access_inst.aggregate_id, &phase);
  461. aggregate_id.is_valid()) {
  462. if (auto aggregate =
  463. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(
  464. aggregate_id)) {
  465. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  466. auto index = static_cast<size_t>(access_inst.index.index);
  467. CARBON_CHECK(index < elements.size(), "Access out of bounds.");
  468. // `Phase` is not used here. If this element is a template constant, then
  469. // so is the result of indexing, even if the aggregate also contains a
  470. // symbolic context.
  471. return eval_context.GetConstantValue(elements[index]);
  472. } else {
  473. CARBON_CHECK(phase != Phase::Template,
  474. "Failed to evaluate template constant {0}", inst);
  475. }
  476. }
  477. return MakeNonConstantResult(phase);
  478. }
  479. // Performs an index into a homogeneous aggregate, retrieving the specified
  480. // element.
  481. static auto PerformArrayIndex(EvalContext& eval_context, SemIR::ArrayIndex inst)
  482. -> SemIR::ConstantId {
  483. Phase phase = Phase::Template;
  484. auto index_id = GetConstantValue(eval_context, inst.index_id, &phase);
  485. if (!index_id.is_valid()) {
  486. return MakeNonConstantResult(phase);
  487. }
  488. auto index = eval_context.insts().TryGetAs<SemIR::IntValue>(index_id);
  489. if (!index) {
  490. CARBON_CHECK(phase != Phase::Template,
  491. "Template constant integer should be a literal");
  492. return MakeNonConstantResult(phase);
  493. }
  494. // Array indexing is invalid if the index is constant and out of range,
  495. // regardless of whether the array itself is constant.
  496. const auto& index_val = eval_context.ints().Get(index->int_id);
  497. auto aggregate_type_id = eval_context.GetConstantValueAsType(
  498. eval_context.insts().Get(inst.array_id).type_id());
  499. if (auto array_type =
  500. eval_context.types().TryGetAs<SemIR::ArrayType>(aggregate_type_id)) {
  501. if (auto bound = eval_context.insts().TryGetAs<SemIR::IntValue>(
  502. array_type->bound_id)) {
  503. // This awkward call to `getZExtValue` is a workaround for APInt not
  504. // supporting comparisons between integers of different bit widths.
  505. if (index_val.getActiveBits() > 64 ||
  506. eval_context.ints()
  507. .Get(bound->int_id)
  508. .ule(index_val.getZExtValue())) {
  509. CARBON_DIAGNOSTIC(ArrayIndexOutOfBounds, Error,
  510. "array index `{0}` is past the end of type {1}",
  511. TypedInt, SemIR::TypeId);
  512. eval_context.emitter().Emit(
  513. inst.index_id, ArrayIndexOutOfBounds,
  514. {.type = index->type_id, .value = index_val}, aggregate_type_id);
  515. return SemIR::ConstantId::Error;
  516. }
  517. }
  518. }
  519. auto aggregate_id = GetConstantValue(eval_context, inst.array_id, &phase);
  520. if (!aggregate_id.is_valid()) {
  521. return MakeNonConstantResult(phase);
  522. }
  523. auto aggregate =
  524. eval_context.insts().TryGetAs<SemIR::AnyAggregateValue>(aggregate_id);
  525. if (!aggregate) {
  526. CARBON_CHECK(phase != Phase::Template,
  527. "Unexpected representation for template constant aggregate");
  528. return MakeNonConstantResult(phase);
  529. }
  530. auto elements = eval_context.inst_blocks().Get(aggregate->elements_id);
  531. return eval_context.GetConstantValue(elements[index_val.getZExtValue()]);
  532. }
  533. // Enforces that an integer type has a valid bit width.
  534. static auto ValidateIntType(Context& context, SemIRLoc loc,
  535. SemIR::IntType result) -> bool {
  536. auto bit_width =
  537. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  538. if (!bit_width) {
  539. // Symbolic bit width.
  540. return true;
  541. }
  542. const auto& bit_width_val = context.ints().Get(bit_width->int_id);
  543. if (bit_width_val.isZero() ||
  544. (context.types().IsSignedInt(bit_width->type_id) &&
  545. bit_width_val.isNegative())) {
  546. CARBON_DIAGNOSTIC(IntWidthNotPositive, Error,
  547. "integer type width of {0} is not positive", TypedInt);
  548. context.emitter().Emit(
  549. loc, IntWidthNotPositive,
  550. {.type = bit_width->type_id, .value = bit_width_val});
  551. return false;
  552. }
  553. // TODO: Pick a maximum size and document it in the design. For now
  554. // we use 2^^23, because that's the largest size that LLVM supports.
  555. constexpr int MaxIntWidth = 1 << 23;
  556. if (bit_width_val.ugt(MaxIntWidth)) {
  557. CARBON_DIAGNOSTIC(IntWidthTooLarge, Error,
  558. "integer type width of {0} is greater than the "
  559. "maximum supported width of {1}",
  560. TypedInt, int);
  561. context.emitter().Emit(loc, IntWidthTooLarge,
  562. {.type = bit_width->type_id, .value = bit_width_val},
  563. MaxIntWidth);
  564. return false;
  565. }
  566. return true;
  567. }
  568. // Forms a constant int type as an evaluation result. Requires that width_id is
  569. // constant.
  570. static auto MakeIntTypeResult(Context& context, SemIRLoc loc,
  571. SemIR::IntKind int_kind, SemIR::InstId width_id,
  572. Phase phase) -> SemIR::ConstantId {
  573. auto result = SemIR::IntType{
  574. .type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::TypeType),
  575. .int_kind = int_kind,
  576. .bit_width_id = width_id};
  577. if (!ValidateIntType(context, loc, result)) {
  578. return SemIR::ConstantId::Error;
  579. }
  580. return MakeConstantResult(context, result, phase);
  581. }
  582. // Enforces that the bit width is 64 for a float.
  583. static auto ValidateFloatBitWidth(Context& context, SemIRLoc loc,
  584. SemIR::InstId inst_id) -> bool {
  585. auto inst = context.insts().GetAs<SemIR::IntValue>(inst_id);
  586. if (context.ints().Get(inst.int_id) == 64) {
  587. return true;
  588. }
  589. CARBON_DIAGNOSTIC(CompileTimeFloatBitWidth, Error, "bit width must be 64");
  590. context.emitter().Emit(loc, CompileTimeFloatBitWidth);
  591. return false;
  592. }
  593. // Enforces that a float type has a valid bit width.
  594. static auto ValidateFloatType(Context& context, SemIRLoc loc,
  595. SemIR::FloatType result) -> bool {
  596. auto bit_width =
  597. context.insts().TryGetAs<SemIR::IntValue>(result.bit_width_id);
  598. if (!bit_width) {
  599. // Symbolic bit width.
  600. return true;
  601. }
  602. return ValidateFloatBitWidth(context, loc, result.bit_width_id);
  603. }
  604. // Performs a conversion between integer types, diagnosing if the value doesn't
  605. // fit in the destination type.
  606. static auto PerformCheckedIntConvert(Context& context, SemIRLoc loc,
  607. SemIR::InstId arg_id,
  608. SemIR::TypeId dest_type_id)
  609. -> SemIR::ConstantId {
  610. auto arg = context.insts().GetAs<SemIR::IntValue>(arg_id);
  611. auto arg_val = context.ints().Get(arg.int_id);
  612. auto [is_signed, bit_width_id] =
  613. context.sem_ir().GetIntTypeInfo(dest_type_id);
  614. auto width = bit_width_id.is_valid()
  615. ? context.ints().Get(bit_width_id).getZExtValue()
  616. : arg_val.getBitWidth();
  617. if (!is_signed && arg_val.isNegative()) {
  618. CARBON_DIAGNOSTIC(
  619. NegativeIntInUnsignedType, Error,
  620. "negative integer value {0} converted to unsigned type {1}", TypedInt,
  621. SemIR::TypeId);
  622. context.emitter().Emit(loc, NegativeIntInUnsignedType,
  623. {.type = arg.type_id, .value = arg_val},
  624. dest_type_id);
  625. }
  626. unsigned arg_non_sign_bits = arg_val.getSignificantBits() - 1;
  627. if (arg_non_sign_bits + is_signed > width) {
  628. CARBON_DIAGNOSTIC(IntTooLargeForType, Error,
  629. "integer value {0} too large for type {1}", TypedInt,
  630. SemIR::TypeId);
  631. context.emitter().Emit(loc, IntTooLargeForType,
  632. {.type = arg.type_id, .value = arg_val},
  633. dest_type_id);
  634. }
  635. return MakeConstantResult(
  636. context, SemIR::IntValue{.type_id = dest_type_id, .int_id = arg.int_id},
  637. Phase::Template);
  638. }
  639. // Issues a diagnostic for a compile-time division by zero.
  640. static auto DiagnoseDivisionByZero(Context& context, SemIRLoc loc) -> void {
  641. CARBON_DIAGNOSTIC(CompileTimeDivisionByZero, Error, "division by zero");
  642. context.emitter().Emit(loc, CompileTimeDivisionByZero);
  643. }
  644. // Performs a builtin unary integer -> integer operation.
  645. static auto PerformBuiltinUnaryIntOp(Context& context, SemIRLoc loc,
  646. SemIR::BuiltinFunctionKind builtin_kind,
  647. SemIR::InstId arg_id)
  648. -> SemIR::ConstantId {
  649. auto op = context.insts().GetAs<SemIR::IntValue>(arg_id);
  650. auto [is_signed, bit_width_id] = context.sem_ir().GetIntTypeInfo(op.type_id);
  651. CARBON_CHECK(bit_width_id != IntId::Invalid,
  652. "Cannot evaluate a generic bit width integer: {0}", op);
  653. llvm::APInt op_val = context.ints().GetAtWidth(op.int_id, bit_width_id);
  654. switch (builtin_kind) {
  655. case SemIR::BuiltinFunctionKind::IntSNegate:
  656. if (is_signed && op_val.isMinSignedValue()) {
  657. CARBON_DIAGNOSTIC(CompileTimeIntegerNegateOverflow, Error,
  658. "integer overflow in negation of {0}", TypedInt);
  659. context.emitter().Emit(loc, CompileTimeIntegerNegateOverflow,
  660. {.type = op.type_id, .value = op_val});
  661. }
  662. op_val.negate();
  663. break;
  664. case SemIR::BuiltinFunctionKind::IntUNegate:
  665. op_val.negate();
  666. break;
  667. case SemIR::BuiltinFunctionKind::IntComplement:
  668. op_val.flipAllBits();
  669. break;
  670. default:
  671. CARBON_FATAL("Unexpected builtin kind");
  672. }
  673. return MakeIntResult(context, op.type_id, is_signed, std::move(op_val));
  674. }
  675. // Performs a builtin binary integer -> integer operation.
  676. static auto PerformBuiltinBinaryIntOp(Context& context, SemIRLoc loc,
  677. SemIR::BuiltinFunctionKind builtin_kind,
  678. SemIR::InstId lhs_id,
  679. SemIR::InstId rhs_id)
  680. -> SemIR::ConstantId {
  681. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  682. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  683. // Check for division by zero.
  684. switch (builtin_kind) {
  685. case SemIR::BuiltinFunctionKind::IntSDiv:
  686. case SemIR::BuiltinFunctionKind::IntSMod:
  687. case SemIR::BuiltinFunctionKind::IntUDiv:
  688. case SemIR::BuiltinFunctionKind::IntUMod:
  689. if (context.ints().Get(rhs.int_id).isZero()) {
  690. DiagnoseDivisionByZero(context, loc);
  691. return SemIR::ConstantId::Error;
  692. }
  693. break;
  694. default:
  695. break;
  696. }
  697. auto [lhs_is_signed, lhs_bit_width_id] =
  698. context.sem_ir().GetIntTypeInfo(lhs.type_id);
  699. llvm::APInt lhs_val = context.ints().GetAtWidth(lhs.int_id, lhs_bit_width_id);
  700. llvm::APInt result_val;
  701. // First handle shift, which can directly use the canonical RHS and doesn't
  702. // overflow.
  703. switch (builtin_kind) {
  704. // Bit shift.
  705. case SemIR::BuiltinFunctionKind::IntLeftShift:
  706. case SemIR::BuiltinFunctionKind::IntRightShift: {
  707. const auto& rhs_orig_val = context.ints().Get(rhs.int_id);
  708. if (rhs_orig_val.uge(lhs_val.getBitWidth()) ||
  709. (rhs_orig_val.isNegative() && lhs_is_signed)) {
  710. CARBON_DIAGNOSTIC(
  711. CompileTimeShiftOutOfRange, Error,
  712. "shift distance not in range [0, {0}) in {1} {2:<<|>>} {3}",
  713. unsigned, TypedInt, BoolAsSelect, TypedInt);
  714. context.emitter().Emit(
  715. loc, CompileTimeShiftOutOfRange, lhs_val.getBitWidth(),
  716. {.type = lhs.type_id, .value = lhs_val},
  717. builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift,
  718. {.type = rhs.type_id, .value = rhs_orig_val});
  719. // TODO: Is it useful to recover by returning 0 or -1?
  720. return SemIR::ConstantId::Error;
  721. }
  722. if (builtin_kind == SemIR::BuiltinFunctionKind::IntLeftShift) {
  723. result_val = lhs_val.shl(rhs_orig_val);
  724. } else if (lhs_is_signed) {
  725. result_val = lhs_val.ashr(rhs_orig_val);
  726. } else {
  727. result_val = lhs_val.lshr(rhs_orig_val);
  728. }
  729. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  730. std::move(result_val));
  731. }
  732. default:
  733. // Break to do additional setup for other builtin kinds.
  734. break;
  735. }
  736. // Other operations are already checked to be homogeneous, so we can extend
  737. // the RHS with the LHS bit width.
  738. CARBON_CHECK(rhs.type_id == lhs.type_id, "Heterogeneous builtin integer op!");
  739. llvm::APInt rhs_val = context.ints().GetAtWidth(rhs.int_id, lhs_bit_width_id);
  740. // We may also need to diagnose overflow for these operations.
  741. bool overflow = false;
  742. Lex::TokenKind op_token = Lex::TokenKind::Not;
  743. switch (builtin_kind) {
  744. // Arithmetic.
  745. case SemIR::BuiltinFunctionKind::IntSAdd:
  746. result_val = lhs_val.sadd_ov(rhs_val, overflow);
  747. op_token = Lex::TokenKind::Plus;
  748. break;
  749. case SemIR::BuiltinFunctionKind::IntSSub:
  750. result_val = lhs_val.ssub_ov(rhs_val, overflow);
  751. op_token = Lex::TokenKind::Minus;
  752. break;
  753. case SemIR::BuiltinFunctionKind::IntSMul:
  754. result_val = lhs_val.smul_ov(rhs_val, overflow);
  755. op_token = Lex::TokenKind::Star;
  756. break;
  757. case SemIR::BuiltinFunctionKind::IntSDiv:
  758. result_val = lhs_val.sdiv_ov(rhs_val, overflow);
  759. op_token = Lex::TokenKind::Slash;
  760. break;
  761. case SemIR::BuiltinFunctionKind::IntSMod:
  762. result_val = lhs_val.srem(rhs_val);
  763. // LLVM weirdly lacks `srem_ov`, so we work it out for ourselves:
  764. // <signed min> % -1 overflows because <signed min> / -1 overflows.
  765. overflow = lhs_val.isMinSignedValue() && rhs_val.isAllOnes();
  766. op_token = Lex::TokenKind::Percent;
  767. break;
  768. case SemIR::BuiltinFunctionKind::IntUAdd:
  769. result_val = lhs_val + rhs_val;
  770. op_token = Lex::TokenKind::Plus;
  771. break;
  772. case SemIR::BuiltinFunctionKind::IntUSub:
  773. result_val = lhs_val - rhs_val;
  774. op_token = Lex::TokenKind::Minus;
  775. break;
  776. case SemIR::BuiltinFunctionKind::IntUMul:
  777. result_val = lhs_val * rhs_val;
  778. op_token = Lex::TokenKind::Star;
  779. break;
  780. case SemIR::BuiltinFunctionKind::IntUDiv:
  781. result_val = lhs_val.udiv(rhs_val);
  782. op_token = Lex::TokenKind::Slash;
  783. break;
  784. case SemIR::BuiltinFunctionKind::IntUMod:
  785. result_val = lhs_val.urem(rhs_val);
  786. op_token = Lex::TokenKind::Percent;
  787. break;
  788. // Bitwise.
  789. case SemIR::BuiltinFunctionKind::IntAnd:
  790. result_val = lhs_val & rhs_val;
  791. op_token = Lex::TokenKind::And;
  792. break;
  793. case SemIR::BuiltinFunctionKind::IntOr:
  794. result_val = lhs_val | rhs_val;
  795. op_token = Lex::TokenKind::Pipe;
  796. break;
  797. case SemIR::BuiltinFunctionKind::IntXor:
  798. result_val = lhs_val ^ rhs_val;
  799. op_token = Lex::TokenKind::Caret;
  800. break;
  801. case SemIR::BuiltinFunctionKind::IntLeftShift:
  802. case SemIR::BuiltinFunctionKind::IntRightShift:
  803. CARBON_FATAL("Handled specially above.");
  804. default:
  805. CARBON_FATAL("Unexpected operation kind.");
  806. }
  807. if (overflow) {
  808. CARBON_DIAGNOSTIC(CompileTimeIntegerOverflow, Error,
  809. "integer overflow in calculation {0} {1} {2}", TypedInt,
  810. Lex::TokenKind, TypedInt);
  811. context.emitter().Emit(loc, CompileTimeIntegerOverflow,
  812. {.type = lhs.type_id, .value = lhs_val}, op_token,
  813. {.type = rhs.type_id, .value = rhs_val});
  814. }
  815. return MakeIntResult(context, lhs.type_id, lhs_is_signed,
  816. std::move(result_val));
  817. }
  818. // Performs a builtin integer comparison.
  819. static auto PerformBuiltinIntComparison(Context& context,
  820. SemIR::BuiltinFunctionKind builtin_kind,
  821. SemIR::InstId lhs_id,
  822. SemIR::InstId rhs_id,
  823. SemIR::TypeId bool_type_id)
  824. -> SemIR::ConstantId {
  825. auto lhs = context.insts().GetAs<SemIR::IntValue>(lhs_id);
  826. auto rhs = context.insts().GetAs<SemIR::IntValue>(rhs_id);
  827. CARBON_CHECK(lhs.type_id == rhs.type_id,
  828. "Builtin comparison with mismatched types!");
  829. auto [is_signed, bit_width_id] = context.sem_ir().GetIntTypeInfo(lhs.type_id);
  830. CARBON_CHECK(bit_width_id != IntId::Invalid,
  831. "Cannot evaluate a generic bit width integer: {0}", lhs);
  832. llvm::APInt lhs_val = context.ints().GetAtWidth(lhs.int_id, bit_width_id);
  833. llvm::APInt rhs_val = context.ints().GetAtWidth(rhs.int_id, bit_width_id);
  834. bool result;
  835. switch (builtin_kind) {
  836. case SemIR::BuiltinFunctionKind::IntEq:
  837. result = (lhs_val == rhs_val);
  838. break;
  839. case SemIR::BuiltinFunctionKind::IntNeq:
  840. result = (lhs_val != rhs_val);
  841. break;
  842. case SemIR::BuiltinFunctionKind::IntLess:
  843. result = is_signed ? lhs_val.slt(rhs_val) : lhs_val.ult(rhs_val);
  844. break;
  845. case SemIR::BuiltinFunctionKind::IntLessEq:
  846. result = is_signed ? lhs_val.sle(rhs_val) : lhs_val.ule(rhs_val);
  847. break;
  848. case SemIR::BuiltinFunctionKind::IntGreater:
  849. result = is_signed ? lhs_val.sgt(rhs_val) : lhs_val.sgt(rhs_val);
  850. break;
  851. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  852. result = is_signed ? lhs_val.sge(rhs_val) : lhs_val.sge(rhs_val);
  853. break;
  854. default:
  855. CARBON_FATAL("Unexpected operation kind.");
  856. }
  857. return MakeBoolResult(context, bool_type_id, result);
  858. }
  859. // Performs a builtin unary float -> float operation.
  860. static auto PerformBuiltinUnaryFloatOp(Context& context,
  861. SemIR::BuiltinFunctionKind builtin_kind,
  862. SemIR::InstId arg_id)
  863. -> SemIR::ConstantId {
  864. auto op = context.insts().GetAs<SemIR::FloatLiteral>(arg_id);
  865. auto op_val = context.floats().Get(op.float_id);
  866. switch (builtin_kind) {
  867. case SemIR::BuiltinFunctionKind::FloatNegate:
  868. op_val.changeSign();
  869. break;
  870. default:
  871. CARBON_FATAL("Unexpected builtin kind");
  872. }
  873. return MakeFloatResult(context, op.type_id, std::move(op_val));
  874. }
  875. // Performs a builtin binary float -> float operation.
  876. static auto PerformBuiltinBinaryFloatOp(Context& context,
  877. SemIR::BuiltinFunctionKind builtin_kind,
  878. SemIR::InstId lhs_id,
  879. SemIR::InstId rhs_id)
  880. -> SemIR::ConstantId {
  881. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  882. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  883. auto lhs_val = context.floats().Get(lhs.float_id);
  884. auto rhs_val = context.floats().Get(rhs.float_id);
  885. llvm::APFloat result_val(lhs_val.getSemantics());
  886. switch (builtin_kind) {
  887. case SemIR::BuiltinFunctionKind::FloatAdd:
  888. result_val = lhs_val + rhs_val;
  889. break;
  890. case SemIR::BuiltinFunctionKind::FloatSub:
  891. result_val = lhs_val - rhs_val;
  892. break;
  893. case SemIR::BuiltinFunctionKind::FloatMul:
  894. result_val = lhs_val * rhs_val;
  895. break;
  896. case SemIR::BuiltinFunctionKind::FloatDiv:
  897. result_val = lhs_val / rhs_val;
  898. break;
  899. default:
  900. CARBON_FATAL("Unexpected operation kind.");
  901. }
  902. return MakeFloatResult(context, lhs.type_id, std::move(result_val));
  903. }
  904. // Performs a builtin float comparison.
  905. static auto PerformBuiltinFloatComparison(
  906. Context& context, SemIR::BuiltinFunctionKind builtin_kind,
  907. SemIR::InstId lhs_id, SemIR::InstId rhs_id, SemIR::TypeId bool_type_id)
  908. -> SemIR::ConstantId {
  909. auto lhs = context.insts().GetAs<SemIR::FloatLiteral>(lhs_id);
  910. auto rhs = context.insts().GetAs<SemIR::FloatLiteral>(rhs_id);
  911. const auto& lhs_val = context.floats().Get(lhs.float_id);
  912. const auto& rhs_val = context.floats().Get(rhs.float_id);
  913. bool result;
  914. switch (builtin_kind) {
  915. case SemIR::BuiltinFunctionKind::FloatEq:
  916. result = (lhs_val == rhs_val);
  917. break;
  918. case SemIR::BuiltinFunctionKind::FloatNeq:
  919. result = (lhs_val != rhs_val);
  920. break;
  921. case SemIR::BuiltinFunctionKind::FloatLess:
  922. result = lhs_val < rhs_val;
  923. break;
  924. case SemIR::BuiltinFunctionKind::FloatLessEq:
  925. result = lhs_val <= rhs_val;
  926. break;
  927. case SemIR::BuiltinFunctionKind::FloatGreater:
  928. result = lhs_val > rhs_val;
  929. break;
  930. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  931. result = lhs_val >= rhs_val;
  932. break;
  933. default:
  934. CARBON_FATAL("Unexpected operation kind.");
  935. }
  936. return MakeBoolResult(context, bool_type_id, result);
  937. }
  938. // Returns a constant for a call to a builtin function.
  939. static auto MakeConstantForBuiltinCall(Context& context, SemIRLoc loc,
  940. SemIR::Call call,
  941. SemIR::BuiltinFunctionKind builtin_kind,
  942. llvm::ArrayRef<SemIR::InstId> arg_ids,
  943. Phase phase) -> SemIR::ConstantId {
  944. switch (builtin_kind) {
  945. case SemIR::BuiltinFunctionKind::None:
  946. CARBON_FATAL("Not a builtin function.");
  947. case SemIR::BuiltinFunctionKind::PrintInt: {
  948. // Providing a constant result would allow eliding the function call.
  949. return SemIR::ConstantId::NotConstant;
  950. }
  951. case SemIR::BuiltinFunctionKind::IntLiteralMakeType: {
  952. return context.constant_values().Get(
  953. SemIR::InstId::BuiltinIntLiteralType);
  954. }
  955. case SemIR::BuiltinFunctionKind::IntMakeType32: {
  956. return context.constant_values().Get(SemIR::InstId::BuiltinIntType);
  957. }
  958. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned: {
  959. return MakeIntTypeResult(context, loc, SemIR::IntKind::Signed, arg_ids[0],
  960. phase);
  961. }
  962. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned: {
  963. return MakeIntTypeResult(context, loc, SemIR::IntKind::Unsigned,
  964. arg_ids[0], phase);
  965. }
  966. case SemIR::BuiltinFunctionKind::FloatMakeType: {
  967. // TODO: Support a symbolic constant width.
  968. if (phase != Phase::Template) {
  969. break;
  970. }
  971. if (!ValidateFloatBitWidth(context, loc, arg_ids[0])) {
  972. return SemIR::ConstantId::Error;
  973. }
  974. return context.constant_values().Get(SemIR::InstId::BuiltinFloatType);
  975. }
  976. case SemIR::BuiltinFunctionKind::BoolMakeType: {
  977. return context.constant_values().Get(SemIR::InstId::BuiltinBoolType);
  978. }
  979. // Integer conversions.
  980. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  981. if (phase == Phase::Symbolic) {
  982. return MakeConstantResult(context, call, phase);
  983. }
  984. return PerformCheckedIntConvert(context, loc, arg_ids[0], call.type_id);
  985. }
  986. // Unary integer -> integer operations.
  987. case SemIR::BuiltinFunctionKind::IntSNegate:
  988. case SemIR::BuiltinFunctionKind::IntUNegate:
  989. case SemIR::BuiltinFunctionKind::IntComplement: {
  990. if (phase != Phase::Template) {
  991. break;
  992. }
  993. return PerformBuiltinUnaryIntOp(context, loc, builtin_kind, arg_ids[0]);
  994. }
  995. // Binary integer -> integer operations.
  996. case SemIR::BuiltinFunctionKind::IntSAdd:
  997. case SemIR::BuiltinFunctionKind::IntSSub:
  998. case SemIR::BuiltinFunctionKind::IntSMul:
  999. case SemIR::BuiltinFunctionKind::IntSDiv:
  1000. case SemIR::BuiltinFunctionKind::IntSMod:
  1001. case SemIR::BuiltinFunctionKind::IntUAdd:
  1002. case SemIR::BuiltinFunctionKind::IntUSub:
  1003. case SemIR::BuiltinFunctionKind::IntUMul:
  1004. case SemIR::BuiltinFunctionKind::IntUDiv:
  1005. case SemIR::BuiltinFunctionKind::IntUMod:
  1006. case SemIR::BuiltinFunctionKind::IntAnd:
  1007. case SemIR::BuiltinFunctionKind::IntOr:
  1008. case SemIR::BuiltinFunctionKind::IntXor:
  1009. case SemIR::BuiltinFunctionKind::IntLeftShift:
  1010. case SemIR::BuiltinFunctionKind::IntRightShift: {
  1011. if (phase != Phase::Template) {
  1012. break;
  1013. }
  1014. return PerformBuiltinBinaryIntOp(context, loc, builtin_kind, arg_ids[0],
  1015. arg_ids[1]);
  1016. }
  1017. // Integer comparisons.
  1018. case SemIR::BuiltinFunctionKind::IntEq:
  1019. case SemIR::BuiltinFunctionKind::IntNeq:
  1020. case SemIR::BuiltinFunctionKind::IntLess:
  1021. case SemIR::BuiltinFunctionKind::IntLessEq:
  1022. case SemIR::BuiltinFunctionKind::IntGreater:
  1023. case SemIR::BuiltinFunctionKind::IntGreaterEq: {
  1024. if (phase != Phase::Template) {
  1025. break;
  1026. }
  1027. return PerformBuiltinIntComparison(context, builtin_kind, arg_ids[0],
  1028. arg_ids[1], call.type_id);
  1029. }
  1030. // Unary float -> float operations.
  1031. case SemIR::BuiltinFunctionKind::FloatNegate: {
  1032. if (phase != Phase::Template) {
  1033. break;
  1034. }
  1035. return PerformBuiltinUnaryFloatOp(context, builtin_kind, arg_ids[0]);
  1036. }
  1037. // Binary float -> float operations.
  1038. case SemIR::BuiltinFunctionKind::FloatAdd:
  1039. case SemIR::BuiltinFunctionKind::FloatSub:
  1040. case SemIR::BuiltinFunctionKind::FloatMul:
  1041. case SemIR::BuiltinFunctionKind::FloatDiv: {
  1042. if (phase != Phase::Template) {
  1043. break;
  1044. }
  1045. return PerformBuiltinBinaryFloatOp(context, builtin_kind, arg_ids[0],
  1046. arg_ids[1]);
  1047. }
  1048. // Float comparisons.
  1049. case SemIR::BuiltinFunctionKind::FloatEq:
  1050. case SemIR::BuiltinFunctionKind::FloatNeq:
  1051. case SemIR::BuiltinFunctionKind::FloatLess:
  1052. case SemIR::BuiltinFunctionKind::FloatLessEq:
  1053. case SemIR::BuiltinFunctionKind::FloatGreater:
  1054. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  1055. if (phase != Phase::Template) {
  1056. break;
  1057. }
  1058. return PerformBuiltinFloatComparison(context, builtin_kind, arg_ids[0],
  1059. arg_ids[1], call.type_id);
  1060. }
  1061. }
  1062. return SemIR::ConstantId::NotConstant;
  1063. }
  1064. // Makes a constant for a call instruction.
  1065. static auto MakeConstantForCall(EvalContext& eval_context, SemIRLoc loc,
  1066. SemIR::Call call) -> SemIR::ConstantId {
  1067. Phase phase = Phase::Template;
  1068. // A call with an invalid argument list is used to represent an erroneous
  1069. // call.
  1070. //
  1071. // TODO: Use a better representation for this.
  1072. if (call.args_id == SemIR::InstBlockId::Invalid) {
  1073. return SemIR::ConstantId::Error;
  1074. }
  1075. // Find the constant value of the callee.
  1076. bool has_constant_callee = ReplaceFieldWithConstantValue(
  1077. eval_context, &call, &SemIR::Call::callee_id, &phase);
  1078. auto callee_function =
  1079. SemIR::GetCalleeFunction(eval_context.sem_ir(), call.callee_id);
  1080. auto builtin_kind = SemIR::BuiltinFunctionKind::None;
  1081. if (callee_function.function_id.is_valid()) {
  1082. // Calls to builtins might be constant.
  1083. builtin_kind = eval_context.functions()
  1084. .Get(callee_function.function_id)
  1085. .builtin_function_kind;
  1086. if (builtin_kind == SemIR::BuiltinFunctionKind::None) {
  1087. // TODO: Eventually we'll want to treat some kinds of non-builtin
  1088. // functions as producing constants.
  1089. return SemIR::ConstantId::NotConstant;
  1090. }
  1091. } else {
  1092. // Calls to non-functions, such as calls to generic entity names, might be
  1093. // constant.
  1094. }
  1095. // Find the argument values and the return type.
  1096. bool has_constant_operands =
  1097. has_constant_callee &&
  1098. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::type_id,
  1099. &phase) &&
  1100. ReplaceFieldWithConstantValue(eval_context, &call, &SemIR::Call::args_id,
  1101. &phase);
  1102. if (phase == Phase::UnknownDueToError) {
  1103. return SemIR::ConstantId::Error;
  1104. }
  1105. // If any operand of the call is non-constant, the call is non-constant.
  1106. // TODO: Some builtin calls might allow some operands to be non-constant.
  1107. if (!has_constant_operands) {
  1108. if (builtin_kind.IsCompTimeOnly()) {
  1109. CARBON_DIAGNOSTIC(NonConstantCallToCompTimeOnlyFunction, Error,
  1110. "non-constant call to compile-time-only function");
  1111. CARBON_DIAGNOSTIC(CompTimeOnlyFunctionHere, Note,
  1112. "compile-time-only function declared here");
  1113. eval_context.emitter()
  1114. .Build(loc, NonConstantCallToCompTimeOnlyFunction)
  1115. .Note(eval_context.functions()
  1116. .Get(callee_function.function_id)
  1117. .latest_decl_id(),
  1118. CompTimeOnlyFunctionHere)
  1119. .Emit();
  1120. }
  1121. return SemIR::ConstantId::NotConstant;
  1122. }
  1123. // Handle calls to builtins.
  1124. if (builtin_kind != SemIR::BuiltinFunctionKind::None) {
  1125. return MakeConstantForBuiltinCall(
  1126. eval_context.context(), loc, call, builtin_kind,
  1127. eval_context.inst_blocks().Get(call.args_id), phase);
  1128. }
  1129. return SemIR::ConstantId::NotConstant;
  1130. }
  1131. // Creates a FacetType constant.
  1132. static auto MakeFacetTypeResult(Context& context,
  1133. const SemIR::FacetTypeInfo& info, Phase phase)
  1134. -> SemIR::ConstantId {
  1135. SemIR::FacetTypeId facet_type_id = context.facet_types().Add(info);
  1136. return MakeConstantResult(context,
  1137. SemIR::FacetType{.type_id = SemIR::TypeId::TypeType,
  1138. .facet_type_id = facet_type_id},
  1139. phase);
  1140. }
  1141. // Implementation for `TryEvalInst`, wrapping `Context` with `EvalContext`.
  1142. static auto TryEvalInstInContext(EvalContext& eval_context,
  1143. SemIR::InstId inst_id, SemIR::Inst inst)
  1144. -> SemIR::ConstantId {
  1145. // TODO: Ensure we have test coverage for each of these cases that can result
  1146. // in a constant, once those situations are all reachable.
  1147. CARBON_KIND_SWITCH(inst) {
  1148. // These cases are constants if their operands are.
  1149. case SemIR::AddrOf::Kind:
  1150. return RebuildIfFieldsAreConstant(eval_context, inst,
  1151. &SemIR::AddrOf::type_id,
  1152. &SemIR::AddrOf::lvalue_id);
  1153. case CARBON_KIND(SemIR::ArrayType array_type): {
  1154. return RebuildAndValidateIfFieldsAreConstant(
  1155. eval_context, inst,
  1156. [&](SemIR::ArrayType result) {
  1157. auto bound_id = array_type.bound_id;
  1158. auto int_bound =
  1159. eval_context.insts().TryGetAs<SemIR::IntValue>(result.bound_id);
  1160. if (!int_bound) {
  1161. // TODO: Permit symbolic array bounds. This will require fixing
  1162. // callers of `GetArrayBoundValue`.
  1163. eval_context.context().TODO(bound_id, "symbolic array bound");
  1164. return false;
  1165. }
  1166. // TODO: We should check that the size of the resulting array type
  1167. // fits in 64 bits, not just that the bound does. Should we use a
  1168. // 32-bit limit for 32-bit targets?
  1169. const auto& bound_val = eval_context.ints().Get(int_bound->int_id);
  1170. if (eval_context.types().IsSignedInt(int_bound->type_id) &&
  1171. bound_val.isNegative()) {
  1172. CARBON_DIAGNOSTIC(ArrayBoundNegative, Error,
  1173. "array bound of {0} is negative", TypedInt);
  1174. eval_context.emitter().Emit(
  1175. bound_id, ArrayBoundNegative,
  1176. {.type = int_bound->type_id, .value = bound_val});
  1177. return false;
  1178. }
  1179. if (bound_val.getActiveBits() > 64) {
  1180. CARBON_DIAGNOSTIC(ArrayBoundTooLarge, Error,
  1181. "array bound of {0} is too large", TypedInt);
  1182. eval_context.emitter().Emit(
  1183. bound_id, ArrayBoundTooLarge,
  1184. {.type = int_bound->type_id, .value = bound_val});
  1185. return false;
  1186. }
  1187. return true;
  1188. },
  1189. &SemIR::ArrayType::bound_id, &SemIR::ArrayType::element_type_id);
  1190. }
  1191. case SemIR::AssociatedEntity::Kind:
  1192. return RebuildIfFieldsAreConstant(eval_context, inst,
  1193. &SemIR::AssociatedEntity::type_id);
  1194. case SemIR::AssociatedEntityType::Kind:
  1195. return RebuildIfFieldsAreConstant(
  1196. eval_context, inst, &SemIR::AssociatedEntityType::interface_type_id,
  1197. &SemIR::AssociatedEntityType::entity_type_id);
  1198. case SemIR::BoundMethod::Kind:
  1199. return RebuildIfFieldsAreConstant(
  1200. eval_context, inst, &SemIR::BoundMethod::type_id,
  1201. &SemIR::BoundMethod::object_id, &SemIR::BoundMethod::function_id);
  1202. case SemIR::ClassType::Kind:
  1203. return RebuildIfFieldsAreConstant(eval_context, inst,
  1204. &SemIR::ClassType::specific_id);
  1205. case SemIR::CompleteTypeWitness::Kind:
  1206. return RebuildIfFieldsAreConstant(
  1207. eval_context, inst, &SemIR::CompleteTypeWitness::object_repr_id);
  1208. case SemIR::FunctionType::Kind:
  1209. return RebuildIfFieldsAreConstant(eval_context, inst,
  1210. &SemIR::FunctionType::specific_id);
  1211. case SemIR::GenericClassType::Kind:
  1212. return RebuildIfFieldsAreConstant(
  1213. eval_context, inst, &SemIR::GenericClassType::enclosing_specific_id);
  1214. case SemIR::GenericInterfaceType::Kind:
  1215. return RebuildIfFieldsAreConstant(
  1216. eval_context, inst,
  1217. &SemIR::GenericInterfaceType::enclosing_specific_id);
  1218. case SemIR::InterfaceWitness::Kind:
  1219. return RebuildIfFieldsAreConstant(eval_context, inst,
  1220. &SemIR::InterfaceWitness::elements_id);
  1221. case CARBON_KIND(SemIR::IntType int_type): {
  1222. return RebuildAndValidateIfFieldsAreConstant(
  1223. eval_context, inst,
  1224. [&](SemIR::IntType result) {
  1225. return ValidateIntType(
  1226. eval_context.context(),
  1227. inst_id.is_valid() ? inst_id : int_type.bit_width_id, result);
  1228. },
  1229. &SemIR::IntType::bit_width_id);
  1230. }
  1231. case SemIR::PointerType::Kind:
  1232. return RebuildIfFieldsAreConstant(eval_context, inst,
  1233. &SemIR::PointerType::pointee_id);
  1234. case CARBON_KIND(SemIR::FloatType float_type): {
  1235. return RebuildAndValidateIfFieldsAreConstant(
  1236. eval_context, inst,
  1237. [&](SemIR::FloatType result) {
  1238. return ValidateFloatType(eval_context.context(),
  1239. float_type.bit_width_id, result);
  1240. },
  1241. &SemIR::FloatType::bit_width_id);
  1242. }
  1243. case SemIR::SpecificFunction::Kind:
  1244. return RebuildIfFieldsAreConstant(eval_context, inst,
  1245. &SemIR::SpecificFunction::callee_id,
  1246. &SemIR::SpecificFunction::specific_id);
  1247. case SemIR::StructType::Kind:
  1248. return RebuildIfFieldsAreConstant(eval_context, inst,
  1249. &SemIR::StructType::fields_id);
  1250. case SemIR::StructValue::Kind:
  1251. return RebuildIfFieldsAreConstant(eval_context, inst,
  1252. &SemIR::StructValue::type_id,
  1253. &SemIR::StructValue::elements_id);
  1254. case SemIR::TupleType::Kind:
  1255. return RebuildIfFieldsAreConstant(eval_context, inst,
  1256. &SemIR::TupleType::elements_id);
  1257. case SemIR::TupleValue::Kind:
  1258. return RebuildIfFieldsAreConstant(eval_context, inst,
  1259. &SemIR::TupleValue::type_id,
  1260. &SemIR::TupleValue::elements_id);
  1261. case SemIR::UnboundElementType::Kind:
  1262. return RebuildIfFieldsAreConstant(
  1263. eval_context, inst, &SemIR::UnboundElementType::class_type_id,
  1264. &SemIR::UnboundElementType::element_type_id);
  1265. // Initializers evaluate to a value of the object representation.
  1266. case SemIR::ArrayInit::Kind:
  1267. // TODO: Add an `ArrayValue` to represent a constant array object
  1268. // representation instead of using a `TupleValue`.
  1269. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1270. case SemIR::ClassInit::Kind:
  1271. // TODO: Add a `ClassValue` to represent a constant class object
  1272. // representation instead of using a `StructValue`.
  1273. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1274. case SemIR::StructInit::Kind:
  1275. return RebuildInitAsValue(eval_context, inst, SemIR::StructValue::Kind);
  1276. case SemIR::TupleInit::Kind:
  1277. return RebuildInitAsValue(eval_context, inst, SemIR::TupleValue::Kind);
  1278. case SemIR::BuiltinInst::Kind:
  1279. // Builtins are always template constants.
  1280. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1281. case CARBON_KIND(SemIR::FunctionDecl fn_decl): {
  1282. return TransformIfFieldsAreConstant(
  1283. eval_context, fn_decl,
  1284. [&](SemIR::FunctionDecl result) {
  1285. return SemIR::StructValue{.type_id = result.type_id,
  1286. .elements_id = SemIR::InstBlockId::Empty};
  1287. },
  1288. &SemIR::FunctionDecl::type_id);
  1289. }
  1290. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  1291. // If the class has generic parameters, we don't produce a class type, but
  1292. // a callable whose return value is a class type.
  1293. if (eval_context.classes().Get(class_decl.class_id).has_parameters()) {
  1294. return TransformIfFieldsAreConstant(
  1295. eval_context, class_decl,
  1296. [&](SemIR::ClassDecl result) {
  1297. return SemIR::StructValue{
  1298. .type_id = result.type_id,
  1299. .elements_id = SemIR::InstBlockId::Empty};
  1300. },
  1301. &SemIR::ClassDecl::type_id);
  1302. }
  1303. // A non-generic class declaration evaluates to the class type.
  1304. return MakeConstantResult(
  1305. eval_context.context(),
  1306. SemIR::ClassType{.type_id = SemIR::TypeId::TypeType,
  1307. .class_id = class_decl.class_id,
  1308. .specific_id = SemIR::SpecificId::Invalid},
  1309. Phase::Template);
  1310. }
  1311. case CARBON_KIND(SemIR::FacetType facet_type): {
  1312. Phase phase = Phase::Template;
  1313. SemIR::FacetTypeInfo info = GetConstantFacetTypeInfo(
  1314. eval_context, facet_type.facet_type_id, &phase);
  1315. // TODO: Reuse `inst` if we can detect that nothing has changed.
  1316. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1317. }
  1318. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  1319. // If the interface has generic parameters, we don't produce an interface
  1320. // type, but a callable whose return value is an interface type.
  1321. if (eval_context.interfaces()
  1322. .Get(interface_decl.interface_id)
  1323. .has_parameters()) {
  1324. return TransformIfFieldsAreConstant(
  1325. eval_context, interface_decl,
  1326. [&](SemIR::InterfaceDecl result) {
  1327. return SemIR::StructValue{
  1328. .type_id = result.type_id,
  1329. .elements_id = SemIR::InstBlockId::Empty};
  1330. },
  1331. &SemIR::InterfaceDecl::type_id);
  1332. }
  1333. // A non-generic interface declaration evaluates to a facet type.
  1334. return MakeConstantResult(
  1335. eval_context.context(),
  1336. eval_context.context().FacetTypeFromInterface(
  1337. interface_decl.interface_id, SemIR::SpecificId::Invalid),
  1338. Phase::Template);
  1339. }
  1340. case CARBON_KIND(SemIR::SpecificConstant specific): {
  1341. // Pull the constant value out of the specific.
  1342. return SemIR::GetConstantValueInSpecific(
  1343. eval_context.sem_ir(), specific.specific_id, specific.inst_id);
  1344. }
  1345. // These cases are treated as being the unique canonical definition of the
  1346. // corresponding constant value.
  1347. // TODO: This doesn't properly handle redeclarations. Consider adding a
  1348. // corresponding `Value` inst for each of these cases, or returning the
  1349. // first declaration.
  1350. case SemIR::AssociatedConstantDecl::Kind:
  1351. case SemIR::BaseDecl::Kind:
  1352. case SemIR::FieldDecl::Kind:
  1353. case SemIR::ImplDecl::Kind:
  1354. case SemIR::Namespace::Kind:
  1355. return SemIR::ConstantId::ForTemplateConstant(inst_id);
  1356. case SemIR::BoolLiteral::Kind:
  1357. case SemIR::FloatLiteral::Kind:
  1358. case SemIR::IntValue::Kind:
  1359. case SemIR::StringLiteral::Kind:
  1360. // Promote literals to the constant block.
  1361. // TODO: Convert literals into a canonical form. Currently we can form two
  1362. // different `i32` constants with the same value if they are represented
  1363. // by `APInt`s with different bit widths.
  1364. // TODO: Can the type of an IntValue or FloatLiteral be symbolic? If so,
  1365. // we may need to rebuild.
  1366. return MakeConstantResult(eval_context.context(), inst, Phase::Template);
  1367. // The elements of a constant aggregate can be accessed.
  1368. case SemIR::ClassElementAccess::Kind:
  1369. case SemIR::InterfaceWitnessAccess::Kind:
  1370. case SemIR::StructAccess::Kind:
  1371. case SemIR::TupleAccess::Kind:
  1372. return PerformAggregateAccess(eval_context, inst);
  1373. case CARBON_KIND(SemIR::ArrayIndex index): {
  1374. return PerformArrayIndex(eval_context, index);
  1375. }
  1376. case CARBON_KIND(SemIR::Call call): {
  1377. return MakeConstantForCall(eval_context, inst_id, call);
  1378. }
  1379. // TODO: These need special handling.
  1380. case SemIR::BindValue::Kind:
  1381. case SemIR::Deref::Kind:
  1382. case SemIR::ImportRefLoaded::Kind:
  1383. case SemIR::ReturnSlot::Kind:
  1384. case SemIR::Temporary::Kind:
  1385. case SemIR::TemporaryStorage::Kind:
  1386. case SemIR::ValueAsRef::Kind:
  1387. break;
  1388. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  1389. // TODO: Disable constant evaluation of SymbolicBindingPattern once
  1390. // DeduceGenericCallArguments no longer needs implicit params to have
  1391. // constant values.
  1392. const auto& bind_name =
  1393. eval_context.entity_names().Get(bind.entity_name_id);
  1394. // If we know which specific we're evaluating within and this is an
  1395. // argument of that specific, its constant value is the corresponding
  1396. // argument value.
  1397. if (auto value =
  1398. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1399. value.is_valid()) {
  1400. return value;
  1401. }
  1402. // The constant form of a symbolic binding is an idealized form of the
  1403. // original, with no equivalent value.
  1404. bind.entity_name_id =
  1405. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1406. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1407. }
  1408. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  1409. const auto& bind_name =
  1410. eval_context.entity_names().Get(bind.entity_name_id);
  1411. // If we know which specific we're evaluating within and this is an
  1412. // argument of that specific, its constant value is the corresponding
  1413. // argument value.
  1414. if (auto value =
  1415. eval_context.GetCompileTimeBindValue(bind_name.bind_index);
  1416. value.is_valid()) {
  1417. return value;
  1418. }
  1419. // The constant form of a symbolic binding is an idealized form of the
  1420. // original, with no equivalent value.
  1421. bind.entity_name_id =
  1422. eval_context.entity_names().MakeCanonical(bind.entity_name_id);
  1423. bind.value_id = SemIR::InstId::Invalid;
  1424. return MakeConstantResult(eval_context.context(), bind, Phase::Symbolic);
  1425. }
  1426. // These semantic wrappers don't change the constant value.
  1427. case CARBON_KIND(SemIR::AsCompatible inst): {
  1428. return eval_context.GetConstantValue(inst.source_id);
  1429. }
  1430. case CARBON_KIND(SemIR::BindAlias typed_inst): {
  1431. return eval_context.GetConstantValue(typed_inst.value_id);
  1432. }
  1433. case CARBON_KIND(SemIR::ExportDecl typed_inst): {
  1434. return eval_context.GetConstantValue(typed_inst.value_id);
  1435. }
  1436. case CARBON_KIND(SemIR::NameRef typed_inst): {
  1437. return eval_context.GetConstantValue(typed_inst.value_id);
  1438. }
  1439. case CARBON_KIND(SemIR::ValueParamPattern param_pattern): {
  1440. // TODO: Treat this as a non-expression (here and in GetExprCategory)
  1441. // once generic deduction doesn't need patterns to have constant values.
  1442. return eval_context.GetConstantValue(param_pattern.subpattern_id);
  1443. }
  1444. case CARBON_KIND(SemIR::Converted typed_inst): {
  1445. return eval_context.GetConstantValue(typed_inst.result_id);
  1446. }
  1447. case CARBON_KIND(SemIR::InitializeFrom typed_inst): {
  1448. return eval_context.GetConstantValue(typed_inst.src_id);
  1449. }
  1450. case CARBON_KIND(SemIR::SpliceBlock typed_inst): {
  1451. return eval_context.GetConstantValue(typed_inst.result_id);
  1452. }
  1453. case CARBON_KIND(SemIR::ValueOfInitializer typed_inst): {
  1454. return eval_context.GetConstantValue(typed_inst.init_id);
  1455. }
  1456. case CARBON_KIND(SemIR::FacetTypeAccess typed_inst): {
  1457. // TODO: Once we start tracking the witness in the facet value, remove it
  1458. // here. For now, we model a facet value as just a type.
  1459. return eval_context.GetConstantValue(typed_inst.facet_id);
  1460. }
  1461. case CARBON_KIND(SemIR::WhereExpr typed_inst): {
  1462. Phase phase = Phase::Template;
  1463. SemIR::TypeId base_facet_type_id =
  1464. eval_context.insts().Get(typed_inst.period_self_id).type_id();
  1465. SemIR::Inst base_facet_inst =
  1466. eval_context.GetConstantValueAsInst(base_facet_type_id);
  1467. SemIR::FacetTypeInfo info = {.requirement_block_id =
  1468. SemIR::InstBlockId::Invalid};
  1469. // `where` provides that the base facet is an error, `type`, or a facet
  1470. // type.
  1471. if (auto facet_type = base_facet_inst.TryAs<SemIR::FacetType>()) {
  1472. info = GetConstantFacetTypeInfo(eval_context, facet_type->facet_type_id,
  1473. &phase);
  1474. } else if (base_facet_type_id == SemIR::TypeId::Error) {
  1475. return SemIR::ConstantId::Error;
  1476. } else {
  1477. CARBON_CHECK(base_facet_type_id == SemIR::TypeId::TypeType,
  1478. "Unexpected type_id: {0}, inst: {1}", base_facet_type_id,
  1479. base_facet_inst);
  1480. }
  1481. // TODO: Combine other requirements, and then process & canonicalize them.
  1482. info.requirement_block_id = typed_inst.requirements_id;
  1483. return MakeFacetTypeResult(eval_context.context(), info, phase);
  1484. }
  1485. // `not true` -> `false`, `not false` -> `true`.
  1486. // All other uses of unary `not` are non-constant.
  1487. case CARBON_KIND(SemIR::UnaryOperatorNot typed_inst): {
  1488. auto const_id = eval_context.GetConstantValue(typed_inst.operand_id);
  1489. auto phase = GetPhase(const_id);
  1490. if (phase == Phase::Template) {
  1491. auto value = eval_context.insts().GetAs<SemIR::BoolLiteral>(
  1492. eval_context.constant_values().GetInstId(const_id));
  1493. return MakeBoolResult(eval_context.context(), value.type_id,
  1494. !value.value.ToBool());
  1495. }
  1496. if (phase == Phase::UnknownDueToError) {
  1497. return SemIR::ConstantId::Error;
  1498. }
  1499. break;
  1500. }
  1501. // `const (const T)` evaluates to `const T`. Otherwise, `const T` evaluates
  1502. // to itself.
  1503. case CARBON_KIND(SemIR::ConstType typed_inst): {
  1504. auto phase = Phase::Template;
  1505. auto inner_id =
  1506. GetConstantValue(eval_context, typed_inst.inner_id, &phase);
  1507. if (eval_context.context().types().Is<SemIR::ConstType>(inner_id)) {
  1508. return eval_context.context().types().GetConstantId(inner_id);
  1509. }
  1510. typed_inst.inner_id = inner_id;
  1511. return MakeConstantResult(eval_context.context(), typed_inst, phase);
  1512. }
  1513. // These cases are either not expressions or not constant.
  1514. case SemIR::AdaptDecl::Kind:
  1515. case SemIR::AddrPattern::Kind:
  1516. case SemIR::Assign::Kind:
  1517. case SemIR::BindName::Kind:
  1518. case SemIR::BindingPattern::Kind:
  1519. case SemIR::BlockArg::Kind:
  1520. case SemIR::Branch::Kind:
  1521. case SemIR::BranchIf::Kind:
  1522. case SemIR::BranchWithArg::Kind:
  1523. case SemIR::ImportDecl::Kind:
  1524. case SemIR::OutParam::Kind:
  1525. case SemIR::OutParamPattern::Kind:
  1526. case SemIR::RequirementEquivalent::Kind:
  1527. case SemIR::RequirementImpls::Kind:
  1528. case SemIR::RequirementRewrite::Kind:
  1529. case SemIR::Return::Kind:
  1530. case SemIR::ReturnExpr::Kind:
  1531. case SemIR::ReturnSlotPattern::Kind:
  1532. case SemIR::StructLiteral::Kind:
  1533. case SemIR::TupleLiteral::Kind:
  1534. case SemIR::ValueParam::Kind:
  1535. case SemIR::VarStorage::Kind:
  1536. break;
  1537. case SemIR::ImportRefUnloaded::Kind:
  1538. CARBON_FATAL("ImportRefUnloaded should be loaded before TryEvalInst: {0}",
  1539. inst);
  1540. }
  1541. return SemIR::ConstantId::NotConstant;
  1542. }
  1543. auto TryEvalInst(Context& context, SemIR::InstId inst_id, SemIR::Inst inst)
  1544. -> SemIR::ConstantId {
  1545. EvalContext eval_context(context);
  1546. return TryEvalInstInContext(eval_context, inst_id, inst);
  1547. }
  1548. auto TryEvalBlockForSpecific(Context& context, SemIR::SpecificId specific_id,
  1549. SemIR::GenericInstIndex::Region region)
  1550. -> SemIR::InstBlockId {
  1551. auto generic_id = context.specifics().Get(specific_id).generic_id;
  1552. auto eval_block_id = context.generics().Get(generic_id).GetEvalBlock(region);
  1553. auto eval_block = context.inst_blocks().Get(eval_block_id);
  1554. llvm::SmallVector<SemIR::InstId> result;
  1555. result.resize(eval_block.size(), SemIR::InstId::Invalid);
  1556. EvalContext eval_context(context, specific_id,
  1557. SpecificEvalInfo{
  1558. .region = region,
  1559. .values = result,
  1560. });
  1561. for (auto [i, inst_id] : llvm::enumerate(eval_block)) {
  1562. auto const_id = TryEvalInstInContext(eval_context, inst_id,
  1563. context.insts().Get(inst_id));
  1564. result[i] = context.constant_values().GetInstId(const_id);
  1565. // TODO: If this becomes possible through monomorphization failure, produce
  1566. // a diagnostic and put `SemIR::InstId::BuiltinError` in the table entry.
  1567. CARBON_CHECK(result[i].is_valid());
  1568. }
  1569. return context.inst_blocks().Add(result);
  1570. }
  1571. } // namespace Carbon::Check