import_ref.cpp 139 KB

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