eval.cpp 59 KB

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