import_ref.cpp 137 KB

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