eval.cpp 134 KB

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