eval.cpp 124 KB

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