import_ref.cpp 126 KB

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