import_ref.cpp 117 KB

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