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