import_ref.cpp 140 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427
  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/import_ref.h"
  5. #include <optional>
  6. #include <tuple>
  7. #include <type_traits>
  8. #include <utility>
  9. #include "common/check.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/context.h"
  12. #include "toolchain/check/eval.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/inst.h"
  15. #include "toolchain/check/name_lookup.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/parse/node_ids.h"
  19. #include "toolchain/sem_ir/constant.h"
  20. #include "toolchain/sem_ir/file.h"
  21. #include "toolchain/sem_ir/ids.h"
  22. #include "toolchain/sem_ir/import_ir.h"
  23. #include "toolchain/sem_ir/inst.h"
  24. #include "toolchain/sem_ir/inst_kind.h"
  25. #include "toolchain/sem_ir/type_info.h"
  26. #include "toolchain/sem_ir/typed_insts.h"
  27. namespace Carbon::Check {
  28. // Adds the ImportIR, excluding the update to the check_ir_map.
  29. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  30. -> SemIR::ImportIRId {
  31. context.import_ir_constant_values().push_back(
  32. SemIR::ConstantValueStore(SemIR::ConstantId::None));
  33. return context.import_irs().Add(import_ir);
  34. }
  35. // Adds a special-cased IR and verifies it received the correct ID.
  36. static auto SetSpecialImportIR(Context& context, SemIR::ImportIR import_ir,
  37. SemIR::ImportIRId expected_import_ir_id)
  38. -> void {
  39. auto ir_id = SemIR::ImportIRId::None;
  40. if (import_ir.sem_ir != nullptr) {
  41. ir_id = AddImportIR(context, import_ir);
  42. } else {
  43. // We don't have a check_ir_id, so add without touching check_ir_map.
  44. ir_id = InternalAddImportIR(context, import_ir);
  45. }
  46. CARBON_CHECK(ir_id == expected_import_ir_id,
  47. "Actual ImportIRId ($0) != Expected ImportIRId ({1})", ir_id,
  48. expected_import_ir_id);
  49. }
  50. auto SetSpecialImportIRs(Context& context, SemIR::ImportIR import_ir) -> void {
  51. SetSpecialImportIR(context, import_ir, SemIR::ImportIRId::ApiForImpl);
  52. SetSpecialImportIR(context,
  53. {.decl_id = SemIR::InstId::None, .is_export = false},
  54. SemIR::ImportIRId::Cpp);
  55. }
  56. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  57. -> SemIR::ImportIRId {
  58. auto& ir_id = context.check_ir_map()[import_ir.sem_ir->check_ir_id().index];
  59. if (!ir_id.has_value()) {
  60. // Note this updates check_ir_map.
  61. ir_id = InternalAddImportIR(context, import_ir);
  62. } else if (import_ir.is_export) {
  63. // We're processing an `export import`. In case the IR was indirectly added
  64. // as a non-export, mark it as an export.
  65. context.import_irs().Get(ir_id).is_export = true;
  66. }
  67. return ir_id;
  68. }
  69. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  70. SemIR::EntityNameId entity_name_id =
  71. SemIR::EntityNameId::None) -> SemIR::InstId {
  72. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  73. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  74. .entity_name_id = entity_name_id};
  75. auto import_ref_id = AddPlaceholderInstInNoBlock(
  76. context, MakeImportedLocIdAndInst(context, import_ir_inst_id, inst));
  77. // ImportRefs have a dedicated block because this may be called during
  78. // processing where the instruction shouldn't be inserted in the current inst
  79. // block.
  80. context.imports().push_back(import_ref_id);
  81. return import_ref_id;
  82. }
  83. // Adds an import_ref instruction for an instruction that we have already loaded
  84. // from an imported IR, with a known constant value. This is useful when the
  85. // instruction has a symbolic constant value, in order to produce an instruction
  86. // that hold that symbolic constant.
  87. static auto AddLoadedImportRef(Context& context, SemIR::TypeId type_id,
  88. SemIR::ImportIRInst import_ir_inst,
  89. SemIR::ConstantId const_id) -> SemIR::InstId {
  90. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  91. SemIR::ImportRefLoaded inst = {.type_id = type_id,
  92. .import_ir_inst_id = import_ir_inst_id,
  93. .entity_name_id = SemIR::EntityNameId::None};
  94. auto inst_id = AddPlaceholderInstInNoBlock(
  95. context, MakeImportedLocIdAndInst(context, import_ir_inst_id, inst));
  96. context.imports().push_back(inst_id);
  97. context.constant_values().Set(inst_id, const_id);
  98. context.import_ir_constant_values()[import_ir_inst.ir_id().index].Set(
  99. import_ir_inst.inst_id(), const_id);
  100. return inst_id;
  101. }
  102. static auto GetCanonicalImportIRInst(Context& context,
  103. const SemIR::File* target_ir,
  104. SemIR::InstId target_inst_id)
  105. -> SemIR::ImportIRInst {
  106. auto [canonical_ir, canonical_inst_id] =
  107. GetCanonicalFileAndInstId(target_ir, target_inst_id);
  108. auto ir_id = SemIR::ImportIRId::None;
  109. if (canonical_ir != &context.sem_ir()) {
  110. // This uses AddImportIR in case it was indirectly found, which can
  111. // happen with two or more steps of exports.
  112. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::None,
  113. .is_export = false,
  114. .sem_ir = canonical_ir});
  115. }
  116. return SemIR::ImportIRInst(ir_id, canonical_inst_id);
  117. }
  118. auto GetCanonicalImportIRInst(Context& context, SemIR::InstId inst_id)
  119. -> SemIR::ImportIRInst {
  120. return GetCanonicalImportIRInst(context, &context.sem_ir(), inst_id);
  121. }
  122. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::NameId name_id,
  123. SemIR::InstId prev_id,
  124. SemIR::ImportIRInst prev_import_ir_inst,
  125. SemIR::ImportIRId new_ir_id,
  126. const SemIR::File* new_import_ir,
  127. SemIR::InstId new_inst_id) -> void {
  128. auto new_import_ir_inst =
  129. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  130. if (new_import_ir_inst == prev_import_ir_inst) {
  131. return;
  132. }
  133. auto conflict_id =
  134. AddImportRef(context, SemIR::ImportIRInst(new_ir_id, new_inst_id));
  135. // TODO: Pass the imported name location instead of the conflict id.
  136. DiagnoseDuplicateName(context, name_id, SemIR::LocId(conflict_id),
  137. SemIR::LocId(prev_id));
  138. }
  139. namespace {
  140. class ImportRefResolver;
  141. // The result of attempting to resolve an imported instruction to a constant.
  142. struct ResolveResult {
  143. // The new constant value, if known.
  144. SemIR::ConstantId const_id;
  145. // Newly created declaration whose value is being resolved, if any.
  146. SemIR::InstId decl_id = SemIR::InstId::None;
  147. // Whether resolution has been attempted once and needs to be retried.
  148. bool retry = false;
  149. // Produces a resolve result that tries resolving this instruction again. If
  150. // `const_id` is specified, then this is the end of the second phase, and the
  151. // constant value will be passed to the next resolution attempt. Otherwise,
  152. // this is the end of the first phase.
  153. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::None,
  154. SemIR::InstId decl_id = SemIR::InstId::None)
  155. -> ResolveResult {
  156. return {.const_id = const_id, .decl_id = decl_id, .retry = true};
  157. }
  158. // Produces a resolve result that provides the given constant value. Requires
  159. // that there is no new work.
  160. static auto Done(SemIR::ConstantId const_id,
  161. SemIR::InstId decl_id = SemIR::InstId::None)
  162. -> ResolveResult {
  163. return {.const_id = const_id, .decl_id = decl_id};
  164. }
  165. };
  166. } // namespace
  167. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  168. SemIR::ConstantId const_id) -> ResolveResult;
  169. namespace {
  170. // A context within which we are performing an import. Tracks information about
  171. // the source and destination. This provides a restricted interface compared to
  172. // ImportResolver: in particular, it does not have access to a work list.
  173. // Therefore code that accepts an ImportContext is unable to enqueue new work.
  174. class ImportContext {
  175. public:
  176. // A generic that we have partially imported.
  177. struct PendingGeneric {
  178. SemIR::GenericId import_id;
  179. SemIR::GenericId local_id;
  180. };
  181. // A specific that we have partially imported.
  182. struct PendingSpecific {
  183. SemIR::SpecificId import_id;
  184. SemIR::SpecificId local_id;
  185. };
  186. // `context` must not be null.
  187. explicit ImportContext(Context* context, SemIR::ImportIRId import_ir_id)
  188. : context_(context),
  189. import_ir_id_(import_ir_id),
  190. import_ir_(*context_->import_irs().Get(import_ir_id).sem_ir) {}
  191. // Returns the file we are importing from.
  192. auto import_ir() -> const SemIR::File& { return import_ir_; }
  193. // Accessors into value stores of the file we are importing from.
  194. auto import_associated_constants() -> decltype(auto) {
  195. return import_ir().associated_constants();
  196. }
  197. auto import_classes() -> decltype(auto) { return import_ir().classes(); }
  198. auto import_constant_values() -> decltype(auto) {
  199. return import_ir().constant_values();
  200. }
  201. auto import_entity_names() -> decltype(auto) {
  202. return import_ir().entity_names();
  203. }
  204. auto import_facet_types() -> decltype(auto) {
  205. return import_ir().facet_types();
  206. }
  207. auto import_functions() -> decltype(auto) { return import_ir().functions(); }
  208. auto import_generics() -> decltype(auto) { return import_ir().generics(); }
  209. auto import_identifiers() -> decltype(auto) {
  210. return import_ir().identifiers();
  211. }
  212. auto import_impls() -> decltype(auto) { return import_ir().impls(); }
  213. auto import_inst_blocks() -> decltype(auto) {
  214. return import_ir().inst_blocks();
  215. }
  216. auto import_insts() -> decltype(auto) { return import_ir().insts(); }
  217. auto import_interfaces() -> decltype(auto) {
  218. return import_ir().interfaces();
  219. }
  220. auto import_ints() -> decltype(auto) { return import_ir().ints(); }
  221. auto import_name_scopes() -> decltype(auto) {
  222. return import_ir().name_scopes();
  223. }
  224. auto import_specifics() -> decltype(auto) { return import_ir().specifics(); }
  225. auto import_specific_interfaces() -> decltype(auto) {
  226. return import_ir().specific_interfaces();
  227. }
  228. auto import_string_literal_values() -> decltype(auto) {
  229. return import_ir().string_literal_values();
  230. }
  231. auto import_struct_type_fields() -> decltype(auto) {
  232. return import_ir().struct_type_fields();
  233. }
  234. auto import_types() -> decltype(auto) { return import_ir().types(); }
  235. // Returns the local file's import ID for the IR we are importing from.
  236. auto import_ir_id() -> SemIR::ImportIRId { return import_ir_id_; }
  237. // A value store for local constant values of imported instructions. This maps
  238. // from `InstId`s in the import IR to corresponding `ConstantId`s in the local
  239. // IR.
  240. auto local_constant_values_for_import_insts() -> decltype(auto) {
  241. return local_context().import_ir_constant_values()[import_ir_id_.index];
  242. }
  243. // Returns the file we are importing into.
  244. auto local_ir() -> SemIR::File& { return context_->sem_ir(); }
  245. // Returns the type-checking context we are importing into.
  246. auto local_context() -> Context& { return *context_; }
  247. // Accessors into value stores of the file we are importing into.
  248. auto local_associated_constants() -> decltype(auto) {
  249. return local_ir().associated_constants();
  250. }
  251. auto local_classes() -> decltype(auto) { return local_ir().classes(); }
  252. auto local_constant_values() -> decltype(auto) {
  253. return local_ir().constant_values();
  254. }
  255. auto local_entity_names() -> decltype(auto) {
  256. return local_ir().entity_names();
  257. }
  258. auto local_facet_types() -> decltype(auto) {
  259. return local_ir().facet_types();
  260. }
  261. auto local_functions() -> decltype(auto) { return local_ir().functions(); }
  262. auto local_generics() -> decltype(auto) { return local_ir().generics(); }
  263. auto local_identifiers() -> decltype(auto) {
  264. return local_ir().identifiers();
  265. }
  266. auto local_impls() -> decltype(auto) { return local_ir().impls(); }
  267. auto local_import_ir_insts() -> decltype(auto) {
  268. return local_ir().import_ir_insts();
  269. }
  270. auto local_inst_blocks() -> decltype(auto) {
  271. return local_ir().inst_blocks();
  272. }
  273. auto local_insts() -> decltype(auto) { return local_ir().insts(); }
  274. auto local_interfaces() -> decltype(auto) { return local_ir().interfaces(); }
  275. auto local_ints() -> decltype(auto) { return local_ir().ints(); }
  276. auto local_name_scopes() -> decltype(auto) {
  277. return local_ir().name_scopes();
  278. }
  279. auto local_specifics() -> decltype(auto) { return local_ir().specifics(); }
  280. auto local_specific_interfaces() -> decltype(auto) {
  281. return local_ir().specific_interfaces();
  282. }
  283. auto local_string_literal_values() -> decltype(auto) {
  284. return local_ir().string_literal_values();
  285. }
  286. auto local_struct_type_fields() -> decltype(auto) {
  287. return local_ir().struct_type_fields();
  288. }
  289. auto local_types() -> decltype(auto) { return local_ir().types(); }
  290. // Add a generic that has been partially imported but needs to be finished.
  291. auto AddPendingGeneric(PendingGeneric pending) -> void {
  292. pending_generics_.push_back(pending);
  293. }
  294. // Add a specific that has been partially imported but needs to be finished.
  295. auto AddPendingSpecific(PendingSpecific pending) -> void {
  296. pending_specifics_.push_back(pending);
  297. }
  298. protected:
  299. auto pending_generics() -> llvm::SmallVector<PendingGeneric>& {
  300. return pending_generics_;
  301. }
  302. auto pending_specifics() -> llvm::SmallVector<PendingSpecific>& {
  303. return pending_specifics_;
  304. }
  305. private:
  306. Context* context_;
  307. SemIR::ImportIRId import_ir_id_;
  308. const SemIR::File& import_ir_;
  309. // TODO: The following members don't belong here. This pending work mechanism
  310. // can probably be removed entirely if we stop importing generic eval blocks
  311. // and instead evaluate them directly in the imported IR.
  312. // Generics that we have partially imported but not yet finished importing.
  313. llvm::SmallVector<PendingGeneric> pending_generics_;
  314. // Specifics that we have partially imported but not yet finished importing.
  315. llvm::SmallVector<PendingSpecific> pending_specifics_;
  316. };
  317. // Resolves an instruction from an imported IR into a constant referring to the
  318. // current IR.
  319. //
  320. // Calling Resolve on an instruction operates in an iterative manner, tracking
  321. // Work items on work_stack_. At a high level, the loop is:
  322. //
  323. // 1. If a constant value is already known for the work item and was not set by
  324. // this work item, it's considered resolved.
  325. // - The constant check avoids performance costs of deduplication on add.
  326. // - If we've processed this work item before, then we now process it again.
  327. // It didn't complete last time, even though we have a constant value
  328. // already.
  329. //
  330. // 2. Resolve the instruction (TryResolveInst/TryResolveTypedInst). This is done
  331. // in three phases. The first and second phases can add work to the worklist
  332. // and end in a retry, in which case those phases will be rerun once the
  333. // added work is done. The rerun cannot also end in a retry, so this results
  334. // in at most three calls, but in practice one or two calls is almost always
  335. // sufficient. Due to the chance of a second or third call to TryResolveInst,
  336. // it's important to only perform expensive work once, even when the same
  337. // phase is rerun.
  338. //
  339. // - First phase:
  340. // - Gather all input constants necessary to form the constant value of the
  341. // instruction. Gathering constants directly adds unresolved values to
  342. // work_stack_.
  343. // - If HasNewWork() reports that any work was added, then return Retry():
  344. // this instruction needs another call to complete. Gather the
  345. // now-resolved constants and continue to the next step once the retry
  346. // happens.
  347. //
  348. // - Second phase:
  349. // - Build the constant value of the instruction.
  350. // - Gather all input constants necessary to finish importing the
  351. // instruction. This is only necessary for instructions like classes that
  352. // can be forward-declared. For these instructions, we first import the
  353. // constant value and then later import the rest of the declaration in
  354. // order to break cycles.
  355. // - If HasNewWork() reports that any work was added, then return
  356. // Retry(constant_value): this instruction needs another call to
  357. // complete. Gather the now-resolved constants and continue to the next
  358. // step once the retry happens.
  359. //
  360. // - Third phase:
  361. // - After the second phase, the constant value for the instruction is
  362. // already set, and will be passed back into TryResolve*Inst on retry. It
  363. // should not be created again.
  364. // - Fill in any remaining information to complete the import of the
  365. // instruction. For example, when importing a class declaration, build
  366. // the class scope and information about the definition.
  367. // - Return Done() to finish the resolution process. This will cause the
  368. // Resolve loop to set a constant value if we didn't retry at the end of
  369. // the second phase.
  370. //
  371. // In the common case where the second phase cannot add new work (because the
  372. // inst doesn't represent a declaration of an entity that can be forward
  373. // declared), the second and third phases are usually expressed as a call to
  374. // ResolveAsDeduplicated or ResolveAsUnique.
  375. //
  376. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  377. // remain, and may no longer be at the top of the stack; update the state of
  378. // the work item to track what work still needs to be done.
  379. //
  380. // The same instruction can be enqueued for resolution multiple times. However,
  381. // we will only reach the second phase once: once a constant value is set, only
  382. // the resolution step that set it will retry.
  383. //
  384. // TODO: Fix class `extern` handling and merging, rewrite tests.
  385. // - check/testdata/class/cross_package_import.carbon
  386. // - check/testdata/class/extern.carbon
  387. // TODO: Fix function `extern` handling and merging, rewrite tests.
  388. // - check/testdata/function/declaration/import.carbon
  389. // - check/testdata/packages/cross_package_import.carbon
  390. class ImportRefResolver : public ImportContext {
  391. public:
  392. // `context` must not be null.
  393. explicit ImportRefResolver(Context* context, SemIR::ImportIRId import_ir_id)
  394. : ImportContext(context, import_ir_id) {}
  395. // Iteratively resolves an imported instruction's inner references until a
  396. // constant ID referencing the current IR is produced. See the class comment
  397. // for more details.
  398. auto ResolveOneInst(SemIR::InstId inst_id) -> SemIR::ConstantId {
  399. work_stack_.push_back({.inst_id = inst_id});
  400. while (!work_stack_.empty()) {
  401. auto work = work_stack_.back();
  402. CARBON_CHECK(work.inst_id.has_value());
  403. // Step 1: check for a constant value.
  404. auto existing = FindResolvedConstId(work.inst_id);
  405. if (existing.const_id.has_value() && !work.retry_with_constant_value) {
  406. work_stack_.pop_back();
  407. continue;
  408. }
  409. // Step 2: resolve the instruction.
  410. initial_work_ = work_stack_.size();
  411. auto [new_const_id, _, retry] =
  412. TryResolveInst(*this, work.inst_id, existing.const_id);
  413. CARBON_CHECK(!HasNewWork() || retry);
  414. CARBON_CHECK(
  415. !existing.const_id.has_value() || existing.const_id == new_const_id,
  416. "Constant value changed in third phase.");
  417. if (!existing.const_id.has_value()) {
  418. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  419. }
  420. // Step 3: pop or retry.
  421. if (retry) {
  422. work_stack_[initial_work_ - 1].retry_with_constant_value =
  423. new_const_id.has_value();
  424. } else {
  425. work_stack_.pop_back();
  426. }
  427. }
  428. auto constant_id =
  429. local_constant_values_for_import_insts().GetAttached(inst_id);
  430. CARBON_CHECK(constant_id.has_value());
  431. return constant_id;
  432. }
  433. // Performs resolution for one instruction and then performs all work we
  434. // deferred.
  435. // NOLINTNEXTLINE(misc-no-recursion)
  436. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  437. auto const_id = ResolveOneInst(inst_id);
  438. PerformPendingWork();
  439. return const_id;
  440. }
  441. // Wraps constant evaluation with logic to handle constants.
  442. // NOLINTNEXTLINE(misc-no-recursion)
  443. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId {
  444. return Resolve(GetInstWithConstantValue(import_ir(), import_const_id));
  445. }
  446. // Wraps constant evaluation with logic to handle types.
  447. // NOLINTNEXTLINE(misc-no-recursion)
  448. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  449. if (!import_type_id.has_value()) {
  450. return import_type_id;
  451. }
  452. auto import_type_const_id =
  453. import_ir().types().GetConstantId(import_type_id);
  454. CARBON_CHECK(import_type_const_id.has_value());
  455. if (auto import_type_inst_id = import_ir().types().GetAsTypeInstId(
  456. import_ir().constant_values().GetInstId(import_type_const_id));
  457. SemIR::IsSingletonInstId(import_type_inst_id)) {
  458. // Builtins don't require constant resolution; we can use them directly.
  459. return GetSingletonType(local_context(), import_type_inst_id);
  460. } else {
  461. return local_context().types().GetTypeIdForTypeConstantId(
  462. ResolveConstant(import_type_id.AsConstantId()));
  463. }
  464. }
  465. // Returns true if new unresolved constants were found as part of this
  466. // `Resolve` step.
  467. auto HasNewWork() -> bool {
  468. CARBON_CHECK(initial_work_ <= work_stack_.size(),
  469. "Work shouldn't decrease");
  470. return initial_work_ < work_stack_.size();
  471. }
  472. // Returns the ConstantId for an InstId. Adds unresolved constants to
  473. // work_stack_.
  474. auto GetLocalConstantValueOrPush(SemIR::InstId inst_id) -> SemIR::ConstantId {
  475. if (!inst_id.has_value()) {
  476. return SemIR::ConstantId::None;
  477. }
  478. auto const_id =
  479. local_constant_values_for_import_insts().GetAttached(inst_id);
  480. if (!const_id.has_value()) {
  481. work_stack_.push_back({.inst_id = inst_id});
  482. }
  483. return const_id;
  484. }
  485. private:
  486. // A step in work_stack_.
  487. struct Work {
  488. // The instruction to work on.
  489. SemIR::InstId inst_id;
  490. // Whether this work item set the constant value for the instruction and
  491. // requested a retry.
  492. bool retry_with_constant_value = false;
  493. };
  494. // The constant found by FindResolvedConstId.
  495. struct ResolvedConstId {
  496. // The constant for the instruction. `None` if not yet resolved.
  497. SemIR::ConstantId const_id = SemIR::ConstantId::None;
  498. // Instructions which are indirect but equivalent to the current instruction
  499. // being resolved, and should have their constant set to the same. Empty
  500. // when `const_id` has a value.
  501. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  502. };
  503. // Looks to see if an instruction has been resolved. If a constant is only
  504. // found indirectly, sets the constant for any indirect steps that don't
  505. // already have the constant. If a constant isn't found, returns the indirect
  506. // instructions so that they can have the resolved constant assigned later.
  507. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  508. ResolvedConstId result;
  509. if (auto existing_const_id =
  510. local_constant_values_for_import_insts().GetAttached(inst_id);
  511. existing_const_id.has_value()) {
  512. result.const_id = existing_const_id;
  513. return result;
  514. }
  515. const auto* cursor_ir = &import_ir();
  516. auto cursor_inst_id = inst_id;
  517. while (true) {
  518. auto import_ir_inst_id =
  519. cursor_ir->insts().GetImportSource(cursor_inst_id);
  520. if (!import_ir_inst_id.has_value()) {
  521. return result;
  522. }
  523. auto ir_inst = cursor_ir->import_ir_insts().Get(import_ir_inst_id);
  524. const auto* prev_ir = cursor_ir;
  525. auto prev_inst_id = cursor_inst_id;
  526. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id()).sem_ir;
  527. auto cursor_ir_id =
  528. AddImportIR(local_context(), {.decl_id = SemIR::InstId::None,
  529. .is_export = false,
  530. .sem_ir = cursor_ir});
  531. cursor_inst_id = ir_inst.inst_id();
  532. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id,
  533. "{0}", cursor_ir->insts().Get(cursor_inst_id));
  534. if (auto const_id = local_context()
  535. .import_ir_constant_values()[cursor_ir_id.index]
  536. .GetAttached(cursor_inst_id);
  537. const_id.has_value()) {
  538. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  539. result.const_id = const_id;
  540. result.indirect_insts.clear();
  541. return result;
  542. } else {
  543. result.indirect_insts.push_back(
  544. SemIR::ImportIRInst(cursor_ir_id, cursor_inst_id));
  545. }
  546. }
  547. }
  548. // Sets a resolved constant into the current and indirect instructions.
  549. auto SetResolvedConstId(SemIR::InstId inst_id,
  550. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  551. SemIR::ConstantId const_id) -> void {
  552. local_constant_values_for_import_insts().Set(inst_id, const_id);
  553. for (auto indirect_inst : indirect_insts) {
  554. local_context()
  555. .import_ir_constant_values()[indirect_inst.ir_id().index]
  556. .Set(indirect_inst.inst_id(), const_id);
  557. }
  558. }
  559. auto PerformPendingWork() -> void;
  560. llvm::SmallVector<Work> work_stack_;
  561. // The size of work_stack_ at the start of resolving the current instruction.
  562. size_t initial_work_ = 0;
  563. };
  564. } // namespace
  565. static auto AddImportRef(ImportContext& context, SemIR::InstId inst_id,
  566. SemIR::EntityNameId entity_name_id =
  567. SemIR::EntityNameId::None) -> SemIR::InstId {
  568. return AddImportRef(context.local_context(),
  569. SemIR::ImportIRInst(context.import_ir_id(), inst_id),
  570. entity_name_id);
  571. }
  572. static auto AddLoadedImportRef(ImportContext& context, SemIR::TypeId type_id,
  573. SemIR::InstId inst_id,
  574. SemIR::ConstantId const_id) -> SemIR::InstId {
  575. return AddLoadedImportRef(
  576. context.local_context(), type_id,
  577. SemIR::ImportIRInst(context.import_ir_id(), inst_id), const_id);
  578. }
  579. static auto AddImportIRInst(ImportContext& context, SemIR::InstId inst_id)
  580. -> SemIR::ImportIRInstId {
  581. return context.local_import_ir_insts().Add(
  582. SemIR::ImportIRInst(context.import_ir_id(), inst_id));
  583. }
  584. // Computes, sets, and returns the constant value for an instruction.
  585. static auto SetConstantValue(Context& context, SemIR::InstId inst_id,
  586. SemIR::Inst inst) -> SemIR::ConstantId {
  587. auto const_id = TryEvalInstUnsafe(context, inst_id, inst);
  588. if (const_id.is_constant()) {
  589. CARBON_VLOG_TO(context.vlog_stream(), "Constant: {0} -> {1}\n", inst,
  590. context.constant_values().GetInstId(const_id));
  591. }
  592. context.constant_values().Set(inst_id, const_id);
  593. return const_id;
  594. }
  595. // Adds an imported instruction without setting its constant value. The
  596. // instruction should later be updated by either `SetConstantValue` or
  597. // `ReplacePlaceholderImportedInst`.
  598. template <typename InstT>
  599. static auto AddPlaceholderImportedInst(ImportContext& context,
  600. SemIR::InstId import_inst_id, InstT inst)
  601. -> SemIR::InstId {
  602. auto inst_id = context.local_insts().AddInNoBlock(MakeImportedLocIdAndInst(
  603. context.local_context(), AddImportIRInst(context, import_inst_id), inst));
  604. CARBON_VLOG_TO(context.local_context().vlog_stream(),
  605. "AddPlaceholderImportedInst: {0}\n", inst);
  606. // Track the instruction in the imports block so that it's included in
  607. // formatted SemIR if it's referenced.
  608. context.local_context().imports().push_back(inst_id);
  609. return inst_id;
  610. }
  611. // Replace an imported instruction that was added by
  612. // `AddPlaceholderImportedInst` with a new instruction. Computes, sets, and
  613. // returns the new constant value.
  614. static auto ReplacePlaceholderImportedInst(ImportContext& context,
  615. SemIR::InstId inst_id,
  616. SemIR::Inst inst)
  617. -> SemIR::ConstantId {
  618. CARBON_VLOG_TO(context.local_context().vlog_stream(),
  619. "ReplaceImportedInst: {0} -> {1}\n", inst_id, inst);
  620. context.local_insts().Set(inst_id, inst);
  621. CARBON_CHECK(context.local_constant_values().Get(inst_id) ==
  622. SemIR::ConstantId::NotConstant);
  623. return SetConstantValue(context.local_context(), inst_id, inst);
  624. }
  625. // Returns the ConstantId for an InstId. Adds unresolved constants to
  626. // the resolver's work stack.
  627. static auto GetLocalConstantId(ImportRefResolver& resolver,
  628. SemIR::InstId inst_id) -> SemIR::ConstantId {
  629. return resolver.GetLocalConstantValueOrPush(inst_id);
  630. }
  631. // Returns the ConstantId for an imported ConstantId. Adds unresolved
  632. // constants to the resolver's work stack.
  633. static auto GetLocalConstantId(ImportRefResolver& resolver,
  634. SemIR::ConstantId const_id)
  635. -> SemIR::ConstantId {
  636. return GetLocalConstantId(
  637. resolver, GetInstWithConstantValue(resolver.import_ir(), const_id));
  638. }
  639. // Returns the local constant InstId for an imported InstId.
  640. static auto GetLocalConstantInstId(ImportRefResolver& resolver,
  641. SemIR::InstId inst_id) -> SemIR::InstId {
  642. auto const_id = GetLocalConstantId(resolver, inst_id);
  643. return resolver.local_constant_values().GetInstIdIfValid(const_id);
  644. }
  645. // Returns the local constant InstId for an imported InstId.
  646. static auto GetLocalTypeInstId(ImportRefResolver& resolver,
  647. SemIR::TypeInstId inst_id) -> SemIR::TypeInstId {
  648. // The input instruction is a TypeInstId, and import does not change the type
  649. // of instructions, so the result is also a valid TypeInstId.
  650. return SemIR::TypeInstId::UnsafeMake(
  651. GetLocalConstantInstId(resolver, static_cast<SemIR::InstId>(inst_id)));
  652. }
  653. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  654. // work_stack_.
  655. static auto GetLocalConstantId(ImportRefResolver& resolver,
  656. SemIR::TypeId type_id) -> SemIR::ConstantId {
  657. return GetLocalConstantId(resolver,
  658. resolver.import_types().GetConstantId(type_id));
  659. }
  660. // Translates a NameId from the import IR to a local NameId.
  661. static auto GetLocalNameId(ImportContext& context, SemIR::NameId import_name_id)
  662. -> SemIR::NameId {
  663. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.has_value()) {
  664. return SemIR::NameId::ForIdentifier(context.local_identifiers().Add(
  665. context.import_identifiers().Get(ident_id)));
  666. }
  667. return import_name_id;
  668. }
  669. // Gets the local constant values corresponding to an imported inst block.
  670. static auto GetLocalInstBlockContents(ImportRefResolver& resolver,
  671. SemIR::InstBlockId import_block_id)
  672. -> llvm::SmallVector<SemIR::InstId> {
  673. llvm::SmallVector<SemIR::InstId> inst_ids;
  674. if (!import_block_id.has_value() ||
  675. import_block_id == SemIR::InstBlockId::Empty) {
  676. return inst_ids;
  677. }
  678. // Import all the values in the block.
  679. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  680. inst_ids.reserve(import_block.size());
  681. for (auto import_inst_id : import_block) {
  682. auto const_id = GetLocalConstantId(resolver, import_inst_id);
  683. inst_ids.push_back(
  684. resolver.local_constant_values().GetInstIdIfValid(const_id));
  685. }
  686. return inst_ids;
  687. }
  688. // Gets a local canonical instruction block ID corresponding to an imported inst
  689. // block whose contents were already imported, for example by
  690. // GetLocalInstBlockContents.
  691. static auto GetLocalCanonicalInstBlockId(ImportContext& context,
  692. SemIR::InstBlockId import_block_id,
  693. llvm::ArrayRef<SemIR::InstId> contents)
  694. -> SemIR::InstBlockId {
  695. if (!import_block_id.has_value()) {
  696. return SemIR::InstBlockId::None;
  697. }
  698. return context.local_inst_blocks().AddCanonical(contents);
  699. }
  700. // Gets a local instruction block containing ImportRefs referring to the
  701. // instructions in the specified imported instruction block.
  702. static auto GetLocalImportRefInstBlock(ImportContext& context,
  703. SemIR::InstBlockId import_inst_block_id)
  704. -> SemIR::InstBlockId {
  705. llvm::SmallVector<SemIR::InstId> elements;
  706. auto import_elements = context.import_inst_blocks().Get(import_inst_block_id);
  707. elements.reserve(import_elements.size());
  708. for (auto element : import_elements) {
  709. elements.push_back(AddImportRef(context, element));
  710. }
  711. return context.local_inst_blocks().Add(elements);
  712. }
  713. // Gets an incomplete local version of an imported generic. Most fields are
  714. // set in the third phase.
  715. static auto MakeIncompleteGeneric(ImportContext& context, SemIR::InstId decl_id,
  716. SemIR::GenericId generic_id)
  717. -> SemIR::GenericId {
  718. if (!generic_id.has_value()) {
  719. return SemIR::GenericId::None;
  720. }
  721. return context.local_generics().Add(
  722. {.decl_id = decl_id,
  723. .bindings_id = SemIR::InstBlockId::None,
  724. .self_specific_id = SemIR::SpecificId::None});
  725. }
  726. namespace {
  727. // Local information associated with an imported generic.
  728. struct GenericData {
  729. // TODO: Delete `GenericData` if we still don't use it once generic import is
  730. // more stable.
  731. };
  732. } // namespace
  733. // Gets a local version of the data associated with a generic.
  734. static auto GetLocalGenericData(ImportRefResolver& /*resolver*/,
  735. SemIR::GenericId /*generic_id*/)
  736. -> GenericData {
  737. return {};
  738. }
  739. // Adds the given local generic data to the given generic.
  740. static auto SetGenericData(ImportContext& context,
  741. SemIR::GenericId import_generic_id,
  742. SemIR::GenericId new_generic_id,
  743. const GenericData& /*generic_data*/) -> void {
  744. if (!import_generic_id.has_value()) {
  745. return;
  746. }
  747. const auto& import_generic = context.import_generics().Get(import_generic_id);
  748. auto& new_generic = context.local_generics().Get(new_generic_id);
  749. new_generic.bindings_id =
  750. GetLocalImportRefInstBlock(context, import_generic.bindings_id);
  751. // Track that we need to fill in the remaining information in
  752. // FinishPendingGeneric.
  753. context.AddPendingGeneric(
  754. {.import_id = import_generic_id, .local_id = new_generic_id});
  755. }
  756. // Gets a local constant value corresponding to an imported generic ID. May
  757. // add work to the work stack and return `None`.
  758. static auto GetLocalConstantId(ImportRefResolver& resolver,
  759. SemIR::GenericId generic_id)
  760. -> SemIR::ConstantId {
  761. if (!generic_id.has_value()) {
  762. return SemIR::ConstantId::None;
  763. }
  764. auto import_decl_inst_id = resolver.import_generics().Get(generic_id).decl_id;
  765. auto import_decl_inst =
  766. resolver.import_insts().GetWithAttachedType(import_decl_inst_id);
  767. if (import_decl_inst.Is<SemIR::ImplDecl>()) {
  768. // For an impl declaration, the imported entity can be found via the
  769. // declaration.
  770. return GetLocalConstantId(resolver, import_decl_inst_id);
  771. }
  772. // For all other kinds of declaration, the imported entity can be found via
  773. // the type of the declaration.
  774. return GetLocalConstantId(resolver, import_decl_inst.type_id());
  775. }
  776. // Gets a local generic ID given the corresponding local constant ID returned
  777. // by GetLocalConstantId for the imported generic. Does not add any new work.
  778. static auto GetLocalGenericId(ImportContext& context,
  779. SemIR::ConstantId local_const_id)
  780. -> SemIR::GenericId {
  781. if (!local_const_id.has_value()) {
  782. return SemIR::GenericId::None;
  783. }
  784. auto inst = context.local_insts().Get(
  785. context.local_constant_values().GetInstId(local_const_id));
  786. CARBON_KIND_SWITCH(inst) {
  787. case CARBON_KIND(SemIR::FunctionType fn_type): {
  788. return context.local_functions().Get(fn_type.function_id).generic_id;
  789. }
  790. case CARBON_KIND(SemIR::GenericClassType class_type): {
  791. return context.local_classes().Get(class_type.class_id).generic_id;
  792. }
  793. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  794. return context.local_interfaces()
  795. .Get(interface_type.interface_id)
  796. .generic_id;
  797. }
  798. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  799. return context.local_impls().Get(impl_decl.impl_id).generic_id;
  800. }
  801. default: {
  802. CARBON_FATAL("Unexpected inst for generic declaration: {0}", inst);
  803. }
  804. }
  805. }
  806. namespace {
  807. // Local information associated with an imported specific.
  808. struct SpecificData {
  809. SemIR::ConstantId generic_const_id;
  810. llvm::SmallVector<SemIR::InstId> args;
  811. };
  812. } // namespace
  813. // Gets local information about an imported specific.
  814. static auto GetLocalSpecificData(ImportRefResolver& resolver,
  815. SemIR::SpecificId specific_id)
  816. -> SpecificData {
  817. if (!specific_id.has_value()) {
  818. return {.generic_const_id = SemIR::ConstantId::None, .args = {}};
  819. }
  820. const auto& specific = resolver.import_specifics().Get(specific_id);
  821. return {
  822. .generic_const_id = GetLocalConstantId(resolver, specific.generic_id),
  823. .args = GetLocalInstBlockContents(resolver, specific.args_id),
  824. };
  825. }
  826. // Gets a local specific whose data was already imported by
  827. // GetLocalSpecificData. Does not add any new work.
  828. static auto GetOrAddLocalSpecific(ImportContext& context,
  829. SemIR::SpecificId import_specific_id,
  830. const SpecificData& data)
  831. -> SemIR::SpecificId {
  832. if (!import_specific_id.has_value()) {
  833. return SemIR::SpecificId::None;
  834. }
  835. // Form a corresponding local specific ID.
  836. const auto& import_specific =
  837. context.import_specifics().Get(import_specific_id);
  838. auto generic_id = GetLocalGenericId(context, data.generic_const_id);
  839. auto args_id =
  840. GetLocalCanonicalInstBlockId(context, import_specific.args_id, data.args);
  841. // Get the specific.
  842. auto specific_id = context.local_specifics().GetOrAdd(generic_id, args_id);
  843. // Fill in the remaining information in FinishPendingSpecific, if necessary.
  844. auto& specific = context.local_specifics().Get(specific_id);
  845. if (!specific.decl_block_id.has_value() ||
  846. (import_specific.definition_block_id.has_value() &&
  847. !specific.definition_block_id.has_value())) {
  848. context.AddPendingSpecific(
  849. {.import_id = import_specific_id, .local_id = specific_id});
  850. }
  851. return specific_id;
  852. }
  853. namespace {
  854. struct SpecificInterfaceData {
  855. SemIR::ConstantId interface_const_id;
  856. SpecificData specific_data;
  857. };
  858. } // namespace
  859. static auto GetLocalSpecificInterfaceData(
  860. ImportRefResolver& resolver, SemIR::SpecificInterface import_interface)
  861. -> SpecificInterfaceData {
  862. SemIR::ConstantId interface_const_id = SemIR::ConstantId::None;
  863. if (import_interface.interface_id.has_value()) {
  864. interface_const_id =
  865. GetLocalConstantId(resolver, resolver.import_interfaces()
  866. .Get(import_interface.interface_id)
  867. .first_owning_decl_id);
  868. }
  869. return {.interface_const_id = interface_const_id,
  870. .specific_data =
  871. GetLocalSpecificData(resolver, import_interface.specific_id)};
  872. }
  873. static auto GetLocalSpecificInterface(
  874. ImportContext& context, SemIR::SpecificInterface import_specific_interface,
  875. SpecificInterfaceData interface_data) -> SemIR::SpecificInterface {
  876. if (!interface_data.interface_const_id.has_value()) {
  877. return SemIR::SpecificInterface::None;
  878. }
  879. // Find the corresponding interface type. For a non-generic interface,
  880. // this is the type of the interface declaration. For a generic interface,
  881. // build a interface type referencing this specialization of the generic
  882. // interface.
  883. auto interface_const_inst =
  884. context.local_insts().Get(context.local_constant_values().GetInstId(
  885. interface_data.interface_const_id));
  886. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  887. const SemIR::FacetTypeInfo& new_facet_type_info =
  888. context.local_facet_types().Get(facet_type->facet_type_id);
  889. return *new_facet_type_info.TryAsSingleInterface();
  890. } else {
  891. auto generic_interface_type =
  892. context.local_types().GetAs<SemIR::GenericInterfaceType>(
  893. interface_const_inst.type_id());
  894. auto specific_id =
  895. GetOrAddLocalSpecific(context, import_specific_interface.specific_id,
  896. interface_data.specific_data);
  897. return {generic_interface_type.interface_id, specific_id};
  898. }
  899. }
  900. static auto GetLocalNameScopeIdImpl(ImportRefResolver& resolver,
  901. SemIR::ConstantId const_id)
  902. -> SemIR::NameScopeId {
  903. if (!const_id.has_value()) {
  904. return SemIR::NameScopeId::None;
  905. }
  906. auto const_inst_id = resolver.local_constant_values().GetInstId(const_id);
  907. auto name_scope_inst = resolver.local_insts().Get(const_inst_id);
  908. CARBON_KIND_SWITCH(name_scope_inst) {
  909. case CARBON_KIND(SemIR::Namespace inst): {
  910. return inst.name_scope_id;
  911. }
  912. case CARBON_KIND(SemIR::ClassType inst): {
  913. return resolver.local_classes().Get(inst.class_id).scope_id;
  914. }
  915. case CARBON_KIND(SemIR::FacetType inst): {
  916. const SemIR::FacetTypeInfo& facet_type_info =
  917. resolver.local_facet_types().Get(inst.facet_type_id);
  918. // This is specifically the facet type produced by an interface
  919. // declaration, and so should consist of a single interface.
  920. // TODO: Will also have to handle named constraints here, once those are
  921. // implemented.
  922. auto interface = facet_type_info.TryAsSingleInterface();
  923. CARBON_CHECK(interface);
  924. return resolver.local_interfaces().Get(interface->interface_id).scope_id;
  925. }
  926. case CARBON_KIND(SemIR::ImplDecl inst): {
  927. return resolver.local_impls().Get(inst.impl_id).scope_id;
  928. }
  929. case SemIR::StructValue::Kind: {
  930. auto type_inst =
  931. resolver.local_types().GetAsInst(name_scope_inst.type_id());
  932. CARBON_KIND_SWITCH(type_inst) {
  933. case CARBON_KIND(SemIR::GenericClassType inst): {
  934. return resolver.local_classes().Get(inst.class_id).scope_id;
  935. }
  936. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  937. return resolver.local_interfaces().Get(inst.interface_id).scope_id;
  938. }
  939. default: {
  940. break;
  941. }
  942. }
  943. break;
  944. }
  945. default: {
  946. if (const_inst_id == SemIR::ErrorInst::InstId) {
  947. return SemIR::NameScopeId::None;
  948. }
  949. break;
  950. }
  951. }
  952. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  953. name_scope_inst);
  954. }
  955. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  956. // unresolved constants to the resolver's work stack.
  957. static auto GetLocalNameScopeId(ImportRefResolver& resolver,
  958. SemIR::NameScopeId name_scope_id)
  959. -> SemIR::NameScopeId {
  960. // Get the instruction that created the scope.
  961. auto [inst_id, inst] =
  962. resolver.import_name_scopes().GetInstIfValid(name_scope_id);
  963. if (!inst) {
  964. // Map scopes that aren't associated with an instruction to `None`. For now,
  965. // such scopes aren't used, and we don't have a good way to remap them.
  966. return SemIR::NameScopeId::None;
  967. }
  968. // Get the constant value for the scope.
  969. auto const_id = GetLocalConstantId(resolver, inst_id);
  970. if (!const_id.has_value()) {
  971. return SemIR::NameScopeId::None;
  972. }
  973. auto result = GetLocalNameScopeIdImpl(resolver, const_id);
  974. CARBON_CHECK(result.has_value());
  975. return result;
  976. }
  977. // Given an imported entity base, returns an incomplete, local version of it.
  978. //
  979. // Most fields are set in the third phase once they're imported. Import enough
  980. // of the parameter lists that we know whether this interface is a generic
  981. // interface and can build the right constant value for it.
  982. //
  983. // TODO: Support extern.
  984. static auto GetIncompleteLocalEntityBase(
  985. ImportContext& context, SemIR::InstId decl_id,
  986. const SemIR::EntityWithParamsBase& import_base)
  987. -> SemIR::EntityWithParamsBase {
  988. // Translate the extern_library_id if present.
  989. auto extern_library_id = SemIR::LibraryNameId::None;
  990. if (import_base.extern_library_id.has_value()) {
  991. if (import_base.extern_library_id.index >= 0) {
  992. auto val = context.import_string_literal_values().Get(
  993. import_base.extern_library_id.AsStringLiteralValueId());
  994. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  995. context.local_string_literal_values().Add(val));
  996. } else {
  997. extern_library_id = import_base.extern_library_id;
  998. }
  999. }
  1000. return {
  1001. .name_id = GetLocalNameId(context, import_base.name_id),
  1002. .parent_scope_id = SemIR::NameScopeId::None,
  1003. .generic_id =
  1004. MakeIncompleteGeneric(context, decl_id, import_base.generic_id),
  1005. .first_param_node_id = Parse::NodeId::None,
  1006. .last_param_node_id = Parse::NodeId::None,
  1007. .pattern_block_id = SemIR::InstBlockId::None,
  1008. .implicit_param_patterns_id =
  1009. import_base.implicit_param_patterns_id.has_value()
  1010. ? SemIR::InstBlockId::Empty
  1011. : SemIR::InstBlockId::None,
  1012. .param_patterns_id = import_base.param_patterns_id.has_value()
  1013. ? SemIR::InstBlockId::Empty
  1014. : SemIR::InstBlockId::None,
  1015. .is_extern = import_base.is_extern,
  1016. .extern_library_id = extern_library_id,
  1017. .non_owning_decl_id = import_base.non_owning_decl_id.has_value()
  1018. ? decl_id
  1019. : SemIR::InstId::None,
  1020. .first_owning_decl_id = import_base.first_owning_decl_id.has_value()
  1021. ? decl_id
  1022. : SemIR::InstId::None,
  1023. };
  1024. }
  1025. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  1026. // lookup.
  1027. static auto AddNameScopeImportRefs(ImportContext& context,
  1028. const SemIR::NameScope& import_scope,
  1029. SemIR::NameScope& new_scope) -> void {
  1030. for (auto entry : import_scope.entries()) {
  1031. SemIR::ScopeLookupResult result = entry.result;
  1032. if (result.is_poisoned()) {
  1033. continue;
  1034. }
  1035. auto ref_id = AddImportRef(context, result.target_inst_id());
  1036. new_scope.AddRequired({.name_id = GetLocalNameId(context, entry.name_id),
  1037. .result = SemIR::ScopeLookupResult::MakeFound(
  1038. ref_id, result.access_kind())});
  1039. }
  1040. for (auto scope_inst_id : import_scope.extended_scopes()) {
  1041. new_scope.AddExtendedScope(AddImportRef(context, scope_inst_id));
  1042. }
  1043. }
  1044. // Given a block ID for a list of associated entities of a witness, returns a
  1045. // version localized to the current IR.
  1046. static auto AddAssociatedEntities(ImportContext& context,
  1047. SemIR::NameScopeId local_name_scope_id,
  1048. SemIR::InstBlockId associated_entities_id)
  1049. -> SemIR::InstBlockId {
  1050. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  1051. return SemIR::InstBlockId::Empty;
  1052. }
  1053. auto associated_entities =
  1054. context.import_inst_blocks().Get(associated_entities_id);
  1055. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  1056. new_associated_entities.reserve(associated_entities.size());
  1057. for (auto inst_id : associated_entities) {
  1058. // Determine the name of the associated entity, by switching on its kind.
  1059. SemIR::NameId import_name_id = SemIR::NameId::None;
  1060. if (auto assoc_const_decl =
  1061. context.import_insts().TryGetAs<SemIR::AssociatedConstantDecl>(
  1062. inst_id)) {
  1063. const auto& assoc_const = context.import_associated_constants().Get(
  1064. assoc_const_decl->assoc_const_id);
  1065. import_name_id = assoc_const.name_id;
  1066. } else if (auto function_decl =
  1067. context.import_insts().TryGetAs<SemIR::FunctionDecl>(
  1068. inst_id)) {
  1069. const auto& function =
  1070. context.import_functions().Get(function_decl->function_id);
  1071. import_name_id = function.name_id;
  1072. } else if (auto import_ref =
  1073. context.import_insts().TryGetAs<SemIR::AnyImportRef>(
  1074. inst_id)) {
  1075. import_name_id =
  1076. context.import_entity_names().Get(import_ref->entity_name_id).name_id;
  1077. } else {
  1078. // We don't need `GetWithAttachedType` here because we don't access the
  1079. // type.
  1080. CARBON_FATAL("Unhandled associated entity kind: {0}",
  1081. context.import_insts().Get(inst_id).kind());
  1082. }
  1083. auto name_id = GetLocalNameId(context, import_name_id);
  1084. auto entity_name_id = context.local_entity_names().Add(
  1085. {.name_id = name_id, .parent_scope_id = local_name_scope_id});
  1086. new_associated_entities.push_back(
  1087. AddImportRef(context, inst_id, entity_name_id));
  1088. }
  1089. return context.local_inst_blocks().Add(new_associated_entities);
  1090. }
  1091. // Produces a resolve result that provides the given constant value. Retries
  1092. // instead if work has been added.
  1093. static auto RetryOrDone(ImportRefResolver& resolver, SemIR::ConstantId const_id)
  1094. -> ResolveResult {
  1095. if (resolver.HasNewWork()) {
  1096. return ResolveResult::Retry();
  1097. }
  1098. return ResolveResult::Done(const_id);
  1099. }
  1100. // Internal concept for instruction kinds that produce unique constants.
  1101. template <typename InstT>
  1102. concept HasUniqueConstantKind =
  1103. InstT::Kind.constant_kind() == SemIR::InstConstantKind::AlwaysUnique ||
  1104. InstT::Kind.constant_kind() == SemIR::InstConstantKind::ConditionalUnique;
  1105. // Adds `inst` to the local context as a deduplicated constant and returns a
  1106. // successful `ResolveResult`. Requires that there is no new work.
  1107. //
  1108. // This implements phases 2 and 3 of resolving the inst (as described above) for
  1109. // the common case where those phases are combined. Cases where that isn't
  1110. // applicable should instead use `AddPlaceholderImportedInst` and
  1111. // `ReplacePlaceholderImportedInst`.
  1112. //
  1113. // This should not be used for instructions that represent declarations, or
  1114. // other instructions with `constant_kind == InstConstantKind::Unique`, because
  1115. // they should not be deduplicated.
  1116. template <typename InstT>
  1117. requires(!HasUniqueConstantKind<InstT>)
  1118. static auto ResolveAsDeduplicated(ImportRefResolver& resolver, InstT inst)
  1119. -> ResolveResult {
  1120. CARBON_CHECK(!resolver.HasNewWork());
  1121. // AddImportedConstant produces an unattached constant, so its type must
  1122. // be unattached as well.
  1123. inst.type_id =
  1124. resolver.local_context().types().GetUnattachedType(inst.type_id);
  1125. auto const_id = AddImportedConstant(resolver.local_context(), inst);
  1126. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1127. return ResolveResult::Done(const_id);
  1128. }
  1129. // Adds `inst` to the local context as a unique constant and returns a
  1130. // successful `ResolveResult`. `import_inst_id` is the corresponding inst ID in
  1131. // the local context. Requires that there is no new work.
  1132. //
  1133. // This implements phases 2 and 3 of resolving the inst (as described above) for
  1134. // the common case where those phases are combined. Cases where that isn't
  1135. // applicable should instead use `AddPlaceholderImportedInst` and
  1136. // `ReplacePlaceholderImportedInst`.
  1137. //
  1138. // This should only be used for instructions that represent declarations, or
  1139. // other instructions with `constant_kind == InstConstantKind::Unique`, because
  1140. // it does not perform deduplication.
  1141. template <typename InstT>
  1142. requires HasUniqueConstantKind<InstT>
  1143. static auto ResolveAsUnique(ImportRefResolver& resolver,
  1144. SemIR::InstId import_inst_id, InstT inst)
  1145. -> ResolveResult {
  1146. CARBON_CHECK(!resolver.HasNewWork());
  1147. auto inst_id = AddPlaceholderImportedInst(resolver, import_inst_id, inst);
  1148. auto const_id = SetConstantValue(resolver.local_context(), inst_id, inst);
  1149. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1150. return ResolveResult::Done(const_id, inst_id);
  1151. }
  1152. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1153. SemIR::AdaptDecl inst,
  1154. SemIR::InstId import_inst_id) -> ResolveResult {
  1155. auto adapted_type_const_id = GetLocalConstantId(
  1156. resolver,
  1157. resolver.import_constant_values().GetAttached(inst.adapted_type_inst_id));
  1158. if (resolver.HasNewWork()) {
  1159. return ResolveResult::Retry();
  1160. }
  1161. auto adapted_type_inst_id = resolver.local_ir().types().GetAsTypeInstId(
  1162. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId,
  1163. inst.adapted_type_inst_id, adapted_type_const_id));
  1164. // Create a corresponding instruction to represent the declaration.
  1165. return ResolveAsUnique<SemIR::AdaptDecl>(
  1166. resolver, import_inst_id, {.adapted_type_inst_id = adapted_type_inst_id});
  1167. }
  1168. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1169. SemIR::AddrPattern inst,
  1170. SemIR::InstId import_inst_id) -> ResolveResult {
  1171. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1172. auto inner_id = GetLocalConstantInstId(resolver, inst.inner_id);
  1173. if (resolver.HasNewWork()) {
  1174. return ResolveResult::Retry();
  1175. }
  1176. return ResolveAsUnique<SemIR::AddrPattern>(
  1177. resolver, import_inst_id,
  1178. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1179. type_const_id),
  1180. .inner_id = inner_id});
  1181. }
  1182. template <typename ParamPatternT>
  1183. requires SemIR::Internal::HasInstCategory<SemIR::AnyParamPattern,
  1184. ParamPatternT>
  1185. static auto TryResolveTypedInst(ImportRefResolver& resolver, ParamPatternT inst,
  1186. SemIR::InstId import_inst_id) -> ResolveResult {
  1187. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1188. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  1189. if (resolver.HasNewWork()) {
  1190. return ResolveResult::Retry();
  1191. }
  1192. return ResolveAsUnique<ParamPatternT>(
  1193. resolver, import_inst_id,
  1194. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1195. type_const_id),
  1196. .subpattern_id = subpattern_id,
  1197. .index = inst.index});
  1198. }
  1199. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1200. SemIR::ArrayType inst) -> ResolveResult {
  1201. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1202. auto element_type_inst_id =
  1203. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  1204. auto bound_id = GetLocalConstantInstId(resolver, inst.bound_id);
  1205. if (resolver.HasNewWork()) {
  1206. return ResolveResult::Retry();
  1207. }
  1208. return ResolveAsDeduplicated<SemIR::ArrayType>(
  1209. resolver, {.type_id = SemIR::TypeType::TypeId,
  1210. .bound_id = bound_id,
  1211. .element_type_inst_id = element_type_inst_id});
  1212. }
  1213. static auto MakeAssociatedConstant(
  1214. ImportContext& context, const SemIR::AssociatedConstant& import_assoc_const,
  1215. SemIR::TypeId type_id)
  1216. -> std::pair<SemIR::AssociatedConstantId, SemIR::ConstantId> {
  1217. SemIR::AssociatedConstantDecl assoc_const_decl = {
  1218. .type_id = type_id,
  1219. .assoc_const_id = SemIR::AssociatedConstantId::None,
  1220. .decl_block_id = SemIR::InstBlockId::Empty};
  1221. auto assoc_const_decl_id = AddPlaceholderImportedInst(
  1222. context, import_assoc_const.decl_id, assoc_const_decl);
  1223. assoc_const_decl.assoc_const_id = context.local_associated_constants().Add({
  1224. .name_id = GetLocalNameId(context, import_assoc_const.name_id),
  1225. .parent_scope_id = SemIR::NameScopeId::None,
  1226. .decl_id = assoc_const_decl_id,
  1227. .generic_id = MakeIncompleteGeneric(context, import_assoc_const.decl_id,
  1228. import_assoc_const.generic_id),
  1229. .default_value_id =
  1230. import_assoc_const.default_value_id.has_value()
  1231. ? AddImportRef(context, import_assoc_const.default_value_id)
  1232. : SemIR::InstId::None,
  1233. });
  1234. // Write the associated constant ID into the AssociatedConstantDecl.
  1235. auto const_id = ReplacePlaceholderImportedInst(context, assoc_const_decl_id,
  1236. assoc_const_decl);
  1237. return {assoc_const_decl.assoc_const_id, const_id};
  1238. }
  1239. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1240. SemIR::AssociatedConstantDecl inst,
  1241. SemIR::ConstantId const_id) -> ResolveResult {
  1242. const auto& import_assoc_const =
  1243. resolver.import_associated_constants().Get(inst.assoc_const_id);
  1244. SemIR::AssociatedConstantId assoc_const_id =
  1245. SemIR::AssociatedConstantId::None;
  1246. if (!const_id.has_value()) {
  1247. // In the first phase, import the type of the associated constant.
  1248. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1249. if (resolver.HasNewWork()) {
  1250. return ResolveResult::Retry();
  1251. }
  1252. // In the second phase, create the associated constant and its declaration.
  1253. auto type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1254. type_const_id);
  1255. std::tie(assoc_const_id, const_id) =
  1256. MakeAssociatedConstant(resolver, import_assoc_const, type_id);
  1257. } else {
  1258. // In the third phase, compute the associated constant ID from the constant
  1259. // value of the declaration.
  1260. assoc_const_id =
  1261. resolver.local_insts()
  1262. .GetAs<SemIR::AssociatedConstantDecl>(
  1263. resolver.local_constant_values().GetInstId(const_id))
  1264. .assoc_const_id;
  1265. }
  1266. // Load the values to populate the entity with.
  1267. auto parent_scope_id =
  1268. GetLocalNameScopeId(resolver, import_assoc_const.parent_scope_id);
  1269. auto generic_data =
  1270. GetLocalGenericData(resolver, import_assoc_const.generic_id);
  1271. auto& new_assoc_const =
  1272. resolver.local_associated_constants().Get(assoc_const_id);
  1273. if (resolver.HasNewWork()) {
  1274. return ResolveResult::Retry(const_id, new_assoc_const.decl_id);
  1275. }
  1276. // Populate the entity.
  1277. new_assoc_const.parent_scope_id = parent_scope_id;
  1278. SetGenericData(resolver, import_assoc_const.generic_id,
  1279. new_assoc_const.generic_id, generic_data);
  1280. return ResolveResult::Done(const_id, new_assoc_const.decl_id);
  1281. }
  1282. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1283. SemIR::AssociatedEntity inst) -> ResolveResult {
  1284. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1285. if (resolver.HasNewWork()) {
  1286. return ResolveResult::Retry();
  1287. }
  1288. // Add a lazy reference to the target declaration.
  1289. auto decl_id = AddImportRef(resolver, inst.decl_id);
  1290. return ResolveAsDeduplicated<SemIR::AssociatedEntity>(
  1291. resolver,
  1292. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1293. type_const_id),
  1294. .index = inst.index,
  1295. .decl_id = decl_id});
  1296. }
  1297. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1298. SemIR::AssociatedEntityType inst)
  1299. -> ResolveResult {
  1300. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1301. auto data =
  1302. GetLocalSpecificInterfaceData(resolver, inst.GetSpecificInterface());
  1303. if (resolver.HasNewWork()) {
  1304. return ResolveResult::Retry();
  1305. }
  1306. auto specific_interface =
  1307. GetLocalSpecificInterface(resolver, inst.GetSpecificInterface(), data);
  1308. return ResolveAsDeduplicated<SemIR::AssociatedEntityType>(
  1309. resolver, {.type_id = SemIR::TypeType::TypeId,
  1310. .interface_id = specific_interface.interface_id,
  1311. .interface_specific_id = specific_interface.specific_id});
  1312. }
  1313. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1314. SemIR::BaseDecl inst,
  1315. SemIR::InstId import_inst_id) -> ResolveResult {
  1316. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1317. auto base_type_const_id = GetLocalConstantId(
  1318. resolver,
  1319. resolver.import_constant_values().GetAttached(inst.base_type_inst_id));
  1320. if (resolver.HasNewWork()) {
  1321. return ResolveResult::Retry();
  1322. }
  1323. auto base_type_inst_id = resolver.local_ir().types().GetAsTypeInstId(
  1324. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId,
  1325. inst.base_type_inst_id, base_type_const_id));
  1326. // Create a corresponding instruction to represent the declaration.
  1327. return ResolveAsUnique<SemIR::BaseDecl>(
  1328. resolver, import_inst_id,
  1329. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1330. type_const_id),
  1331. .base_type_inst_id = base_type_inst_id,
  1332. .index = inst.index});
  1333. }
  1334. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1335. SemIR::BindAlias inst) -> ResolveResult {
  1336. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1337. return RetryOrDone(resolver, value_id);
  1338. }
  1339. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1340. SemIR::BindSymbolicName inst) -> ResolveResult {
  1341. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1342. if (resolver.HasNewWork()) {
  1343. return ResolveResult::Retry();
  1344. }
  1345. const auto& import_entity_name =
  1346. resolver.import_entity_names().Get(inst.entity_name_id);
  1347. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1348. auto entity_name_id = resolver.local_entity_names().AddSymbolicBindingName(
  1349. name_id, SemIR::NameScopeId::None, import_entity_name.bind_index(),
  1350. import_entity_name.is_template);
  1351. return ResolveAsDeduplicated<SemIR::BindSymbolicName>(
  1352. resolver,
  1353. {.type_id =
  1354. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1355. .entity_name_id = entity_name_id,
  1356. .value_id = SemIR::InstId::None});
  1357. }
  1358. template <typename BindingPatternT>
  1359. requires SemIR::Internal::HasInstCategory<SemIR::AnyBindingPattern,
  1360. BindingPatternT>
  1361. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1362. BindingPatternT inst,
  1363. SemIR::InstId import_inst_id) -> ResolveResult {
  1364. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1365. const auto& import_entity_name =
  1366. resolver.import_entity_names().Get(inst.entity_name_id);
  1367. auto parent_scope_id =
  1368. GetLocalNameScopeId(resolver, import_entity_name.parent_scope_id);
  1369. if (resolver.HasNewWork()) {
  1370. return ResolveResult::Retry();
  1371. }
  1372. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1373. auto entity_name_id = resolver.local_entity_names().Add(
  1374. {.name_id = name_id,
  1375. .parent_scope_id = parent_scope_id,
  1376. .bind_index_value = import_entity_name.bind_index().index,
  1377. .is_template = import_entity_name.is_template});
  1378. return ResolveAsUnique<BindingPatternT>(
  1379. resolver, import_inst_id,
  1380. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1381. type_const_id),
  1382. .entity_name_id = entity_name_id});
  1383. }
  1384. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1385. SemIR::BoundMethod inst) -> ResolveResult {
  1386. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1387. SemIR::BoundMethodType::TypeInstId);
  1388. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1389. auto function_decl_id =
  1390. GetLocalConstantInstId(resolver, inst.function_decl_id);
  1391. if (resolver.HasNewWork()) {
  1392. return ResolveResult::Retry();
  1393. }
  1394. return ResolveAsDeduplicated<SemIR::BoundMethod>(
  1395. resolver,
  1396. {.type_id = GetSingletonType(resolver.local_context(),
  1397. SemIR::BoundMethodType::TypeInstId),
  1398. .object_id = object_id,
  1399. .function_decl_id = function_decl_id});
  1400. }
  1401. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1402. -> ResolveResult {
  1403. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1404. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1405. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1406. if (resolver.HasNewWork()) {
  1407. return ResolveResult::Retry();
  1408. }
  1409. return ResolveAsDeduplicated<SemIR::Call>(
  1410. resolver,
  1411. {.type_id =
  1412. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1413. .callee_id = callee_id,
  1414. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1415. }
  1416. static auto AddPlaceholderNameScope(ImportContext& context)
  1417. -> SemIR::NameScopeId {
  1418. return context.local_name_scopes().Add(
  1419. SemIR::InstId::None, SemIR::NameId::None, SemIR::NameScopeId::None);
  1420. }
  1421. // Makes an incomplete class. This is necessary even with classes with a
  1422. // complete declaration, because things such as `Self` may refer back to the
  1423. // type.
  1424. static auto MakeIncompleteClass(ImportContext& context,
  1425. const SemIR::Class& import_class,
  1426. SemIR::SpecificId enclosing_specific_id)
  1427. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1428. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::TypeId,
  1429. .class_id = SemIR::ClassId::None,
  1430. .decl_block_id = SemIR::InstBlockId::Empty};
  1431. auto class_decl_id = AddPlaceholderImportedInst(
  1432. context, import_class.latest_decl_id(), class_decl);
  1433. // Regardless of whether ClassDecl is a complete type, we first need an
  1434. // incomplete type so that any references have something to point at.
  1435. class_decl.class_id = context.local_classes().Add(
  1436. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1437. {.self_type_id = SemIR::TypeId::None,
  1438. .inheritance_kind = import_class.inheritance_kind,
  1439. .is_dynamic = import_class.is_dynamic,
  1440. .scope_id = import_class.is_complete()
  1441. ? AddPlaceholderNameScope(context)
  1442. : SemIR::NameScopeId::None}});
  1443. if (import_class.has_parameters()) {
  1444. class_decl.type_id = GetGenericClassType(
  1445. context.local_context(), class_decl.class_id, enclosing_specific_id);
  1446. }
  1447. // Write the class ID into the ClassDecl.
  1448. auto self_const_id =
  1449. ReplacePlaceholderImportedInst(context, class_decl_id, class_decl);
  1450. return {class_decl.class_id, self_const_id};
  1451. }
  1452. static auto InitializeNameScopeAndImportRefs(
  1453. ImportContext& context, const SemIR::NameScope& import_scope,
  1454. SemIR::NameScope& new_scope, SemIR::InstId decl_id, SemIR::NameId name_id,
  1455. SemIR::NameScopeId parent_scope_id) {
  1456. new_scope.Set(decl_id, name_id, parent_scope_id);
  1457. AddNameScopeImportRefs(context, import_scope, new_scope);
  1458. }
  1459. // Fills out the class definition for an incomplete class.
  1460. static auto AddClassDefinition(ImportContext& context,
  1461. const SemIR::Class& import_class,
  1462. SemIR::Class& new_class,
  1463. SemIR::InstId complete_type_witness_id,
  1464. SemIR::InstId base_id, SemIR::InstId adapt_id,
  1465. SemIR::InstId vtable_id) -> void {
  1466. new_class.definition_id = new_class.first_owning_decl_id;
  1467. new_class.complete_type_witness_id = complete_type_witness_id;
  1468. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1469. const auto& import_scope =
  1470. context.import_name_scopes().Get(import_class.scope_id);
  1471. // Push a block so that we can add scoped instructions to it.
  1472. context.local_context().inst_block_stack().Push();
  1473. InitializeNameScopeAndImportRefs(
  1474. context, import_scope, new_scope, new_class.first_owning_decl_id,
  1475. SemIR::NameId::None, new_class.parent_scope_id);
  1476. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1477. if (import_class.base_id.has_value()) {
  1478. new_class.base_id = base_id;
  1479. }
  1480. if (import_class.adapt_id.has_value()) {
  1481. new_class.adapt_id = adapt_id;
  1482. }
  1483. if (import_class.vtable_id.has_value()) {
  1484. new_class.vtable_id = vtable_id;
  1485. }
  1486. }
  1487. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1488. SemIR::ClassDecl inst,
  1489. SemIR::ConstantId class_const_id)
  1490. -> ResolveResult {
  1491. // TODO: The handling of interfaces repeats a lot with the handling of
  1492. // classes, and will likely also be repeated for named constraints and
  1493. // choice types. Factor out some of this functionality.
  1494. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1495. SemIR::ClassId class_id = SemIR::ClassId::None;
  1496. if (!class_const_id.has_value()) {
  1497. auto import_specific_id = SemIR::SpecificId::None;
  1498. if (auto import_generic_class_type =
  1499. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1500. inst.type_id)) {
  1501. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1502. }
  1503. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1504. if (resolver.HasNewWork()) {
  1505. // This is the end of the first phase. Don't make a new class yet if
  1506. // we already have new work.
  1507. return ResolveResult::Retry();
  1508. }
  1509. // On the second phase, create a forward declaration of the class for any
  1510. // recursive references.
  1511. auto enclosing_specific_id =
  1512. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1513. std::tie(class_id, class_const_id) =
  1514. MakeIncompleteClass(resolver, import_class, enclosing_specific_id);
  1515. } else {
  1516. // On the third phase, compute the class ID from the constant
  1517. // value of the declaration.
  1518. auto class_const_inst = resolver.local_insts().Get(
  1519. resolver.local_constant_values().GetInstId(class_const_id));
  1520. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1521. class_id = class_type->class_id;
  1522. } else {
  1523. auto generic_class_type =
  1524. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1525. class_const_inst.type_id());
  1526. class_id = generic_class_type.class_id;
  1527. }
  1528. }
  1529. // Load constants for the definition.
  1530. auto parent_scope_id =
  1531. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1532. auto implicit_param_patterns = GetLocalInstBlockContents(
  1533. resolver, import_class.implicit_param_patterns_id);
  1534. auto param_patterns =
  1535. GetLocalInstBlockContents(resolver, import_class.param_patterns_id);
  1536. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1537. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1538. auto complete_type_witness_const_id =
  1539. import_class.complete_type_witness_id.has_value()
  1540. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1541. : SemIR::ConstantId::None;
  1542. auto base_id = import_class.base_id.has_value()
  1543. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1544. : SemIR::InstId::None;
  1545. auto adapt_id = import_class.adapt_id.has_value()
  1546. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1547. : SemIR::InstId::None;
  1548. auto& new_class = resolver.local_classes().Get(class_id);
  1549. if (resolver.HasNewWork()) {
  1550. return ResolveResult::Retry(class_const_id, new_class.first_decl_id());
  1551. }
  1552. auto vtable_id = import_class.vtable_id.has_value()
  1553. ? AddImportRef(resolver, import_class.vtable_id)
  1554. : SemIR::InstId::None;
  1555. new_class.parent_scope_id = parent_scope_id;
  1556. new_class.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1557. resolver, import_class.implicit_param_patterns_id,
  1558. implicit_param_patterns);
  1559. new_class.param_patterns_id = GetLocalCanonicalInstBlockId(
  1560. resolver, import_class.param_patterns_id, param_patterns);
  1561. SetGenericData(resolver, import_class.generic_id, new_class.generic_id,
  1562. generic_data);
  1563. new_class.self_type_id =
  1564. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1565. self_const_id);
  1566. if (import_class.is_complete()) {
  1567. auto complete_type_witness_id = AddLoadedImportRef(
  1568. resolver,
  1569. GetSingletonType(resolver.local_context(),
  1570. SemIR::WitnessType::TypeInstId),
  1571. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1572. AddClassDefinition(resolver, import_class, new_class,
  1573. complete_type_witness_id, base_id, adapt_id, vtable_id);
  1574. }
  1575. return ResolveResult::Done(class_const_id, new_class.first_decl_id());
  1576. }
  1577. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1578. SemIR::ClassType inst) -> ResolveResult {
  1579. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1580. auto class_const_id = GetLocalConstantId(
  1581. resolver,
  1582. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1583. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1584. if (resolver.HasNewWork()) {
  1585. return ResolveResult::Retry();
  1586. }
  1587. // Find the corresponding class type. For a non-generic class, this is the
  1588. // type of the class declaration. For a generic class, build a class type
  1589. // referencing this specialization of the generic class.
  1590. auto class_const_inst = resolver.local_insts().Get(
  1591. resolver.local_constant_values().GetInstId(class_const_id));
  1592. if (class_const_inst.Is<SemIR::ClassType>()) {
  1593. return ResolveResult::Done(class_const_id);
  1594. } else {
  1595. auto generic_class_type =
  1596. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1597. class_const_inst.type_id());
  1598. auto specific_id =
  1599. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1600. return ResolveAsDeduplicated<SemIR::ClassType>(
  1601. resolver, {.type_id = SemIR::TypeType::TypeId,
  1602. .class_id = generic_class_type.class_id,
  1603. .specific_id = specific_id});
  1604. }
  1605. }
  1606. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1607. SemIR::CompleteTypeWitness inst)
  1608. -> ResolveResult {
  1609. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1610. SemIR::WitnessType::TypeInstId);
  1611. auto object_repr_type_inst_id =
  1612. GetLocalTypeInstId(resolver, inst.object_repr_type_inst_id);
  1613. if (resolver.HasNewWork()) {
  1614. return ResolveResult::Retry();
  1615. }
  1616. return ResolveAsDeduplicated<SemIR::CompleteTypeWitness>(
  1617. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1618. SemIR::WitnessType::TypeInstId),
  1619. .object_repr_type_inst_id = object_repr_type_inst_id});
  1620. }
  1621. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1622. SemIR::ConstType inst) -> ResolveResult {
  1623. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1624. auto inner_id = GetLocalTypeInstId(resolver, inst.inner_id);
  1625. if (resolver.HasNewWork()) {
  1626. return ResolveResult::Retry();
  1627. }
  1628. return ResolveAsDeduplicated<SemIR::ConstType>(
  1629. resolver, {.type_id = SemIR::TypeType::TypeId, .inner_id = inner_id});
  1630. }
  1631. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1632. SemIR::ExportDecl inst) -> ResolveResult {
  1633. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1634. return RetryOrDone(resolver, value_id);
  1635. }
  1636. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1637. SemIR::FieldDecl inst,
  1638. SemIR::InstId import_inst_id) -> ResolveResult {
  1639. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1640. if (resolver.HasNewWork()) {
  1641. return ResolveResult::Retry();
  1642. }
  1643. return ResolveAsUnique<SemIR::FieldDecl>(
  1644. resolver, import_inst_id,
  1645. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1646. const_id),
  1647. .name_id = GetLocalNameId(resolver, inst.name_id),
  1648. .index = inst.index});
  1649. }
  1650. // Make a declaration of a function. This is done as a separate step from
  1651. // importing the function declaration in order to resolve cycles.
  1652. static auto MakeFunctionDecl(ImportContext& context,
  1653. const SemIR::Function& import_function,
  1654. SemIR::SpecificId specific_id)
  1655. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1656. SemIR::FunctionDecl function_decl = {
  1657. .type_id = SemIR::TypeId::None,
  1658. .function_id = SemIR::FunctionId::None,
  1659. .decl_block_id = SemIR::InstBlockId::Empty};
  1660. auto function_decl_id = AddPlaceholderImportedInst(
  1661. context, import_function.first_decl_id(), function_decl);
  1662. // Start with an incomplete function.
  1663. function_decl.function_id = context.local_functions().Add(
  1664. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  1665. {.call_params_id = SemIR::InstBlockId::None,
  1666. .return_slot_pattern_id = SemIR::InstId::None,
  1667. .special_function_kind = import_function.special_function_kind,
  1668. .builtin_function_kind = import_function.builtin_function_kind}});
  1669. function_decl.type_id = GetFunctionType(
  1670. context.local_context(), function_decl.function_id, specific_id);
  1671. // Write the function ID and type into the FunctionDecl.
  1672. auto function_const_id =
  1673. ReplacePlaceholderImportedInst(context, function_decl_id, function_decl);
  1674. return {function_decl.function_id, function_const_id};
  1675. }
  1676. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1677. SemIR::FunctionDecl inst,
  1678. SemIR::ConstantId function_const_id)
  1679. -> ResolveResult {
  1680. const auto& import_function =
  1681. resolver.import_functions().Get(inst.function_id);
  1682. SemIR::FunctionId function_id = SemIR::FunctionId::None;
  1683. if (!function_const_id.has_value()) {
  1684. auto import_specific_id = resolver.import_types()
  1685. .GetAs<SemIR::FunctionType>(inst.type_id)
  1686. .specific_id;
  1687. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1688. if (resolver.HasNewWork()) {
  1689. // This is the end of the first phase. Don't make a new function yet if
  1690. // we already have new work.
  1691. return ResolveResult::Retry();
  1692. }
  1693. // On the second phase, create a forward declaration of the interface.
  1694. auto specific_id =
  1695. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1696. std::tie(function_id, function_const_id) =
  1697. MakeFunctionDecl(resolver, import_function, specific_id);
  1698. } else {
  1699. // On the third phase, compute the function ID from the constant value of
  1700. // the declaration.
  1701. auto function_const_inst = resolver.local_insts().Get(
  1702. resolver.local_constant_values().GetInstId(function_const_id));
  1703. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  1704. function_const_inst.type_id());
  1705. function_id = function_type.function_id;
  1706. }
  1707. auto return_type_const_id = SemIR::ConstantId::None;
  1708. if (import_function.return_slot_pattern_id.has_value()) {
  1709. return_type_const_id = GetLocalConstantId(
  1710. resolver, resolver.import_insts().GetAttachedType(
  1711. import_function.return_slot_pattern_id));
  1712. }
  1713. auto parent_scope_id =
  1714. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  1715. auto implicit_param_patterns = GetLocalInstBlockContents(
  1716. resolver, import_function.implicit_param_patterns_id);
  1717. auto param_patterns =
  1718. GetLocalInstBlockContents(resolver, import_function.param_patterns_id);
  1719. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  1720. auto self_param_id =
  1721. GetLocalConstantInstId(resolver, import_function.self_param_id);
  1722. auto return_slot_pattern_id =
  1723. GetLocalConstantInstId(resolver, import_function.return_slot_pattern_id);
  1724. auto& new_function = resolver.local_functions().Get(function_id);
  1725. if (resolver.HasNewWork()) {
  1726. return ResolveResult::Retry(function_const_id,
  1727. new_function.first_decl_id());
  1728. }
  1729. // Add the function declaration.
  1730. new_function.parent_scope_id = parent_scope_id;
  1731. new_function.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1732. resolver, import_function.implicit_param_patterns_id,
  1733. implicit_param_patterns);
  1734. new_function.self_param_id = self_param_id;
  1735. new_function.param_patterns_id = GetLocalCanonicalInstBlockId(
  1736. resolver, import_function.param_patterns_id, param_patterns);
  1737. new_function.return_slot_pattern_id = return_slot_pattern_id;
  1738. SetGenericData(resolver, import_function.generic_id, new_function.generic_id,
  1739. generic_data);
  1740. if (import_function.definition_id.has_value()) {
  1741. new_function.definition_id = new_function.first_owning_decl_id;
  1742. }
  1743. return ResolveResult::Done(function_const_id, new_function.first_decl_id());
  1744. }
  1745. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1746. SemIR::FunctionType inst) -> ResolveResult {
  1747. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1748. auto fn_val_id = GetLocalConstantInstId(
  1749. resolver,
  1750. resolver.import_functions().Get(inst.function_id).first_decl_id());
  1751. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1752. if (resolver.HasNewWork()) {
  1753. return ResolveResult::Retry();
  1754. }
  1755. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  1756. return ResolveAsDeduplicated<SemIR::FunctionType>(
  1757. resolver, {.type_id = SemIR::TypeType::TypeId,
  1758. .function_id = resolver.local_types()
  1759. .GetAs<SemIR::FunctionType>(fn_type_id)
  1760. .function_id,
  1761. .specific_id = GetOrAddLocalSpecific(
  1762. resolver, inst.specific_id, specific_data)});
  1763. }
  1764. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1765. SemIR::FunctionTypeWithSelfType inst)
  1766. -> ResolveResult {
  1767. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1768. auto interface_function_type_id =
  1769. GetLocalTypeInstId(resolver, inst.interface_function_type_id);
  1770. auto self_id = GetLocalConstantInstId(resolver, inst.self_id);
  1771. if (resolver.HasNewWork()) {
  1772. return ResolveResult::Retry();
  1773. }
  1774. return ResolveAsDeduplicated<SemIR::FunctionTypeWithSelfType>(
  1775. resolver, {.type_id = SemIR::TypeType::TypeId,
  1776. .interface_function_type_id = interface_function_type_id,
  1777. .self_id = self_id});
  1778. }
  1779. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1780. SemIR::GenericClassType inst) -> ResolveResult {
  1781. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1782. auto class_val_id = GetLocalConstantInstId(
  1783. resolver,
  1784. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1785. if (resolver.HasNewWork()) {
  1786. return ResolveResult::Retry();
  1787. }
  1788. auto class_val = resolver.local_insts().Get(class_val_id);
  1789. CARBON_CHECK(
  1790. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1791. return ResolveResult::Done(
  1792. resolver.local_types().GetConstantId(class_val.type_id()));
  1793. }
  1794. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1795. SemIR::GenericInterfaceType inst)
  1796. -> ResolveResult {
  1797. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1798. auto interface_val_id = GetLocalConstantInstId(
  1799. resolver,
  1800. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  1801. if (resolver.HasNewWork()) {
  1802. return ResolveResult::Retry();
  1803. }
  1804. auto interface_val = resolver.local_insts().Get(interface_val_id);
  1805. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  1806. interface_val.type_id()));
  1807. return ResolveResult::Done(
  1808. resolver.local_types().GetConstantId(interface_val.type_id()));
  1809. }
  1810. // Make a declaration of an impl. This is done as a separate step from
  1811. // importing the impl definition in order to resolve cycles.
  1812. static auto MakeImplDeclaration(ImportContext& context,
  1813. const SemIR::Impl& import_impl,
  1814. SemIR::InstId witness_id)
  1815. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  1816. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  1817. .decl_block_id = SemIR::InstBlockId::Empty};
  1818. auto impl_decl_id = AddPlaceholderImportedInst(
  1819. context, import_impl.latest_decl_id(), impl_decl);
  1820. impl_decl.impl_id = context.local_impls().Add(
  1821. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  1822. {.self_id = SemIR::TypeInstId::None,
  1823. .constraint_id = SemIR::TypeInstId::None,
  1824. .interface = SemIR::SpecificInterface::None,
  1825. .witness_id = witness_id,
  1826. .scope_id = import_impl.is_complete() ? AddPlaceholderNameScope(context)
  1827. : SemIR::NameScopeId::None,
  1828. .is_final = import_impl.is_final}});
  1829. // Write the impl ID into the ImplDecl.
  1830. auto impl_const_id =
  1831. ReplacePlaceholderImportedInst(context, impl_decl_id, impl_decl);
  1832. return {impl_decl.impl_id, impl_const_id};
  1833. }
  1834. // Imports the definition of an impl.
  1835. static auto AddImplDefinition(ImportContext& context,
  1836. const SemIR::Impl& import_impl,
  1837. SemIR::Impl& new_impl) -> void {
  1838. new_impl.definition_id = new_impl.first_owning_decl_id;
  1839. new_impl.defined = true;
  1840. if (import_impl.scope_id.has_value()) {
  1841. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  1842. new_scope.Set(new_impl.first_owning_decl_id, SemIR::NameId::None,
  1843. new_impl.parent_scope_id);
  1844. // Import the contents of the definition scope, if we might need it. Name
  1845. // lookup is never performed into this scope by a user of the impl, so
  1846. // this is only necessary in the same library that defined the impl, in
  1847. // order to support defining members of the impl out of line in the impl
  1848. // file when the impl is defined in the API file.
  1849. // TODO: Check to see if this impl is owned by the API file, rather than
  1850. // merely being imported into it.
  1851. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1852. const auto& import_scope =
  1853. context.import_name_scopes().Get(import_impl.scope_id);
  1854. // Push a block so that we can add scoped instructions to it.
  1855. context.local_context().inst_block_stack().Push();
  1856. AddNameScopeImportRefs(context, import_scope, new_scope);
  1857. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  1858. }
  1859. }
  1860. }
  1861. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1862. SemIR::ImplDecl inst,
  1863. SemIR::ConstantId impl_const_id)
  1864. -> ResolveResult {
  1865. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  1866. // functions. Factor out the commonality.
  1867. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  1868. auto specific_interface_data =
  1869. GetLocalSpecificInterfaceData(resolver, import_impl.interface);
  1870. SemIR::ImplId impl_id = SemIR::ImplId::None;
  1871. if (!impl_const_id.has_value()) {
  1872. if (resolver.HasNewWork()) {
  1873. // This is the end of the first phase. Don't make a new impl yet if we
  1874. // already have new work.
  1875. return ResolveResult::Retry();
  1876. }
  1877. // On the second phase, create a forward declaration of the impl for any
  1878. // recursive references.
  1879. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  1880. std::tie(impl_id, impl_const_id) =
  1881. MakeImplDeclaration(resolver, import_impl, witness_id);
  1882. } else {
  1883. // On the third phase, compute the impl ID from the "constant value" of
  1884. // the declaration, which is a reference to the created ImplDecl.
  1885. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  1886. resolver.local_constant_values().GetInstId(impl_const_id));
  1887. impl_id = impl_const_inst.impl_id;
  1888. }
  1889. // Load constants for the definition.
  1890. auto parent_scope_id =
  1891. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  1892. auto implicit_param_patterns = GetLocalInstBlockContents(
  1893. resolver, import_impl.implicit_param_patterns_id);
  1894. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  1895. auto self_const_id = GetLocalConstantId(
  1896. resolver,
  1897. resolver.import_constant_values().GetAttached(import_impl.self_id));
  1898. auto constraint_const_id = GetLocalConstantId(
  1899. resolver,
  1900. resolver.import_constant_values().GetAttached(import_impl.constraint_id));
  1901. auto& new_impl = resolver.local_impls().Get(impl_id);
  1902. if (resolver.HasNewWork()) {
  1903. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  1904. }
  1905. new_impl.parent_scope_id = parent_scope_id;
  1906. new_impl.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1907. resolver, import_impl.implicit_param_patterns_id,
  1908. implicit_param_patterns);
  1909. SetGenericData(resolver, import_impl.generic_id, new_impl.generic_id,
  1910. generic_data);
  1911. // Create instructions for self and constraint to hold the symbolic constant
  1912. // value for a generic impl.
  1913. new_impl.self_id = resolver.local_ir().types().GetAsTypeInstId(
  1914. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId, import_impl.self_id,
  1915. self_const_id));
  1916. new_impl.constraint_id = resolver.local_ir().types().GetAsTypeInstId(
  1917. AddLoadedImportRef(resolver, SemIR::TypeType::TypeId,
  1918. import_impl.constraint_id, constraint_const_id));
  1919. new_impl.interface = GetLocalSpecificInterface(
  1920. resolver, import_impl.interface, specific_interface_data);
  1921. if (import_impl.is_complete()) {
  1922. AddImplDefinition(resolver, import_impl, new_impl);
  1923. }
  1924. // If the `impl` is declared in the API file corresponding to the current
  1925. // file, add this to impl lookup so that it can be found by redeclarations
  1926. // in the current file.
  1927. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1928. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  1929. }
  1930. return ResolveResult::Done(impl_const_id, new_impl.first_decl_id());
  1931. }
  1932. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1933. SemIR::ImportRefLoaded /*inst*/,
  1934. SemIR::InstId inst_id) -> ResolveResult {
  1935. // Return the constant for the instruction of the imported constant.
  1936. auto constant_id = resolver.import_constant_values().Get(inst_id);
  1937. CARBON_CHECK(constant_id.has_value(),
  1938. "Loaded import ref has no constant value");
  1939. if (!constant_id.is_constant()) {
  1940. resolver.local_context().TODO(
  1941. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  1942. return ResolveResult::Done(constant_id);
  1943. }
  1944. auto new_constant_id = GetLocalConstantId(
  1945. resolver, resolver.import_constant_values().GetInstId(constant_id));
  1946. return RetryOrDone(resolver, new_constant_id);
  1947. }
  1948. // Make a declaration of an interface. This is done as a separate step from
  1949. // importing the interface definition in order to resolve cycles.
  1950. static auto MakeInterfaceDecl(ImportContext& context,
  1951. const SemIR::Interface& import_interface,
  1952. SemIR::SpecificId enclosing_specific_id)
  1953. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1954. SemIR::InterfaceDecl interface_decl = {
  1955. .type_id = SemIR::TypeType::TypeId,
  1956. .interface_id = SemIR::InterfaceId::None,
  1957. .decl_block_id = SemIR::InstBlockId::Empty};
  1958. auto interface_decl_id = AddPlaceholderImportedInst(
  1959. context, import_interface.first_owning_decl_id, interface_decl);
  1960. // Start with an incomplete interface.
  1961. interface_decl.interface_id = context.local_interfaces().Add(
  1962. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  1963. import_interface),
  1964. {.scope_id = import_interface.is_complete()
  1965. ? AddPlaceholderNameScope(context)
  1966. : SemIR::NameScopeId::None}});
  1967. if (import_interface.has_parameters()) {
  1968. interface_decl.type_id = GetGenericInterfaceType(
  1969. context.local_context(), interface_decl.interface_id,
  1970. enclosing_specific_id);
  1971. }
  1972. // Write the interface ID into the InterfaceDecl.
  1973. auto interface_const_id = ReplacePlaceholderImportedInst(
  1974. context, interface_decl_id, interface_decl);
  1975. return {interface_decl.interface_id, interface_const_id};
  1976. }
  1977. // Imports the definition for an interface that has been imported as a forward
  1978. // declaration.
  1979. static auto AddInterfaceDefinition(ImportContext& context,
  1980. const SemIR::Interface& import_interface,
  1981. SemIR::Interface& new_interface,
  1982. SemIR::InstId self_param_id) -> void {
  1983. auto& new_scope = context.local_name_scopes().Get(new_interface.scope_id);
  1984. const auto& import_scope =
  1985. context.import_name_scopes().Get(import_interface.scope_id);
  1986. // Push a block so that we can add scoped instructions to it.
  1987. context.local_context().inst_block_stack().Push();
  1988. InitializeNameScopeAndImportRefs(
  1989. context, import_scope, new_scope, new_interface.first_owning_decl_id,
  1990. SemIR::NameId::None, new_interface.parent_scope_id);
  1991. new_scope.set_is_interface_definition();
  1992. new_interface.associated_entities_id = AddAssociatedEntities(
  1993. context, new_interface.scope_id, import_interface.associated_entities_id);
  1994. new_interface.body_block_id =
  1995. context.local_context().inst_block_stack().Pop();
  1996. new_interface.self_param_id = self_param_id;
  1997. CARBON_CHECK(import_scope.extended_scopes().empty(),
  1998. "Interfaces don't currently have extended scopes to support.");
  1999. }
  2000. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2001. SemIR::InterfaceDecl inst,
  2002. SemIR::ConstantId interface_const_id)
  2003. -> ResolveResult {
  2004. const auto& import_interface =
  2005. resolver.import_interfaces().Get(inst.interface_id);
  2006. SemIR::InterfaceId interface_id = SemIR::InterfaceId::None;
  2007. if (!interface_const_id.has_value()) {
  2008. auto import_specific_id = SemIR::SpecificId::None;
  2009. if (auto import_generic_interface_type =
  2010. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  2011. inst.type_id)) {
  2012. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  2013. }
  2014. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2015. if (resolver.HasNewWork()) {
  2016. // This is the end of the first phase. Don't make a new interface yet if
  2017. // we already have new work.
  2018. return ResolveResult::Retry();
  2019. }
  2020. // On the second phase, create a forward declaration of the interface.
  2021. auto enclosing_specific_id =
  2022. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2023. std::tie(interface_id, interface_const_id) =
  2024. MakeInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  2025. } else {
  2026. // On the third phase, compute the interface ID from the constant value of
  2027. // the declaration.
  2028. auto interface_const_inst = resolver.local_insts().Get(
  2029. resolver.local_constant_values().GetInstId(interface_const_id));
  2030. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2031. const SemIR::FacetTypeInfo& facet_type_info =
  2032. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2033. auto interface_type = facet_type_info.TryAsSingleInterface();
  2034. CARBON_CHECK(interface_type);
  2035. interface_id = interface_type->interface_id;
  2036. } else {
  2037. auto generic_interface_type =
  2038. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2039. interface_const_inst.type_id());
  2040. interface_id = generic_interface_type.interface_id;
  2041. }
  2042. }
  2043. auto parent_scope_id =
  2044. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  2045. auto implicit_param_patterns = GetLocalInstBlockContents(
  2046. resolver, import_interface.implicit_param_patterns_id);
  2047. auto param_patterns =
  2048. GetLocalInstBlockContents(resolver, import_interface.param_patterns_id);
  2049. auto generic_data =
  2050. GetLocalGenericData(resolver, import_interface.generic_id);
  2051. std::optional<SemIR::InstId> self_param_id;
  2052. if (import_interface.is_complete()) {
  2053. self_param_id =
  2054. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  2055. }
  2056. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  2057. if (resolver.HasNewWork()) {
  2058. return ResolveResult::Retry(interface_const_id,
  2059. new_interface.first_decl_id());
  2060. }
  2061. new_interface.parent_scope_id = parent_scope_id;
  2062. new_interface.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2063. resolver, import_interface.implicit_param_patterns_id,
  2064. implicit_param_patterns);
  2065. new_interface.param_patterns_id = GetLocalCanonicalInstBlockId(
  2066. resolver, import_interface.param_patterns_id, param_patterns);
  2067. SetGenericData(resolver, import_interface.generic_id,
  2068. new_interface.generic_id, generic_data);
  2069. if (import_interface.is_complete()) {
  2070. CARBON_CHECK(self_param_id);
  2071. AddInterfaceDefinition(resolver, import_interface, new_interface,
  2072. *self_param_id);
  2073. }
  2074. return ResolveResult::Done(interface_const_id, new_interface.first_decl_id());
  2075. }
  2076. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2077. SemIR::FacetAccessType inst) -> ResolveResult {
  2078. auto facet_value_inst_id =
  2079. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2080. if (resolver.HasNewWork()) {
  2081. return ResolveResult::Retry();
  2082. }
  2083. return ResolveAsDeduplicated<SemIR::FacetAccessType>(
  2084. resolver, {.type_id = SemIR::TypeType::TypeId,
  2085. .facet_value_inst_id = facet_value_inst_id});
  2086. }
  2087. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2088. SemIR::FacetType inst) -> ResolveResult {
  2089. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2090. const SemIR::FacetTypeInfo& import_facet_type_info =
  2091. resolver.import_facet_types().Get(inst.facet_type_id);
  2092. for (auto interface : import_facet_type_info.extend_constraints) {
  2093. // We discard this here and recompute it below instead of saving it to avoid
  2094. // allocations.
  2095. GetLocalSpecificInterfaceData(resolver, interface);
  2096. }
  2097. for (auto interface : import_facet_type_info.self_impls_constraints) {
  2098. // We discard this here and recompute it below instead of saving it to avoid
  2099. // allocations.
  2100. GetLocalSpecificInterfaceData(resolver, interface);
  2101. }
  2102. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  2103. GetLocalConstantInstId(resolver, rewrite.lhs_id);
  2104. GetLocalConstantInstId(resolver, rewrite.rhs_id);
  2105. }
  2106. if (resolver.HasNewWork()) {
  2107. return ResolveResult::Retry();
  2108. }
  2109. SemIR::FacetTypeInfo local_facet_type_info = {
  2110. .other_requirements = import_facet_type_info.other_requirements};
  2111. local_facet_type_info.extend_constraints.reserve(
  2112. import_facet_type_info.extend_constraints.size());
  2113. for (auto interface : import_facet_type_info.extend_constraints) {
  2114. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2115. local_facet_type_info.extend_constraints.push_back(
  2116. GetLocalSpecificInterface(resolver, interface, data));
  2117. }
  2118. local_facet_type_info.self_impls_constraints.reserve(
  2119. import_facet_type_info.self_impls_constraints.size());
  2120. for (auto interface : import_facet_type_info.self_impls_constraints) {
  2121. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2122. local_facet_type_info.self_impls_constraints.push_back(
  2123. GetLocalSpecificInterface(resolver, interface, data));
  2124. }
  2125. local_facet_type_info.rewrite_constraints.reserve(
  2126. import_facet_type_info.rewrite_constraints.size());
  2127. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  2128. local_facet_type_info.rewrite_constraints.push_back(
  2129. {.lhs_id = GetLocalConstantInstId(resolver, rewrite.lhs_id),
  2130. .rhs_id = GetLocalConstantInstId(resolver, rewrite.rhs_id)});
  2131. }
  2132. // TODO: Also process the other requirements.
  2133. SemIR::FacetTypeId facet_type_id =
  2134. resolver.local_facet_types().Add(std::move(local_facet_type_info));
  2135. return ResolveAsDeduplicated<SemIR::FacetType>(
  2136. resolver,
  2137. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  2138. }
  2139. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2140. SemIR::FacetValue inst) -> ResolveResult {
  2141. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2142. auto type_inst_id = GetLocalTypeInstId(resolver, inst.type_inst_id);
  2143. auto witnesses = GetLocalInstBlockContents(resolver, inst.witnesses_block_id);
  2144. if (resolver.HasNewWork()) {
  2145. return ResolveResult::Retry();
  2146. }
  2147. return ResolveAsDeduplicated<SemIR::FacetValue>(
  2148. resolver,
  2149. {.type_id =
  2150. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2151. .type_inst_id = type_inst_id,
  2152. .witnesses_block_id = GetLocalCanonicalInstBlockId(
  2153. resolver, inst.witnesses_block_id, witnesses)});
  2154. }
  2155. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2156. SemIR::LookupImplWitness inst)
  2157. -> ResolveResult {
  2158. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2159. SemIR::WitnessType::TypeInstId);
  2160. auto query_self_inst_id =
  2161. GetLocalConstantInstId(resolver, inst.query_self_inst_id);
  2162. const auto& import_specific_interface =
  2163. resolver.import_specific_interfaces().Get(
  2164. inst.query_specific_interface_id);
  2165. auto data =
  2166. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  2167. if (resolver.HasNewWork()) {
  2168. return ResolveResult::Retry();
  2169. }
  2170. auto specific_interface =
  2171. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  2172. auto query_specific_interface_id =
  2173. resolver.local_specific_interfaces().Add(specific_interface);
  2174. return ResolveAsDeduplicated<SemIR::LookupImplWitness>(
  2175. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2176. SemIR::WitnessType::TypeInstId),
  2177. .query_self_inst_id = query_self_inst_id,
  2178. .query_specific_interface_id = query_specific_interface_id});
  2179. }
  2180. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2181. SemIR::ImplWitness inst) -> ResolveResult {
  2182. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2183. SemIR::WitnessType::TypeInstId);
  2184. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2185. auto witness_table_id =
  2186. GetLocalConstantInstId(resolver, inst.witness_table_id);
  2187. if (resolver.HasNewWork()) {
  2188. return ResolveResult::Retry();
  2189. }
  2190. auto specific_id =
  2191. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2192. return ResolveAsDeduplicated<SemIR::ImplWitness>(
  2193. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2194. SemIR::WitnessType::TypeInstId),
  2195. .witness_table_id = witness_table_id,
  2196. .specific_id = specific_id});
  2197. }
  2198. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2199. SemIR::ImplWitnessAccess inst)
  2200. -> ResolveResult {
  2201. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2202. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  2203. if (resolver.HasNewWork()) {
  2204. return ResolveResult::Retry();
  2205. }
  2206. return ResolveAsDeduplicated<SemIR::ImplWitnessAccess>(
  2207. resolver,
  2208. {.type_id =
  2209. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2210. .witness_id = witness_id,
  2211. .index = inst.index});
  2212. }
  2213. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2214. SemIR::ImplWitnessTable inst,
  2215. SemIR::InstId import_inst_id) -> ResolveResult {
  2216. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2217. auto import_decl_inst_id = import_impl.first_decl_id();
  2218. auto local_decl_inst_id =
  2219. GetLocalConstantInstId(resolver, import_decl_inst_id);
  2220. if (resolver.HasNewWork()) {
  2221. return ResolveResult::Retry();
  2222. }
  2223. auto impl_decl =
  2224. resolver.local_insts().GetAs<SemIR::ImplDecl>(local_decl_inst_id);
  2225. auto impl_id = impl_decl.impl_id;
  2226. auto elements_id = GetLocalImportRefInstBlock(resolver, inst.elements_id);
  2227. // Create a corresponding instruction to represent the table.
  2228. return ResolveAsUnique<SemIR::ImplWitnessTable>(
  2229. resolver, import_inst_id,
  2230. {.elements_id = elements_id, .impl_id = impl_id});
  2231. }
  2232. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2233. SemIR::IntValue inst) -> ResolveResult {
  2234. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2235. if (resolver.HasNewWork()) {
  2236. return ResolveResult::Retry();
  2237. }
  2238. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  2239. // to add a new canonical int in this IR.
  2240. auto int_id = inst.int_id.is_embedded_value()
  2241. ? inst.int_id
  2242. : resolver.local_ints().AddSigned(
  2243. resolver.import_ints().Get(inst.int_id));
  2244. return ResolveAsDeduplicated<SemIR::IntValue>(
  2245. resolver,
  2246. {.type_id =
  2247. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2248. .int_id = int_id});
  2249. }
  2250. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2251. SemIR::IntType inst) -> ResolveResult {
  2252. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2253. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  2254. if (resolver.HasNewWork()) {
  2255. return ResolveResult::Retry();
  2256. }
  2257. return ResolveAsDeduplicated<SemIR::IntType>(
  2258. resolver, {.type_id = SemIR::TypeType::TypeId,
  2259. .int_kind = inst.int_kind,
  2260. .bit_width_id = bit_width_id});
  2261. }
  2262. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2263. SemIR::Namespace inst,
  2264. SemIR::InstId import_inst_id) -> ResolveResult {
  2265. const auto& name_scope =
  2266. resolver.import_name_scopes().Get(inst.name_scope_id);
  2267. // A package from a different file becomes a child of the package here, as it
  2268. // would be if it were imported.
  2269. auto parent_scope_id =
  2270. inst.name_scope_id == SemIR::NameScopeId::Package
  2271. ? SemIR::NameScopeId::Package
  2272. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  2273. if (resolver.HasNewWork()) {
  2274. return ResolveResult::Retry();
  2275. }
  2276. auto namespace_type_id = GetSingletonType(resolver.local_context(),
  2277. SemIR::NamespaceType::TypeInstId);
  2278. auto namespace_decl =
  2279. SemIR::Namespace{.type_id = namespace_type_id,
  2280. .name_scope_id = SemIR::NameScopeId::None,
  2281. .import_id = SemIR::AbsoluteInstId::None};
  2282. auto inst_id =
  2283. AddPlaceholderImportedInst(resolver, import_inst_id, namespace_decl);
  2284. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  2285. namespace_decl.name_scope_id =
  2286. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  2287. // Namespaces from this package are eagerly imported, so anything we load here
  2288. // must be a closed import.
  2289. resolver.local_name_scopes()
  2290. .Get(namespace_decl.name_scope_id)
  2291. .set_is_closed_import(true);
  2292. auto namespace_const_id =
  2293. ReplacePlaceholderImportedInst(resolver, inst_id, namespace_decl);
  2294. return {.const_id = namespace_const_id};
  2295. }
  2296. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2297. SemIR::PatternType inst) -> ResolveResult {
  2298. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2299. auto scrutinee_type_inst_id =
  2300. GetLocalTypeInstId(resolver, inst.scrutinee_type_inst_id);
  2301. if (resolver.HasNewWork()) {
  2302. return ResolveResult::Retry();
  2303. }
  2304. return ResolveAsDeduplicated<SemIR::PatternType>(
  2305. resolver, {.type_id = SemIR::TypeType::TypeId,
  2306. .scrutinee_type_inst_id = scrutinee_type_inst_id});
  2307. }
  2308. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2309. SemIR::PointerType inst) -> ResolveResult {
  2310. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2311. auto pointee_id = GetLocalTypeInstId(resolver, inst.pointee_id);
  2312. if (resolver.HasNewWork()) {
  2313. return ResolveResult::Retry();
  2314. }
  2315. return ResolveAsDeduplicated<SemIR::PointerType>(
  2316. resolver, {.type_id = SemIR::TypeType::TypeId, .pointee_id = pointee_id});
  2317. }
  2318. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2319. SemIR::RequireCompleteType inst)
  2320. -> ResolveResult {
  2321. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2322. SemIR::WitnessType::TypeInstId);
  2323. auto complete_type_inst_id =
  2324. GetLocalTypeInstId(resolver, inst.complete_type_inst_id);
  2325. if (resolver.HasNewWork()) {
  2326. return ResolveResult::Retry();
  2327. }
  2328. return ResolveAsDeduplicated<SemIR::RequireCompleteType>(
  2329. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2330. SemIR::WitnessType::TypeInstId),
  2331. .complete_type_inst_id = complete_type_inst_id});
  2332. }
  2333. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2334. SemIR::ReturnSlotPattern inst,
  2335. SemIR::InstId import_inst_id) -> ResolveResult {
  2336. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2337. if (resolver.HasNewWork()) {
  2338. return ResolveResult::Retry();
  2339. }
  2340. return ResolveAsUnique<SemIR::ReturnSlotPattern>(
  2341. resolver, import_inst_id,
  2342. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2343. type_const_id),
  2344. .type_inst_id = SemIR::TypeInstId::None});
  2345. }
  2346. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2347. SemIR::SpecificFunction inst) -> ResolveResult {
  2348. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2349. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2350. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2351. if (resolver.HasNewWork()) {
  2352. return ResolveResult::Retry();
  2353. }
  2354. auto type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2355. type_const_id);
  2356. auto specific_id =
  2357. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2358. return ResolveAsDeduplicated<SemIR::SpecificFunction>(
  2359. resolver,
  2360. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2361. }
  2362. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2363. SemIR::SpecificImplFunction inst)
  2364. -> ResolveResult {
  2365. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2366. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2367. if (resolver.HasNewWork()) {
  2368. return ResolveResult::Retry();
  2369. }
  2370. auto type_id = GetSingletonType(resolver.local_context(),
  2371. SemIR::SpecificFunctionType::TypeInstId);
  2372. auto specific_id =
  2373. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2374. return ResolveAsDeduplicated<SemIR::SpecificImplFunction>(
  2375. resolver,
  2376. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2377. }
  2378. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2379. SemIR::StructAccess inst) -> ResolveResult {
  2380. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2381. auto struct_id = GetLocalConstantInstId(resolver, inst.struct_id);
  2382. if (resolver.HasNewWork()) {
  2383. return ResolveResult::Retry();
  2384. }
  2385. // A `struct_access` constant requires its struct operand to have a complete
  2386. // type.
  2387. CompleteTypeOrCheckFail(resolver.local_context(),
  2388. resolver.local_insts().Get(struct_id).type_id());
  2389. return ResolveAsDeduplicated<SemIR::StructAccess>(
  2390. resolver,
  2391. {.type_id =
  2392. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2393. .struct_id = struct_id,
  2394. .index = inst.index});
  2395. }
  2396. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2397. SemIR::StructType inst) -> ResolveResult {
  2398. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2399. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  2400. llvm::SmallVector<SemIR::TypeInstId> field_type_inst_ids;
  2401. field_type_inst_ids.reserve(orig_fields.size());
  2402. for (auto field : orig_fields) {
  2403. field_type_inst_ids.push_back(
  2404. GetLocalTypeInstId(resolver, field.type_inst_id));
  2405. }
  2406. if (resolver.HasNewWork()) {
  2407. return ResolveResult::Retry();
  2408. }
  2409. // Prepare a vector of fields for GetStructType.
  2410. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  2411. new_fields.reserve(orig_fields.size());
  2412. for (auto [orig_field, field_type_inst_id] :
  2413. llvm::zip(orig_fields, field_type_inst_ids)) {
  2414. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  2415. new_fields.push_back(
  2416. {.name_id = name_id, .type_inst_id = field_type_inst_id});
  2417. }
  2418. return ResolveAsDeduplicated<SemIR::StructType>(
  2419. resolver, {.type_id = SemIR::TypeType::TypeId,
  2420. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  2421. new_fields)});
  2422. }
  2423. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2424. SemIR::StructValue inst) -> ResolveResult {
  2425. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2426. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2427. if (resolver.HasNewWork()) {
  2428. return ResolveResult::Retry();
  2429. }
  2430. return ResolveAsDeduplicated<SemIR::StructValue>(
  2431. resolver,
  2432. {.type_id =
  2433. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2434. .elements_id =
  2435. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2436. }
  2437. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2438. SemIR::TupleAccess inst) -> ResolveResult {
  2439. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2440. auto tuple_id = GetLocalConstantInstId(resolver, inst.tuple_id);
  2441. if (resolver.HasNewWork()) {
  2442. return ResolveResult::Retry();
  2443. }
  2444. // A `tuple_access` constant requires its struct operand to have a complete
  2445. // type.
  2446. CompleteTypeOrCheckFail(resolver.local_context(),
  2447. resolver.local_insts().Get(tuple_id).type_id());
  2448. return ResolveAsDeduplicated<SemIR::TupleAccess>(
  2449. resolver,
  2450. {.type_id =
  2451. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2452. .tuple_id = tuple_id,
  2453. .index = inst.index});
  2454. }
  2455. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2456. SemIR::TuplePattern inst,
  2457. SemIR::InstId import_inst_id) -> ResolveResult {
  2458. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2459. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  2460. if (resolver.HasNewWork()) {
  2461. return ResolveResult::Retry();
  2462. }
  2463. return ResolveAsUnique<SemIR::TuplePattern>(
  2464. resolver, import_inst_id,
  2465. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2466. type_const_id),
  2467. .elements_id =
  2468. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements)});
  2469. }
  2470. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2471. SemIR::TupleType inst) -> ResolveResult {
  2472. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2473. auto orig_type_inst_ids =
  2474. resolver.import_inst_blocks().Get(inst.type_elements_id);
  2475. // TODO: It might be nice to make the `InstBlock` in `TupleType` record in the
  2476. // type system that its holding `TypeInstId` elements.
  2477. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  2478. type_inst_ids.reserve(orig_type_inst_ids.size());
  2479. for (auto elem_type_inst_id :
  2480. resolver.import_ir().types().GetBlockAsTypeInstIds(orig_type_inst_ids)) {
  2481. type_inst_ids.push_back(GetLocalTypeInstId(resolver, elem_type_inst_id));
  2482. }
  2483. if (resolver.HasNewWork()) {
  2484. return ResolveResult::Retry();
  2485. }
  2486. return ResolveAsDeduplicated<SemIR::TupleType>(
  2487. resolver, {.type_id = SemIR::TypeType::TypeId,
  2488. .type_elements_id = GetLocalCanonicalInstBlockId(
  2489. resolver, inst.type_elements_id, type_inst_ids)});
  2490. }
  2491. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2492. SemIR::TupleValue inst) -> ResolveResult {
  2493. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2494. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2495. if (resolver.HasNewWork()) {
  2496. return ResolveResult::Retry();
  2497. }
  2498. return ResolveAsDeduplicated<SemIR::TupleValue>(
  2499. resolver,
  2500. {.type_id =
  2501. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2502. .elements_id =
  2503. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2504. }
  2505. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2506. SemIR::UnboundElementType inst)
  2507. -> ResolveResult {
  2508. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2509. auto class_const_inst_id =
  2510. GetLocalTypeInstId(resolver, inst.class_type_inst_id);
  2511. auto elem_const_inst_id =
  2512. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  2513. if (resolver.HasNewWork()) {
  2514. return ResolveResult::Retry();
  2515. }
  2516. return ResolveAsDeduplicated<SemIR::UnboundElementType>(
  2517. resolver, {.type_id = SemIR::TypeType::TypeId,
  2518. .class_type_inst_id = class_const_inst_id,
  2519. .element_type_inst_id = elem_const_inst_id});
  2520. }
  2521. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2522. SemIR::VarPattern inst,
  2523. SemIR::InstId import_inst_id) -> ResolveResult {
  2524. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2525. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  2526. if (resolver.HasNewWork()) {
  2527. return ResolveResult::Retry();
  2528. }
  2529. return ResolveAsUnique<SemIR::VarPattern>(
  2530. resolver, import_inst_id,
  2531. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2532. type_const_id),
  2533. .subpattern_id = subpattern_id});
  2534. }
  2535. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2536. SemIR::VarStorage inst,
  2537. SemIR::InstId import_inst_id) -> ResolveResult {
  2538. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2539. auto pattern_id = GetLocalConstantInstId(resolver, inst.pattern_id);
  2540. if (resolver.HasNewWork()) {
  2541. return ResolveResult::Retry();
  2542. }
  2543. return ResolveAsUnique<SemIR::VarStorage>(
  2544. resolver, import_inst_id,
  2545. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2546. type_const_id),
  2547. .pattern_id = pattern_id});
  2548. }
  2549. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Vtable inst)
  2550. -> ResolveResult {
  2551. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2552. auto virtual_functions =
  2553. GetLocalInstBlockContents(resolver, inst.virtual_functions_id);
  2554. if (resolver.HasNewWork()) {
  2555. return ResolveResult::Retry();
  2556. }
  2557. auto virtual_functions_id = GetLocalCanonicalInstBlockId(
  2558. resolver, inst.virtual_functions_id, virtual_functions);
  2559. return ResolveAsDeduplicated<SemIR::Vtable>(
  2560. resolver,
  2561. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2562. type_const_id),
  2563. .virtual_functions_id = virtual_functions_id});
  2564. }
  2565. // Tries to resolve the InstId, returning a canonical constant when ready, or
  2566. // `None` if more has been added to the stack. This is the same as
  2567. // TryResolveInst, except that it may resolve symbolic constants as canonical
  2568. // constants instead of as constants associated with a particular generic.
  2569. //
  2570. // TODO: Consider refactoring the body to a helper in order to eliminate
  2571. // recursion.
  2572. // NOLINTNEXTLINE(misc-no-recursion)
  2573. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  2574. SemIR::InstId inst_id,
  2575. SemIR::ConstantId const_id)
  2576. -> ResolveResult {
  2577. if (SemIR::IsSingletonInstId(inst_id)) {
  2578. CARBON_CHECK(!const_id.has_value());
  2579. // Constants for builtins can be directly copied.
  2580. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id));
  2581. }
  2582. auto untyped_inst = resolver.import_insts().GetWithAttachedType(inst_id);
  2583. CARBON_KIND_SWITCH(untyped_inst) {
  2584. case CARBON_KIND(SemIR::AdaptDecl inst): {
  2585. return TryResolveTypedInst(resolver, inst, inst_id);
  2586. }
  2587. case CARBON_KIND(SemIR::AddrPattern inst): {
  2588. return TryResolveTypedInst(resolver, inst, inst_id);
  2589. }
  2590. case CARBON_KIND(SemIR::ArrayType inst): {
  2591. return TryResolveTypedInst(resolver, inst);
  2592. }
  2593. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  2594. return TryResolveTypedInst(resolver, inst, const_id);
  2595. }
  2596. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  2597. return TryResolveTypedInst(resolver, inst);
  2598. }
  2599. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  2600. return TryResolveTypedInst(resolver, inst);
  2601. }
  2602. case CARBON_KIND(SemIR::BaseDecl inst): {
  2603. return TryResolveTypedInst(resolver, inst, inst_id);
  2604. }
  2605. case CARBON_KIND(SemIR::BindAlias inst): {
  2606. return TryResolveTypedInst(resolver, inst);
  2607. }
  2608. case CARBON_KIND(SemIR::BindingPattern inst): {
  2609. return TryResolveTypedInst(resolver, inst, inst_id);
  2610. }
  2611. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  2612. return TryResolveTypedInst(resolver, inst);
  2613. }
  2614. case CARBON_KIND(SemIR::BoundMethod inst): {
  2615. return TryResolveTypedInst(resolver, inst);
  2616. }
  2617. case CARBON_KIND(SemIR::Call inst): {
  2618. return TryResolveTypedInst(resolver, inst);
  2619. }
  2620. case CARBON_KIND(SemIR::ClassDecl inst): {
  2621. return TryResolveTypedInst(resolver, inst, const_id);
  2622. }
  2623. case CARBON_KIND(SemIR::ClassType inst): {
  2624. return TryResolveTypedInst(resolver, inst);
  2625. }
  2626. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  2627. return TryResolveTypedInst(resolver, inst);
  2628. }
  2629. case CARBON_KIND(SemIR::ConstType inst): {
  2630. return TryResolveTypedInst(resolver, inst);
  2631. }
  2632. case CARBON_KIND(SemIR::ExportDecl inst): {
  2633. return TryResolveTypedInst(resolver, inst);
  2634. }
  2635. case CARBON_KIND(SemIR::FacetAccessType inst): {
  2636. return TryResolveTypedInst(resolver, inst);
  2637. }
  2638. case CARBON_KIND(SemIR::FacetType inst): {
  2639. return TryResolveTypedInst(resolver, inst);
  2640. }
  2641. case CARBON_KIND(SemIR::FacetValue inst): {
  2642. return TryResolveTypedInst(resolver, inst);
  2643. }
  2644. case CARBON_KIND(SemIR::FieldDecl inst): {
  2645. return TryResolveTypedInst(resolver, inst, inst_id);
  2646. }
  2647. case CARBON_KIND(SemIR::FunctionDecl inst): {
  2648. return TryResolveTypedInst(resolver, inst, const_id);
  2649. }
  2650. case CARBON_KIND(SemIR::FunctionType inst): {
  2651. return TryResolveTypedInst(resolver, inst);
  2652. }
  2653. case CARBON_KIND(SemIR::FunctionTypeWithSelfType inst): {
  2654. return TryResolveTypedInst(resolver, inst);
  2655. }
  2656. case CARBON_KIND(SemIR::GenericClassType inst): {
  2657. return TryResolveTypedInst(resolver, inst);
  2658. }
  2659. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  2660. return TryResolveTypedInst(resolver, inst);
  2661. }
  2662. case CARBON_KIND(SemIR::ImplDecl inst): {
  2663. return TryResolveTypedInst(resolver, inst, const_id);
  2664. }
  2665. case CARBON_KIND(SemIR::LookupImplWitness inst): {
  2666. return TryResolveTypedInst(resolver, inst);
  2667. }
  2668. case CARBON_KIND(SemIR::ImplWitness inst): {
  2669. return TryResolveTypedInst(resolver, inst);
  2670. }
  2671. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  2672. return TryResolveTypedInst(resolver, inst);
  2673. }
  2674. case CARBON_KIND(SemIR::ImplWitnessTable inst): {
  2675. return TryResolveTypedInst(resolver, inst, inst_id);
  2676. }
  2677. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  2678. return TryResolveTypedInst(resolver, inst, inst_id);
  2679. }
  2680. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  2681. return TryResolveTypedInst(resolver, inst, const_id);
  2682. }
  2683. case CARBON_KIND(SemIR::IntValue inst): {
  2684. return TryResolveTypedInst(resolver, inst);
  2685. }
  2686. case CARBON_KIND(SemIR::IntType inst): {
  2687. return TryResolveTypedInst(resolver, inst);
  2688. }
  2689. case CARBON_KIND(SemIR::Namespace inst): {
  2690. return TryResolveTypedInst(resolver, inst, inst_id);
  2691. }
  2692. case CARBON_KIND(SemIR::OutParamPattern inst): {
  2693. return TryResolveTypedInst(resolver, inst, inst_id);
  2694. }
  2695. case CARBON_KIND(SemIR::PatternType inst): {
  2696. return TryResolveTypedInst(resolver, inst);
  2697. }
  2698. case CARBON_KIND(SemIR::PointerType inst): {
  2699. return TryResolveTypedInst(resolver, inst);
  2700. }
  2701. case CARBON_KIND(SemIR::RefParamPattern inst): {
  2702. return TryResolveTypedInst(resolver, inst, inst_id);
  2703. }
  2704. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  2705. return TryResolveTypedInst(resolver, inst);
  2706. }
  2707. case CARBON_KIND(SemIR::ReturnSlotPattern inst): {
  2708. return TryResolveTypedInst(resolver, inst, inst_id);
  2709. }
  2710. case CARBON_KIND(SemIR::SpecificFunction inst): {
  2711. return TryResolveTypedInst(resolver, inst);
  2712. }
  2713. case CARBON_KIND(SemIR::SpecificImplFunction inst): {
  2714. return TryResolveTypedInst(resolver, inst);
  2715. }
  2716. case CARBON_KIND(SemIR::StructAccess inst): {
  2717. return TryResolveTypedInst(resolver, inst);
  2718. }
  2719. case CARBON_KIND(SemIR::StructType inst): {
  2720. return TryResolveTypedInst(resolver, inst);
  2721. }
  2722. case CARBON_KIND(SemIR::StructValue inst): {
  2723. return TryResolveTypedInst(resolver, inst);
  2724. }
  2725. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  2726. return TryResolveTypedInst(resolver, inst, inst_id);
  2727. }
  2728. case CARBON_KIND(SemIR::TupleAccess inst): {
  2729. return TryResolveTypedInst(resolver, inst);
  2730. }
  2731. case CARBON_KIND(SemIR::TuplePattern inst): {
  2732. return TryResolveTypedInst(resolver, inst, inst_id);
  2733. }
  2734. case CARBON_KIND(SemIR::TupleType inst): {
  2735. return TryResolveTypedInst(resolver, inst);
  2736. }
  2737. case CARBON_KIND(SemIR::TupleValue inst): {
  2738. return TryResolveTypedInst(resolver, inst);
  2739. }
  2740. case CARBON_KIND(SemIR::UnboundElementType inst): {
  2741. return TryResolveTypedInst(resolver, inst);
  2742. }
  2743. case CARBON_KIND(SemIR::ValueParamPattern inst): {
  2744. return TryResolveTypedInst(resolver, inst, inst_id);
  2745. }
  2746. case CARBON_KIND(SemIR::VarPattern inst): {
  2747. return TryResolveTypedInst(resolver, inst, inst_id);
  2748. }
  2749. case CARBON_KIND(SemIR::VarStorage inst): {
  2750. return TryResolveTypedInst(resolver, inst, inst_id);
  2751. }
  2752. case CARBON_KIND(SemIR::Vtable inst): {
  2753. return TryResolveTypedInst(resolver, inst);
  2754. }
  2755. default: {
  2756. auto inst_constant_id = resolver.import_constant_values().Get(inst_id);
  2757. if (!inst_constant_id.is_constant()) {
  2758. // TODO: Import of non-constant BindNames happens when importing `let`
  2759. // declarations.
  2760. CARBON_CHECK(untyped_inst.Is<SemIR::BindName>(),
  2761. "TryResolveInst on non-constant instruction {0}",
  2762. untyped_inst);
  2763. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  2764. }
  2765. // This instruction might have a constant value of a different kind.
  2766. auto constant_inst_id =
  2767. resolver.import_constant_values().GetInstId(inst_constant_id);
  2768. if (constant_inst_id == inst_id) {
  2769. // Produce a diagnostic to provide a source location with the CHECK
  2770. // failure.
  2771. resolver.local_context().TODO(
  2772. SemIR::LocId(AddImportIRInst(resolver, inst_id)),
  2773. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  2774. CARBON_FATAL("TryResolveInst on unsupported instruction kind {0}",
  2775. untyped_inst.kind());
  2776. }
  2777. // Try to resolve the constant value instead. Note that this can only
  2778. // retry once.
  2779. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  2780. constant_inst_id) == constant_inst_id,
  2781. "Constant value of constant instruction should refer to "
  2782. "the same instruction");
  2783. return TryResolveInstCanonical(resolver, constant_inst_id, const_id);
  2784. }
  2785. }
  2786. }
  2787. // Tries to resolve the InstId, returning a constant when ready, or `None` if
  2788. // more has been added to the stack. A similar API is followed for all
  2789. // following TryResolveTypedInst helper functions.
  2790. //
  2791. // `const_id` is `None` unless we've tried to resolve this instruction
  2792. // before, in which case it's the previous result.
  2793. //
  2794. // TODO: Error is returned when support is missing, but that should go away.
  2795. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  2796. SemIR::ConstantId const_id) -> ResolveResult {
  2797. auto inst_const_id = resolver.import_constant_values().GetAttached(inst_id);
  2798. if (!inst_const_id.has_value() || !inst_const_id.is_symbolic()) {
  2799. return TryResolveInstCanonical(resolver, inst_id, const_id);
  2800. }
  2801. // Try to import the generic. This might add new work.
  2802. const auto& symbolic_const =
  2803. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  2804. auto generic_const_id =
  2805. GetLocalConstantId(resolver, symbolic_const.generic_id);
  2806. auto inner_const_id = SemIR::ConstantId::None;
  2807. if (const_id.has_value()) {
  2808. // For the third phase, extract the constant value that
  2809. // TryResolveInstCanonical produced previously.
  2810. inner_const_id = resolver.local_constant_values().GetAttached(
  2811. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  2812. }
  2813. // Import the constant and rebuild the symbolic constant data.
  2814. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  2815. if (!result.const_id.has_value()) {
  2816. // First phase: TryResolveInstCanoncial needs a retry.
  2817. return result;
  2818. }
  2819. if (!const_id.has_value()) {
  2820. // Second phase: we have created an unattached constant. Create a
  2821. // corresponding attached constant.
  2822. if (symbolic_const.generic_id.has_value()) {
  2823. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  2824. {.inst_id =
  2825. resolver.local_constant_values().GetInstId(result.const_id),
  2826. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  2827. .index = symbolic_const.index,
  2828. .dependence = symbolic_const.dependence});
  2829. if (result.decl_id.has_value()) {
  2830. // Overwrite the unattached symbolic constant given initially to the
  2831. // declaration with its final attached symbolic value.
  2832. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  2833. }
  2834. }
  2835. } else {
  2836. // Third phase: perform a consistency check and produce the constant we
  2837. // created in the second phase.
  2838. CARBON_CHECK(result.const_id == inner_const_id,
  2839. "Constant value changed in third phase.");
  2840. result.const_id = const_id;
  2841. }
  2842. return result;
  2843. }
  2844. // Resolves and returns the local contents for an imported instruction block
  2845. // of constant instructions.
  2846. static auto ResolveLocalInstBlockContents(ImportRefResolver& resolver,
  2847. SemIR::InstBlockId import_block_id)
  2848. -> llvm::SmallVector<SemIR::InstId> {
  2849. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  2850. llvm::SmallVector<SemIR::InstId> inst_ids;
  2851. inst_ids.reserve(import_block.size());
  2852. for (auto import_inst_id : import_block) {
  2853. inst_ids.push_back(resolver.local_constant_values().GetInstId(
  2854. resolver.ResolveOneInst(import_inst_id)));
  2855. }
  2856. return inst_ids;
  2857. }
  2858. // Resolves and returns a local eval block for a region of an imported
  2859. // generic.
  2860. static auto ResolveLocalEvalBlock(ImportRefResolver& resolver,
  2861. const SemIR::Generic& import_generic,
  2862. SemIR::GenericId generic_id,
  2863. SemIR::GenericInstIndex::Region region)
  2864. -> SemIR::InstBlockId {
  2865. auto import_block_id = import_generic.GetEvalBlock(region);
  2866. if (!import_block_id.has_value()) {
  2867. return SemIR::InstBlockId::None;
  2868. }
  2869. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2870. auto eval_block_id = RebuildGenericEvalBlock(resolver.local_context(),
  2871. generic_id, region, inst_ids);
  2872. // Set the locations of the instructions in the inst block to match those of
  2873. // the imported instructions.
  2874. for (auto [import_inst_id, local_inst_id] :
  2875. llvm::zip(resolver.import_inst_blocks().Get(import_block_id),
  2876. resolver.local_inst_blocks().Get(eval_block_id))) {
  2877. auto import_ir_inst_id = AddImportIRInst(resolver, import_inst_id);
  2878. resolver.local_insts().SetLocId(local_inst_id, import_ir_inst_id);
  2879. }
  2880. return eval_block_id;
  2881. }
  2882. // Fills in the remaining information in a partially-imported generic.
  2883. // NOLINTNEXTLINE(misc-no-recursion)
  2884. static auto FinishPendingGeneric(ImportRefResolver& resolver,
  2885. ImportContext::PendingGeneric pending)
  2886. -> void {
  2887. const auto& import_generic =
  2888. resolver.import_generics().Get(pending.import_id);
  2889. // Load the bindings for the generic eagerly; they're used to form the self
  2890. // specific.
  2891. // TODO: Avoid recursion.
  2892. for (auto binding_id : resolver.local_inst_blocks().Get(
  2893. resolver.local_generics().Get(pending.local_id).bindings_id)) {
  2894. LoadImportRef(resolver.local_context(), binding_id);
  2895. }
  2896. // Don't store the local generic between calls: the generics list can be
  2897. // reallocated by ResolveLocalEvalBlock importing more specifics.
  2898. auto decl_block_id =
  2899. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2900. SemIR::GenericInstIndex::Region::Declaration);
  2901. resolver.local_generics().Get(pending.local_id).decl_block_id = decl_block_id;
  2902. auto local_decl_id = resolver.local_generics().Get(pending.local_id).decl_id;
  2903. auto self_specific_id = MakeSelfSpecific(
  2904. resolver.local_context(), SemIR::LocId(local_decl_id), pending.local_id);
  2905. resolver.local_generics().Get(pending.local_id).self_specific_id =
  2906. self_specific_id;
  2907. resolver.AddPendingSpecific({.import_id = import_generic.self_specific_id,
  2908. .local_id = self_specific_id});
  2909. auto definition_block_id =
  2910. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2911. SemIR::GenericInstIndex::Region::Definition);
  2912. resolver.local_generics().Get(pending.local_id).definition_block_id =
  2913. definition_block_id;
  2914. }
  2915. // Resolves and returns a local inst block of constant instructions
  2916. // corresponding to an imported inst block.
  2917. static auto ResolveLocalInstBlock(ImportRefResolver& resolver,
  2918. SemIR::InstBlockId import_block_id)
  2919. -> SemIR::InstBlockId {
  2920. if (!import_block_id.has_value()) {
  2921. return SemIR::InstBlockId::None;
  2922. }
  2923. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2924. return resolver.local_inst_blocks().Add(inst_ids);
  2925. }
  2926. // Fills in the remaining information in a partially-imported specific.
  2927. static auto FinishPendingSpecific(ImportRefResolver& resolver,
  2928. ImportContext::PendingSpecific pending)
  2929. -> void {
  2930. const auto& import_specific =
  2931. resolver.import_specifics().Get(pending.import_id);
  2932. // Don't store the local specific between calls: the specifics list can be
  2933. // reallocated by ResolveLocalInstBlock importing more specifics.
  2934. if (!resolver.local_specifics()
  2935. .Get(pending.local_id)
  2936. .decl_block_id.has_value()) {
  2937. auto decl_block_id =
  2938. ResolveLocalInstBlock(resolver, import_specific.decl_block_id);
  2939. resolver.local_specifics().Get(pending.local_id).decl_block_id =
  2940. decl_block_id;
  2941. }
  2942. if (!resolver.local_specifics()
  2943. .Get(pending.local_id)
  2944. .definition_block_id.has_value() &&
  2945. import_specific.definition_block_id.has_value()) {
  2946. auto definition_block_id =
  2947. ResolveLocalInstBlock(resolver, import_specific.definition_block_id);
  2948. resolver.local_specifics().Get(pending.local_id).definition_block_id =
  2949. definition_block_id;
  2950. }
  2951. }
  2952. // Perform any work that we deferred until the end of the main Resolve loop.
  2953. // NOLINTNEXTLINE(misc-no-recursion)
  2954. auto ImportRefResolver::PerformPendingWork() -> void {
  2955. // Note that the individual Finish steps can add new pending work, so keep
  2956. // going until we have no more work to do.
  2957. while (!pending_generics().empty() || !pending_specifics().empty()) {
  2958. // Process generics in the order that we added them because a later
  2959. // generic might refer to an earlier one, and the calls to
  2960. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  2961. // state.
  2962. // TODO: Import the generic eval block rather than calling
  2963. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  2964. // NOLINTNEXTLINE(modernize-loop-convert)
  2965. for (size_t i = 0; i != pending_generics().size(); ++i) {
  2966. FinishPendingGeneric(*this, pending_generics()[i]);
  2967. }
  2968. pending_generics().clear();
  2969. while (!pending_specifics().empty()) {
  2970. FinishPendingSpecific(*this, pending_specifics().pop_back_val());
  2971. }
  2972. }
  2973. }
  2974. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  2975. // loaded (including the one pointed at directly by the ImportRef), and the
  2976. // final instruction's type ID.
  2977. //
  2978. // This addresses cases where an ImportRefUnloaded may point at another
  2979. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  2980. // constant-evaluated version of the instruction to work with.
  2981. static auto GetInstForLoad(Context& context,
  2982. SemIR::ImportIRInstId import_ir_inst_id)
  2983. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  2984. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  2985. {}, SemIR::TypeId::None};
  2986. auto& [import_ir_insts, type_id] = result;
  2987. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  2988. // The first ImportIRInst is added directly because the IR doesn't need to be
  2989. // localized.
  2990. import_ir_insts.push_back(import_ir_inst);
  2991. const auto* cursor_ir =
  2992. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  2993. while (true) {
  2994. auto cursor_inst =
  2995. cursor_ir->insts().GetWithAttachedType(import_ir_inst.inst_id());
  2996. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  2997. if (!import_ref) {
  2998. type_id = cursor_inst.type_id();
  2999. return result;
  3000. }
  3001. import_ir_inst =
  3002. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  3003. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  3004. import_ir_insts.push_back(SemIR::ImportIRInst(
  3005. AddImportIR(context, {.decl_id = SemIR::InstId::None,
  3006. .is_export = false,
  3007. .sem_ir = cursor_ir}),
  3008. import_ir_inst.inst_id()));
  3009. }
  3010. }
  3011. // NOLINTNEXTLINE(misc-no-recursion)
  3012. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  3013. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  3014. if (!inst) {
  3015. return;
  3016. }
  3017. auto [indirect_insts, load_type_id] =
  3018. GetInstForLoad(context, inst->import_ir_inst_id);
  3019. // The last indirect instruction is the one to resolve. Pop it here because
  3020. // Resolve will assign the constant.
  3021. auto load_ir_inst = indirect_insts.pop_back_val();
  3022. ImportRefResolver resolver(&context, load_ir_inst.ir_id());
  3023. auto type_id = resolver.ResolveType(load_type_id);
  3024. auto constant_id = resolver.Resolve(load_ir_inst.inst_id());
  3025. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  3026. // doesn't use ReplacePlaceholderImportedInst because it would trigger
  3027. // TryEvalInst, which we want to avoid with ImportRefs.
  3028. context.sem_ir().insts().Set(
  3029. inst_id,
  3030. SemIR::ImportRefLoaded{.type_id = type_id,
  3031. .import_ir_inst_id = inst->import_ir_inst_id,
  3032. .entity_name_id = inst->entity_name_id});
  3033. // Store the constant for both the ImportRefLoaded and indirect instructions.
  3034. context.constant_values().Set(inst_id, constant_id);
  3035. for (const auto& import_ir_inst : indirect_insts) {
  3036. context.import_ir_constant_values()[import_ir_inst.ir_id().index].Set(
  3037. import_ir_inst.inst_id(), constant_id);
  3038. }
  3039. }
  3040. auto ImportImplsFromApiFile(Context& context) -> void {
  3041. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  3042. auto& import_ir = context.import_irs().Get(import_ir_id);
  3043. if (!import_ir.sem_ir) {
  3044. return;
  3045. }
  3046. for (auto [impl_id, _] : import_ir.sem_ir->impls().enumerate()) {
  3047. // Resolve the imported impl to a local impl ID.
  3048. ImportImpl(context, import_ir_id, impl_id);
  3049. }
  3050. }
  3051. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  3052. SemIR::ImplId impl_id) -> void {
  3053. ImportRefResolver resolver(&context, import_ir_id);
  3054. resolver.Resolve(context.import_irs()
  3055. .Get(import_ir_id)
  3056. .sem_ir->impls()
  3057. .Get(impl_id)
  3058. .first_decl_id());
  3059. }
  3060. // Returns whether a parse node associated with an imported instruction of kind
  3061. // `imported_kind` is usable as the location of a corresponding local
  3062. // instruction of kind `local_kind`.
  3063. static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
  3064. SemIR::InstKind local_kind) -> bool {
  3065. if (imported_kind == local_kind) {
  3066. return true;
  3067. }
  3068. if (imported_kind == SemIR::ImportDecl::Kind &&
  3069. local_kind == SemIR::Namespace::Kind) {
  3070. static_assert(
  3071. std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
  3072. decltype(SemIR::Namespace::Kind)::TypedNodeId>);
  3073. return true;
  3074. }
  3075. return false;
  3076. }
  3077. namespace Internal {
  3078. auto CheckCompatibleImportedNodeKind(Context& context,
  3079. SemIR::ImportIRInstId imported_loc_id,
  3080. SemIR::InstKind kind) -> void {
  3081. auto& import_ir_inst = context.import_ir_insts().Get(imported_loc_id);
  3082. const auto* import_ir =
  3083. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  3084. auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id()).kind();
  3085. CARBON_CHECK(
  3086. HasCompatibleImportedNodeKind(imported_kind, kind),
  3087. "Node of kind {0} created with location of imported node of kind {1}",
  3088. kind, imported_kind);
  3089. }
  3090. } // namespace Internal
  3091. } // namespace Carbon::Check