import_ref.cpp 114 KB

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