eval.cpp 118 KB

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