eval.cpp 135 KB

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