eval.cpp 134 KB

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