import_ref.cpp 170 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135
  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 "common/growing_range.h"
  11. #include "toolchain/base/kind_switch.h"
  12. #include "toolchain/base/shared_value_stores.h"
  13. #include "toolchain/check/context.h"
  14. #include "toolchain/check/eval.h"
  15. #include "toolchain/check/generic.h"
  16. #include "toolchain/check/import.h"
  17. #include "toolchain/check/inst.h"
  18. #include "toolchain/check/name_lookup.h"
  19. #include "toolchain/check/type.h"
  20. #include "toolchain/check/type_completion.h"
  21. #include "toolchain/parse/node_ids.h"
  22. #include "toolchain/sem_ir/constant.h"
  23. #include "toolchain/sem_ir/file.h"
  24. #include "toolchain/sem_ir/ids.h"
  25. #include "toolchain/sem_ir/impl.h"
  26. #include "toolchain/sem_ir/import_ir.h"
  27. #include "toolchain/sem_ir/inst.h"
  28. #include "toolchain/sem_ir/inst_categories.h"
  29. #include "toolchain/sem_ir/inst_kind.h"
  30. #include "toolchain/sem_ir/name_scope.h"
  31. #include "toolchain/sem_ir/specific_interface.h"
  32. #include "toolchain/sem_ir/specific_named_constraint.h"
  33. #include "toolchain/sem_ir/type_info.h"
  34. #include "toolchain/sem_ir/typed_insts.h"
  35. namespace Carbon::Check {
  36. // Adds the ImportIR, excluding the update to the check_ir_map.
  37. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  38. -> SemIR::ImportIRId {
  39. context.import_ir_constant_values().push_back(SemIR::ConstantValueStore(
  40. SemIR::ConstantId::None,
  41. import_ir.sem_ir ? &import_ir.sem_ir->insts() : nullptr));
  42. return context.import_irs().Add(import_ir);
  43. }
  44. // Adds a special-cased IR and verifies it received the correct ID.
  45. static auto SetSpecialImportIR(Context& context, SemIR::ImportIR import_ir,
  46. SemIR::ImportIRId expected_import_ir_id)
  47. -> void {
  48. auto ir_id = SemIR::ImportIRId::None;
  49. if (import_ir.sem_ir != nullptr) {
  50. ir_id = AddImportIR(context, import_ir);
  51. } else {
  52. // We don't have a check_ir_id, so add without touching check_ir_map.
  53. context.import_ir_constant_values().push_back(
  54. SemIR::ConstantValueStore(SemIR::ConstantValueStore::Unusable));
  55. ir_id = context.import_irs().Add(import_ir);
  56. }
  57. CARBON_CHECK(ir_id == expected_import_ir_id,
  58. "Actual ImportIRId ({0}) != Expected ImportIRId ({1})", ir_id,
  59. expected_import_ir_id);
  60. }
  61. auto SetSpecialImportIRs(Context& context, SemIR::ImportIR import_ir) -> void {
  62. SetSpecialImportIR(context, import_ir, SemIR::ImportIRId::ApiForImpl);
  63. SetSpecialImportIR(context,
  64. {.decl_id = SemIR::InstId::None, .is_export = false},
  65. SemIR::ImportIRId::Cpp);
  66. }
  67. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  68. -> SemIR::ImportIRId {
  69. auto& ir_id = context.check_ir_map().Get(import_ir.sem_ir->check_ir_id());
  70. if (!ir_id.has_value()) {
  71. // Note this updates check_ir_map.
  72. ir_id = InternalAddImportIR(context, import_ir);
  73. } else if (import_ir.is_export) {
  74. // We're processing an `export import`. In case the IR was indirectly added
  75. // as a non-export, mark it as an export.
  76. context.import_irs().Get(ir_id).is_export = true;
  77. }
  78. return ir_id;
  79. }
  80. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  81. SemIR::EntityNameId entity_name_id =
  82. SemIR::EntityNameId::None) -> SemIR::InstId {
  83. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  84. auto import_ref_id = AddPlaceholderImportedInstInNoBlock(
  85. context,
  86. MakeImportedLocIdAndInst(
  87. context, import_ir_inst_id,
  88. SemIR::ImportRefUnloaded{.import_ir_inst_id = import_ir_inst_id,
  89. .entity_name_id = entity_name_id}));
  90. return import_ref_id;
  91. }
  92. static auto GetCanonicalImportIRInst(Context& context,
  93. const SemIR::File* target_ir,
  94. SemIR::InstId target_inst_id)
  95. -> SemIR::ImportIRInst {
  96. auto [canonical_ir, canonical_inst_id] =
  97. GetCanonicalFileAndInstId(target_ir, target_inst_id);
  98. auto ir_id = SemIR::ImportIRId::None;
  99. if (canonical_ir != &context.sem_ir()) {
  100. // This uses AddImportIR in case it was indirectly found, which can
  101. // happen with two or more steps of exports.
  102. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::None,
  103. .is_export = false,
  104. .sem_ir = canonical_ir});
  105. }
  106. return SemIR::ImportIRInst(ir_id, canonical_inst_id);
  107. }
  108. auto GetCanonicalImportIRInst(Context& context, SemIR::InstId inst_id)
  109. -> SemIR::ImportIRInst {
  110. return GetCanonicalImportIRInst(context, &context.sem_ir(), inst_id);
  111. }
  112. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::NameId name_id,
  113. SemIR::InstId prev_id,
  114. SemIR::ImportIRInst prev_import_ir_inst,
  115. SemIR::ImportIRId new_ir_id,
  116. const SemIR::File* new_import_ir,
  117. SemIR::InstId new_inst_id) -> void {
  118. auto new_import_ir_inst =
  119. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  120. if (new_import_ir_inst == prev_import_ir_inst) {
  121. return;
  122. }
  123. auto conflict_id =
  124. AddImportRef(context, SemIR::ImportIRInst(new_ir_id, new_inst_id));
  125. // TODO: Pass the imported name location instead of the conflict id.
  126. DiagnoseDuplicateName(context, name_id, SemIR::LocId(conflict_id),
  127. SemIR::LocId(prev_id));
  128. }
  129. namespace {
  130. // A context within which we are performing an import. Tracks information about
  131. // the source and destination. This provides a restricted interface compared to
  132. // ImportResolver: in particular, it does not have access to a work list.
  133. // Therefore code that accepts an ImportContext is unable to enqueue new work.
  134. class ImportContext {
  135. public:
  136. // A generic that we have partially imported.
  137. struct PendingGeneric {
  138. SemIR::GenericId import_id;
  139. SemIR::GenericId local_id;
  140. };
  141. // A specific that we have partially imported.
  142. struct PendingSpecific {
  143. SemIR::SpecificId import_id;
  144. SemIR::SpecificId local_id;
  145. };
  146. // `context` must not be null.
  147. explicit ImportContext(Context* context, SemIR::ImportIRId import_ir_id)
  148. : context_(context),
  149. import_ir_id_(import_ir_id),
  150. import_ir_(*context_->import_irs().Get(import_ir_id).sem_ir) {}
  151. // Returns the file we are importing from.
  152. auto import_ir() -> const SemIR::File& { return import_ir_; }
  153. // Accessors into value stores of the file we are importing from.
  154. auto import_associated_constants() -> const SemIR::AssociatedConstantStore& {
  155. return import_ir().associated_constants();
  156. }
  157. auto import_classes() -> const SemIR::ClassStore& {
  158. return import_ir().classes();
  159. }
  160. auto import_vtables() -> const SemIR::VtableStore& {
  161. return import_ir().vtables();
  162. }
  163. auto import_constant_values() -> const SemIR::ConstantValueStore& {
  164. return import_ir().constant_values();
  165. }
  166. auto import_entity_names() -> const SemIR::EntityNameStore& {
  167. return import_ir().entity_names();
  168. }
  169. auto import_facet_types() -> const SemIR::FacetTypeInfoStore& {
  170. return import_ir().facet_types();
  171. }
  172. auto import_functions() -> const SemIR::FunctionStore& {
  173. return import_ir().functions();
  174. }
  175. auto import_generics() -> const SemIR::GenericStore& {
  176. return import_ir().generics();
  177. }
  178. auto import_identifiers() -> const SharedValueStores::IdentifierStore& {
  179. return import_ir().identifiers();
  180. }
  181. auto import_impls() -> const SemIR::ImplStore& { return import_ir().impls(); }
  182. auto import_inst_blocks() -> const SemIR::InstBlockStore& {
  183. return import_ir().inst_blocks();
  184. }
  185. auto import_insts() -> const SemIR::InstStore& { return import_ir().insts(); }
  186. auto import_interfaces() -> const SemIR::InterfaceStore& {
  187. return import_ir().interfaces();
  188. }
  189. auto import_named_constraints() -> const SemIR::NamedConstraintStore& {
  190. return import_ir().named_constraints();
  191. }
  192. auto import_ints() -> const SharedValueStores::IntStore& {
  193. return import_ir().ints();
  194. }
  195. auto import_name_scopes() -> const SemIR::NameScopeStore& {
  196. return import_ir().name_scopes();
  197. }
  198. auto import_require_impls() -> const SemIR::RequireImplsStore& {
  199. return import_ir().require_impls();
  200. }
  201. auto import_require_impls_blocks() -> const SemIR::RequireImplsBlockStore& {
  202. return import_ir().require_impls_blocks();
  203. }
  204. auto import_specifics() -> const SemIR::SpecificStore& {
  205. return import_ir().specifics();
  206. }
  207. auto import_specific_interfaces() -> const SemIR::SpecificInterfaceStore& {
  208. return import_ir().specific_interfaces();
  209. }
  210. auto import_string_literal_values()
  211. -> const SharedValueStores::StringLiteralStore& {
  212. return import_ir().string_literal_values();
  213. }
  214. auto import_struct_type_fields() -> const SemIR::StructTypeFieldsStore& {
  215. return import_ir().struct_type_fields();
  216. }
  217. auto import_types() -> const SemIR::TypeStore& { return import_ir().types(); }
  218. // Returns the local file's import ID for the IR we are importing from.
  219. auto import_ir_id() -> SemIR::ImportIRId { return import_ir_id_; }
  220. // A value store for local constant values of imported instructions. This maps
  221. // from `InstId`s in the import IR to corresponding `ConstantId`s in the local
  222. // IR.
  223. auto local_constant_values_for_import_insts() -> SemIR::ConstantValueStore& {
  224. return local_context().import_ir_constant_values()
  225. [local_context().sem_ir().import_irs().GetRawIndex(import_ir_id_)];
  226. }
  227. // Returns the file we are importing into.
  228. auto local_ir() -> SemIR::File& { return context_->sem_ir(); }
  229. // Returns the type-checking context we are importing into.
  230. auto local_context() -> Context& { return *context_; }
  231. // Accessors into value stores of the file we are importing into.
  232. auto local_associated_constants() -> SemIR::AssociatedConstantStore& {
  233. return local_ir().associated_constants();
  234. }
  235. auto local_classes() -> SemIR::ClassStore& { return local_ir().classes(); }
  236. auto local_vtables() -> SemIR::VtableStore& { return local_ir().vtables(); }
  237. auto local_constant_values() -> SemIR::ConstantValueStore& {
  238. return local_ir().constant_values();
  239. }
  240. auto local_entity_names() -> SemIR::EntityNameStore& {
  241. return local_ir().entity_names();
  242. }
  243. auto local_facet_types() -> SemIR::FacetTypeInfoStore& {
  244. return local_ir().facet_types();
  245. }
  246. auto local_functions() -> SemIR::FunctionStore& {
  247. return local_ir().functions();
  248. }
  249. auto local_generics() -> SemIR::GenericStore& {
  250. return local_ir().generics();
  251. }
  252. auto local_identifiers() -> SharedValueStores::IdentifierStore& {
  253. return local_ir().identifiers();
  254. }
  255. auto local_impls() -> SemIR::ImplStore& { return local_ir().impls(); }
  256. auto local_import_ir_insts() -> SemIR::ImportIRInstStore& {
  257. return local_ir().import_ir_insts();
  258. }
  259. auto local_inst_blocks() -> SemIR::InstBlockStore& {
  260. return local_ir().inst_blocks();
  261. }
  262. auto local_insts() -> SemIR::InstStore& { return local_ir().insts(); }
  263. auto local_interfaces() -> SemIR::InterfaceStore& {
  264. return local_ir().interfaces();
  265. }
  266. auto local_named_constraints() -> SemIR::NamedConstraintStore& {
  267. return local_ir().named_constraints();
  268. }
  269. auto local_ints() -> SharedValueStores::IntStore& {
  270. return local_ir().ints();
  271. }
  272. auto local_name_scopes() -> SemIR::NameScopeStore& {
  273. return local_ir().name_scopes();
  274. }
  275. auto local_require_impls() -> SemIR::RequireImplsStore& {
  276. return local_ir().require_impls();
  277. }
  278. auto local_require_impls_blocks() -> SemIR::RequireImplsBlockStore& {
  279. return local_ir().require_impls_blocks();
  280. }
  281. auto local_specifics() -> SemIR::SpecificStore& {
  282. return local_ir().specifics();
  283. }
  284. auto local_specific_interfaces() -> SemIR::SpecificInterfaceStore& {
  285. return local_ir().specific_interfaces();
  286. }
  287. auto local_string_literal_values() -> SharedValueStores::StringLiteralStore& {
  288. return local_ir().string_literal_values();
  289. }
  290. auto local_struct_type_fields() -> SemIR::StructTypeFieldsStore& {
  291. return local_ir().struct_type_fields();
  292. }
  293. auto local_types() -> SemIR::TypeStore& { return local_ir().types(); }
  294. // Add a generic that has been partially imported but needs to be finished.
  295. auto AddPendingGeneric(PendingGeneric pending) -> void {
  296. pending_generics_.push_back(pending);
  297. }
  298. // Add a specific that has been partially imported but needs to be finished.
  299. auto AddPendingSpecific(PendingSpecific pending) -> void {
  300. pending_specifics_.push_back(pending);
  301. }
  302. protected:
  303. auto pending_generics() -> llvm::SmallVector<PendingGeneric>& {
  304. return pending_generics_;
  305. }
  306. auto pending_specifics() -> llvm::SmallVector<PendingSpecific>& {
  307. return pending_specifics_;
  308. }
  309. private:
  310. Context* context_;
  311. SemIR::ImportIRId import_ir_id_;
  312. const SemIR::File& import_ir_;
  313. // TODO: The following members don't belong here. This pending work mechanism
  314. // can probably be removed entirely if we stop importing generic eval blocks
  315. // and instead evaluate them directly in the imported IR.
  316. // Generics that we have partially imported but not yet finished importing.
  317. llvm::SmallVector<PendingGeneric> pending_generics_;
  318. // Specifics that we have partially imported but not yet finished importing.
  319. llvm::SmallVector<PendingSpecific> pending_specifics_;
  320. };
  321. // Resolves an instruction from an imported IR into a constant referring to the
  322. // current IR.
  323. //
  324. // Calling Resolve on an instruction operates in an iterative manner, tracking
  325. // Work items on work_stack_. At a high level, the loop is:
  326. //
  327. // 1. If a constant value is already known for the work item and was not set by
  328. // this work item, it's considered resolved.
  329. // - The constant check avoids performance costs of deduplication on add.
  330. // - If we've processed this work item before, then we now process it again.
  331. // It didn't complete last time, even though we have a constant value
  332. // already.
  333. //
  334. // 2. Resolve the instruction (TryResolveInst/TryResolveTypedInst). This is done
  335. // in three phases. The first and second phases can add work to the worklist
  336. // and end in a retry, in which case those phases will be rerun once the
  337. // added work is done. The rerun cannot also end in a retry, so this results
  338. // in at most three calls, but in practice one or two calls is almost always
  339. // sufficient. Due to the chance of a second or third call to TryResolveInst,
  340. // it's important to only perform expensive work once, even when the same
  341. // phase is rerun.
  342. //
  343. // - First phase:
  344. // - Gather all input constants necessary to form the constant value of the
  345. // instruction. Gathering constants directly adds unresolved values to
  346. // work_stack_.
  347. // - If HasNewWork() reports that any work was added, then return Retry():
  348. // this instruction needs another call to complete. Gather the
  349. // now-resolved constants and continue to the next step once the retry
  350. // happens.
  351. //
  352. // - Second phase:
  353. // - Build the constant value of the instruction.
  354. // - Gather all input constants necessary to finish importing the
  355. // instruction. This is only necessary for instructions like classes that
  356. // can be forward-declared. For these instructions, we first import the
  357. // constant value and then later import the rest of the declaration in
  358. // order to break cycles.
  359. // - If HasNewWork() reports that any work was added, then return
  360. // Retry(constant_value): this instruction needs another call to
  361. // complete. Gather the now-resolved constants and continue to the next
  362. // step once the retry happens.
  363. //
  364. // - Third phase:
  365. // - After the second phase, the constant value for the instruction is
  366. // already set, and will be passed back into TryResolve*Inst on retry. It
  367. // should not be created again.
  368. // - Fill in any remaining information to complete the import of the
  369. // instruction. For example, when importing a class declaration, build
  370. // the class scope and information about the definition.
  371. // - Return Done() to finish the resolution process. This will cause the
  372. // Resolve loop to set a constant value if we didn't retry at the end of
  373. // the second phase.
  374. //
  375. // In the common case where the second phase cannot add new work (because the
  376. // inst doesn't represent a declaration of an entity that can be forward
  377. // declared), the second and third phases are usually expressed as a call to
  378. // ResolveResult::Deduplicated or ResolveResult::Unique.
  379. //
  380. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  381. // remain, and may no longer be at the top of the stack; update the state of
  382. // the work item to track what work still needs to be done.
  383. //
  384. // The same instruction can be enqueued for resolution multiple times. However,
  385. // we will only reach the second phase once: once a constant value is set, only
  386. // the resolution step that set it will retry.
  387. //
  388. // TODO: Fix class `extern` handling and merging, rewrite tests.
  389. // - check/testdata/class/cross_package_import.carbon
  390. // - check/testdata/class/extern.carbon
  391. // TODO: Fix function `extern` handling and merging, rewrite tests.
  392. // - check/testdata/function/declaration/import.carbon
  393. // - check/testdata/packages/cross_package_import.carbon
  394. class ImportRefResolver : public ImportContext {
  395. public:
  396. // `context` must not be null.
  397. explicit ImportRefResolver(Context* context, SemIR::ImportIRId import_ir_id)
  398. : ImportContext(context, import_ir_id) {}
  399. // Iteratively resolves an imported instruction's inner references until a
  400. // constant ID referencing the current IR is produced. See the class comment
  401. // for more details.
  402. auto ResolveOneInst(SemIR::InstId inst_id) -> SemIR::ConstantId;
  403. // Performs resolution for one instruction and then performs all work we
  404. // deferred.
  405. // NOLINTNEXTLINE(misc-no-recursion)
  406. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  407. auto const_id = ResolveOneInst(inst_id);
  408. PerformPendingWork();
  409. return const_id;
  410. }
  411. // Wraps constant evaluation with logic to handle constants.
  412. // NOLINTNEXTLINE(misc-no-recursion)
  413. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId {
  414. return Resolve(GetInstWithConstantValue(import_ir(), import_const_id));
  415. }
  416. // Wraps constant evaluation with logic to handle types.
  417. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId;
  418. // Returns true if new unresolved constants were found as part of this
  419. // `Resolve` step.
  420. auto HasNewWork() -> bool {
  421. CARBON_CHECK(initial_work_ <= work_stack_.size(),
  422. "Work shouldn't decrease");
  423. return initial_work_ < work_stack_.size();
  424. }
  425. // Returns the ConstantId for an InstId. Adds unresolved constants to
  426. // work_stack_.
  427. auto GetLocalConstantValueOrPush(SemIR::InstId inst_id) -> SemIR::ConstantId;
  428. private:
  429. // A step in work_stack_.
  430. struct Work {
  431. // The instruction to work on.
  432. SemIR::InstId inst_id;
  433. // Whether this work item set the constant value for the instruction and
  434. // requested a retry.
  435. bool retry_with_constant_value = false;
  436. };
  437. // The constant found by FindResolvedConstId.
  438. struct ResolvedConstId {
  439. // The constant for the instruction. `None` if not yet resolved.
  440. SemIR::ConstantId const_id = SemIR::ConstantId::None;
  441. // Instructions which are indirect but equivalent to the current instruction
  442. // being resolved, and should have their constant set to the same. Empty
  443. // when `const_id` has a value.
  444. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  445. };
  446. // Looks to see if an instruction has been resolved. If a constant is only
  447. // found indirectly, sets the constant for any indirect steps that don't
  448. // already have the constant. If a constant isn't found, returns the indirect
  449. // instructions so that they can have the resolved constant assigned later.
  450. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId;
  451. // Sets a resolved constant into the current and indirect instructions.
  452. auto SetResolvedConstId(SemIR::InstId inst_id,
  453. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  454. SemIR::ConstantId const_id) -> void;
  455. auto PerformPendingWork() -> void;
  456. llvm::SmallVector<Work> work_stack_;
  457. // The size of work_stack_ at the start of resolving the current instruction.
  458. size_t initial_work_ = 0;
  459. };
  460. } // namespace
  461. // Wrapper for `AddImportRef` that provides the `import_ir_id`.
  462. static auto AddImportRef(ImportContext& context, SemIR::InstId inst_id,
  463. SemIR::EntityNameId entity_name_id =
  464. SemIR::EntityNameId::None) -> SemIR::InstId {
  465. return AddImportRef(context.local_context(),
  466. SemIR::ImportIRInst(context.import_ir_id(), inst_id),
  467. entity_name_id);
  468. }
  469. // Adds an import_ref instruction for an instruction that we have already loaded
  470. // from an imported IR, with a known constant value. This is useful when the
  471. // instruction has a symbolic constant value, in order to produce an instruction
  472. // that hold that symbolic constant.
  473. static auto AddLoadedImportRef(ImportContext& context,
  474. SemIR::TypeId local_type_id,
  475. SemIR::InstId import_inst_id,
  476. SemIR::ConstantId local_const_id)
  477. -> SemIR::InstId {
  478. auto import_ir_inst_id = context.local_import_ir_insts().Add(
  479. SemIR::ImportIRInst(context.import_ir_id(), import_inst_id));
  480. SemIR::ImportRefLoaded inst = {.type_id = local_type_id,
  481. .import_ir_inst_id = import_ir_inst_id,
  482. .entity_name_id = SemIR::EntityNameId::None};
  483. auto inst_id = AddPlaceholderImportedInstInNoBlock(
  484. context.local_context(),
  485. MakeImportedLocIdAndInst(context.local_context(), import_ir_inst_id,
  486. inst));
  487. context.local_constant_values().Set(inst_id, local_const_id);
  488. context.local_constant_values_for_import_insts().Set(import_inst_id,
  489. local_const_id);
  490. return inst_id;
  491. }
  492. // Like `AddLoadedImportRef`, but only for types, and returns a `TypeInstId`.
  493. static auto AddLoadedImportRefForType(ImportContext& context,
  494. SemIR::TypeInstId import_inst_id,
  495. SemIR::ConstantId local_const_id)
  496. -> SemIR::TypeInstId {
  497. return context.local_types().GetAsTypeInstId(AddLoadedImportRef(
  498. context, SemIR::TypeType::TypeId, import_inst_id, local_const_id));
  499. }
  500. static auto AddImportIRInst(ImportContext& context, SemIR::InstId inst_id)
  501. -> SemIR::ImportIRInstId {
  502. return context.local_import_ir_insts().Add(
  503. SemIR::ImportIRInst(context.import_ir_id(), inst_id));
  504. }
  505. // Computes, sets, and returns the constant value for an instruction.
  506. static auto SetConstantValue(Context& context, SemIR::InstId inst_id,
  507. SemIR::Inst inst) -> SemIR::ConstantId {
  508. auto const_id = TryEvalInstUnsafe(context, inst_id, inst);
  509. if (const_id.is_constant()) {
  510. CARBON_VLOG_TO(context.vlog_stream(), "Constant: {0} -> {1}\n", inst,
  511. context.constant_values().GetInstId(const_id));
  512. }
  513. context.constant_values().Set(inst_id, const_id);
  514. return const_id;
  515. }
  516. // Adds an imported instruction without setting its constant value. The
  517. // instruction should later be updated by either `SetConstantValue` or
  518. // `ReplacePlaceholderImportedInst`.
  519. template <typename InstT>
  520. static auto AddPlaceholderImportedInst(ImportContext& context,
  521. SemIR::InstId import_inst_id, InstT inst)
  522. -> SemIR::InstId {
  523. auto import_ir_inst_id = AddImportIRInst(context, import_inst_id);
  524. return AddPlaceholderImportedInstInNoBlock(
  525. context.local_context(),
  526. MakeImportedLocIdAndInst(context.local_context(), import_ir_inst_id,
  527. inst));
  528. }
  529. // Replace an imported instruction that was added by
  530. // `AddPlaceholderImportedInst` with a new instruction. Computes, sets, and
  531. // returns the new constant value.
  532. static auto ReplacePlaceholderImportedInst(ImportContext& context,
  533. SemIR::InstId inst_id,
  534. SemIR::Inst inst)
  535. -> SemIR::ConstantId {
  536. CARBON_VLOG_TO(context.local_context().vlog_stream(),
  537. "ReplaceImportedInst: {0} -> {1}\n", inst_id, inst);
  538. context.local_insts().Set(inst_id, inst);
  539. CARBON_CHECK(context.local_constant_values().Get(inst_id) ==
  540. SemIR::ConstantId::None);
  541. return SetConstantValue(context.local_context(), inst_id, inst);
  542. }
  543. // Returns the ConstantId for an InstId. Adds unresolved constants to
  544. // the resolver's work stack.
  545. static auto GetLocalConstantId(ImportRefResolver& resolver,
  546. SemIR::InstId inst_id) -> SemIR::ConstantId {
  547. return resolver.GetLocalConstantValueOrPush(inst_id);
  548. }
  549. // Returns the ConstantId for an imported ConstantId. Adds unresolved
  550. // constants to the resolver's work stack.
  551. static auto GetLocalConstantId(ImportRefResolver& resolver,
  552. SemIR::ConstantId const_id)
  553. -> SemIR::ConstantId {
  554. return GetLocalConstantId(
  555. resolver, GetInstWithConstantValue(resolver.import_ir(), const_id));
  556. }
  557. // Returns the local constant InstId for an imported InstId.
  558. static auto GetLocalConstantInstId(ImportRefResolver& resolver,
  559. SemIR::InstId inst_id) -> SemIR::InstId {
  560. auto const_id = GetLocalConstantId(resolver, inst_id);
  561. return resolver.local_constant_values().GetInstIdIfValid(const_id);
  562. }
  563. // Returns the local constant InstId for an imported InstId.
  564. static auto GetLocalTypeInstId(ImportRefResolver& resolver,
  565. SemIR::TypeInstId inst_id) -> SemIR::TypeInstId {
  566. // The input instruction is a TypeInstId, and import does not change the type
  567. // of instructions, so the result is also a valid TypeInstId.
  568. return SemIR::TypeInstId::UnsafeMake(
  569. GetLocalConstantInstId(resolver, static_cast<SemIR::InstId>(inst_id)));
  570. }
  571. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  572. // work_stack_.
  573. static auto GetLocalConstantId(ImportRefResolver& resolver,
  574. SemIR::TypeId type_id) -> SemIR::ConstantId {
  575. return GetLocalConstantId(resolver,
  576. resolver.import_types().GetConstantId(type_id));
  577. }
  578. // Translates a NameId from the import IR to a local NameId.
  579. //
  580. // No new work is generated by calling this function.
  581. static auto GetLocalNameId(ImportContext& context, SemIR::NameId import_name_id)
  582. -> SemIR::NameId {
  583. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.has_value()) {
  584. return SemIR::NameId::ForIdentifier(context.local_identifiers().Add(
  585. context.import_identifiers().Get(ident_id)));
  586. }
  587. return import_name_id;
  588. }
  589. // Returns the id for a local symbolic EntityName from an imported one,
  590. // preserving only the `NameId`, the `CompileTimeBindIndex`, and whether it is a
  591. // template. Other parts of the EntityName are not kept and are not considered
  592. // part of the canonical EntityName (even if they are present there).
  593. //
  594. // No new work is generated by calling this function.
  595. static auto GetLocalSymbolicEntityNameId(
  596. ImportContext& context, SemIR::EntityNameId import_entity_name_id)
  597. -> SemIR::EntityNameId {
  598. const auto& import_entity_name =
  599. context.import_entity_names().Get(import_entity_name_id);
  600. auto name_id = GetLocalNameId(context, import_entity_name.name_id);
  601. return context.local_entity_names().AddSymbolicBindingName(
  602. name_id, SemIR::NameScopeId::None, import_entity_name.bind_index(),
  603. import_entity_name.is_template);
  604. }
  605. // Gets the local constant values corresponding to an imported inst block.
  606. static auto GetLocalInstBlockContents(ImportRefResolver& resolver,
  607. SemIR::InstBlockId import_block_id)
  608. -> llvm::SmallVector<SemIR::InstId> {
  609. llvm::SmallVector<SemIR::InstId> inst_ids;
  610. if (!import_block_id.has_value() ||
  611. import_block_id == SemIR::InstBlockId::Empty) {
  612. return inst_ids;
  613. }
  614. // Import all the values in the block.
  615. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  616. inst_ids.reserve(import_block.size());
  617. for (auto import_inst_id : import_block) {
  618. inst_ids.push_back(GetLocalConstantInstId(resolver, import_inst_id));
  619. }
  620. return inst_ids;
  621. }
  622. // Gets a local canonical instruction block ID corresponding to an imported inst
  623. // block whose contents were already imported, for example by
  624. // GetLocalInstBlockContents.
  625. static auto GetLocalCanonicalInstBlockId(ImportContext& context,
  626. SemIR::InstBlockId import_block_id,
  627. llvm::ArrayRef<SemIR::InstId> contents)
  628. -> SemIR::InstBlockId {
  629. if (!import_block_id.has_value()) {
  630. return SemIR::InstBlockId::None;
  631. }
  632. return context.local_inst_blocks().AddCanonical(contents);
  633. }
  634. // Imports the RequireImplsDecl instructions for each RequireImplsId in the
  635. // block, and gets the local RequireImplsIds from them. The returned vector is
  636. // only complete if there is no more work to do in the resolver on return.
  637. static auto GetLocalRequireImplsBlockContents(
  638. ImportRefResolver& resolver, SemIR::RequireImplsBlockId import_block_id)
  639. -> llvm::SmallVector<SemIR::RequireImplsId> {
  640. llvm::SmallVector<SemIR::RequireImplsId> require_decl_ids;
  641. if (!import_block_id.has_value() ||
  642. import_block_id == SemIR::RequireImplsBlockId::Empty) {
  643. return require_decl_ids;
  644. }
  645. // Import the RequireImplsDecl for each RequireImpls in the block.
  646. auto import_block =
  647. resolver.import_require_impls_blocks().Get(import_block_id);
  648. require_decl_ids.reserve(import_block.size());
  649. for (auto import_require_impls_id : import_block) {
  650. const auto& import_require =
  651. resolver.import_require_impls().Get(import_require_impls_id);
  652. auto local_decl_id =
  653. GetLocalConstantInstId(resolver, import_require.decl_id);
  654. // If `local_decl_id` is None, the resolver will have more work to do, and
  655. // we will call this function to try get all the decl instructions again.
  656. if (local_decl_id.has_value()) {
  657. // Importing the RequireImplsDecl instruction in `local_decl_id` also
  658. // imported the RequireImpls structure that it points to through the
  659. // RequireImplsId.
  660. require_decl_ids.push_back(
  661. resolver.local_insts()
  662. .GetAs<SemIR::RequireImplsDecl>(local_decl_id)
  663. .require_impls_id);
  664. }
  665. }
  666. return require_decl_ids;
  667. }
  668. // Gets the local block of RequireImplsIds from the imported block. Only valid
  669. // to call once there is no more work to do after the call to
  670. // GetLocalRequireImplsBlockContents().
  671. static auto GetLocalCanonicalRequireImplsBlockId(
  672. ImportContext& context, SemIR::RequireImplsBlockId import_block_id,
  673. llvm::ArrayRef<SemIR::RequireImplsId> contents)
  674. -> SemIR::RequireImplsBlockId {
  675. if (!import_block_id.has_value()) {
  676. return SemIR::RequireImplsBlockId::None;
  677. }
  678. return context.local_require_impls_blocks().Add(contents);
  679. }
  680. // Gets a local instruction block containing ImportRefs referring to the
  681. // instructions in the specified imported instruction block.
  682. static auto GetLocalImportRefInstBlock(ImportContext& context,
  683. SemIR::InstBlockId import_inst_block_id)
  684. -> SemIR::InstBlockId {
  685. llvm::SmallVector<SemIR::InstId> elements;
  686. auto import_elements = context.import_inst_blocks().Get(import_inst_block_id);
  687. elements.reserve(import_elements.size());
  688. for (auto element : import_elements) {
  689. elements.push_back(AddImportRef(context, element));
  690. }
  691. return context.local_inst_blocks().Add(elements);
  692. }
  693. // Gets an incomplete local version of an imported generic. Most fields are
  694. // set in the third phase.
  695. static auto MakeIncompleteGeneric(ImportContext& context, SemIR::InstId decl_id,
  696. SemIR::GenericId generic_id)
  697. -> SemIR::GenericId {
  698. if (!generic_id.has_value()) {
  699. return SemIR::GenericId::None;
  700. }
  701. return context.local_generics().Add(
  702. {.decl_id = decl_id,
  703. .bindings_id = SemIR::InstBlockId::None,
  704. .self_specific_id = SemIR::SpecificId::None});
  705. }
  706. namespace {
  707. // Local information associated with an imported generic.
  708. struct GenericData {
  709. // TODO: Delete `GenericData` if we still don't use it once generic import is
  710. // more stable.
  711. };
  712. } // namespace
  713. // Gets a local version of the data associated with a generic.
  714. static auto GetLocalGenericData(ImportRefResolver& /*resolver*/,
  715. SemIR::GenericId /*generic_id*/)
  716. -> GenericData {
  717. return {};
  718. }
  719. // Adds the given local generic data to the given generic.
  720. static auto SetGenericData(ImportContext& context,
  721. SemIR::GenericId import_generic_id,
  722. SemIR::GenericId new_generic_id,
  723. const GenericData& /*generic_data*/) -> void {
  724. if (!import_generic_id.has_value()) {
  725. return;
  726. }
  727. const auto& import_generic = context.import_generics().Get(import_generic_id);
  728. auto& new_generic = context.local_generics().Get(new_generic_id);
  729. new_generic.bindings_id =
  730. GetLocalImportRefInstBlock(context, import_generic.bindings_id);
  731. // Track that we need to fill in the remaining information in
  732. // FinishPendingGeneric.
  733. context.AddPendingGeneric(
  734. {.import_id = import_generic_id, .local_id = new_generic_id});
  735. }
  736. // Gets a local constant value corresponding to an imported generic ID. May
  737. // add work to the work stack and return `None`.
  738. static auto GetLocalConstantId(ImportRefResolver& resolver,
  739. SemIR::GenericId generic_id)
  740. -> SemIR::ConstantId {
  741. if (!generic_id.has_value()) {
  742. return SemIR::ConstantId::None;
  743. }
  744. auto import_decl_inst_id = resolver.import_generics().Get(generic_id).decl_id;
  745. auto import_decl_inst =
  746. resolver.import_insts().GetWithAttachedType(import_decl_inst_id);
  747. if (import_decl_inst.Is<SemIR::ImplDecl>()) {
  748. // For an impl declaration, the imported entity can be found via the
  749. // declaration.
  750. return GetLocalConstantId(resolver, import_decl_inst_id);
  751. }
  752. // For all other kinds of declaration, the imported entity can be found via
  753. // the type of the declaration.
  754. return GetLocalConstantId(resolver, import_decl_inst.type_id());
  755. }
  756. // Gets a local generic ID given the corresponding local constant ID returned
  757. // by GetLocalConstantId for the imported generic. Does not add any new work.
  758. static auto GetLocalGenericId(ImportContext& context,
  759. SemIR::ConstantId local_const_id)
  760. -> SemIR::GenericId {
  761. if (!local_const_id.has_value()) {
  762. return SemIR::GenericId::None;
  763. }
  764. auto inst = context.local_insts().Get(
  765. context.local_constant_values().GetInstId(local_const_id));
  766. CARBON_KIND_SWITCH(inst) {
  767. case CARBON_KIND(SemIR::FunctionType fn_type): {
  768. return context.local_functions().Get(fn_type.function_id).generic_id;
  769. }
  770. case CARBON_KIND(SemIR::GenericClassType class_type): {
  771. return context.local_classes().Get(class_type.class_id).generic_id;
  772. }
  773. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  774. return context.local_interfaces()
  775. .Get(interface_type.interface_id)
  776. .generic_id;
  777. }
  778. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  779. return context.local_impls().Get(impl_decl.impl_id).generic_id;
  780. }
  781. default: {
  782. CARBON_FATAL("Unexpected inst for generic declaration: {0}", inst);
  783. }
  784. }
  785. }
  786. namespace {
  787. // Local information associated with an imported specific.
  788. struct SpecificData {
  789. SemIR::ConstantId generic_const_id;
  790. llvm::SmallVector<SemIR::InstId> args;
  791. };
  792. } // namespace
  793. // Gets local information about an imported specific.
  794. static auto GetLocalSpecificData(ImportRefResolver& resolver,
  795. SemIR::SpecificId specific_id)
  796. -> SpecificData {
  797. if (!specific_id.has_value()) {
  798. return {.generic_const_id = SemIR::ConstantId::None, .args = {}};
  799. }
  800. const auto& specific = resolver.import_specifics().Get(specific_id);
  801. return {
  802. .generic_const_id = GetLocalConstantId(resolver, specific.generic_id),
  803. .args = GetLocalInstBlockContents(resolver, specific.args_id),
  804. };
  805. }
  806. // Gets a local specific whose data was already imported by
  807. // GetLocalSpecificData. Does not add any new work.
  808. static auto GetOrAddLocalSpecific(ImportContext& context,
  809. SemIR::SpecificId import_specific_id,
  810. const SpecificData& data)
  811. -> SemIR::SpecificId {
  812. if (!import_specific_id.has_value()) {
  813. return SemIR::SpecificId::None;
  814. }
  815. // Form a corresponding local specific ID.
  816. const auto& import_specific =
  817. context.import_specifics().Get(import_specific_id);
  818. auto generic_id = GetLocalGenericId(context, data.generic_const_id);
  819. auto args_id =
  820. GetLocalCanonicalInstBlockId(context, import_specific.args_id, data.args);
  821. // Get the specific.
  822. auto specific_id = context.local_specifics().GetOrAdd(generic_id, args_id);
  823. // Fill in the remaining information in FinishPendingSpecific, if necessary.
  824. auto& specific = context.local_specifics().Get(specific_id);
  825. if (!specific.decl_block_id.has_value() ||
  826. (import_specific.definition_block_id.has_value() &&
  827. !specific.definition_block_id.has_value())) {
  828. context.AddPendingSpecific(
  829. {.import_id = import_specific_id, .local_id = specific_id});
  830. }
  831. return specific_id;
  832. }
  833. namespace {
  834. struct SpecificInterfaceData {
  835. SemIR::ConstantId interface_const_id;
  836. SpecificData specific_data;
  837. };
  838. } // namespace
  839. static auto GetLocalSpecificInterfaceData(
  840. ImportRefResolver& resolver, SemIR::SpecificInterface import_interface)
  841. -> SpecificInterfaceData {
  842. SemIR::ConstantId interface_const_id = SemIR::ConstantId::None;
  843. if (import_interface.interface_id.has_value()) {
  844. interface_const_id =
  845. GetLocalConstantId(resolver, resolver.import_interfaces()
  846. .Get(import_interface.interface_id)
  847. .first_owning_decl_id);
  848. }
  849. return {.interface_const_id = interface_const_id,
  850. .specific_data =
  851. GetLocalSpecificData(resolver, import_interface.specific_id)};
  852. }
  853. static auto GetLocalSpecificInterface(
  854. ImportContext& context, SemIR::SpecificInterface import_specific_interface,
  855. SpecificInterfaceData interface_data) -> SemIR::SpecificInterface {
  856. if (!interface_data.interface_const_id.has_value()) {
  857. return SemIR::SpecificInterface::None;
  858. }
  859. // Find the corresponding interface type. For a non-generic interface,
  860. // this is the type of the interface declaration. For a generic interface,
  861. // build a interface type referencing this specialization of the generic
  862. // interface.
  863. auto interface_const_inst =
  864. context.local_insts().Get(context.local_constant_values().GetInstId(
  865. interface_data.interface_const_id));
  866. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  867. const SemIR::FacetTypeInfo& new_facet_type_info =
  868. context.local_facet_types().Get(facet_type->facet_type_id);
  869. return std::get<SemIR::SpecificInterface>(
  870. *new_facet_type_info.TryAsSingleExtend());
  871. } else {
  872. auto generic_interface_type =
  873. context.local_types().GetAs<SemIR::GenericInterfaceType>(
  874. interface_const_inst.type_id());
  875. auto specific_id =
  876. GetOrAddLocalSpecific(context, import_specific_interface.specific_id,
  877. interface_data.specific_data);
  878. return {generic_interface_type.interface_id, specific_id};
  879. }
  880. }
  881. namespace {
  882. struct SpecificNamedConstraintData {
  883. SemIR::ConstantId constraint_const_id;
  884. SpecificData specific_data;
  885. };
  886. } // namespace
  887. static auto GetLocalSpecificNamedConstraintData(
  888. ImportRefResolver& resolver,
  889. SemIR::SpecificNamedConstraint import_constraint)
  890. -> SpecificNamedConstraintData {
  891. SemIR::ConstantId constraint_const_id = SemIR::ConstantId::None;
  892. if (import_constraint.named_constraint_id.has_value()) {
  893. constraint_const_id = GetLocalConstantId(
  894. resolver, resolver.import_named_constraints()
  895. .Get(import_constraint.named_constraint_id)
  896. .first_owning_decl_id);
  897. }
  898. return {.constraint_const_id = constraint_const_id,
  899. .specific_data =
  900. GetLocalSpecificData(resolver, import_constraint.specific_id)};
  901. }
  902. static auto GetLocalSpecificNamedConstraint(
  903. ImportContext& context,
  904. SemIR::SpecificNamedConstraint import_specific_constraint,
  905. SpecificNamedConstraintData constraint_data)
  906. -> SemIR::SpecificNamedConstraint {
  907. if (!constraint_data.constraint_const_id.has_value()) {
  908. return SemIR::SpecificNamedConstraint::None;
  909. }
  910. // Find the corresponding named constraint type. For a non-generic constraint,
  911. // this is the type of the named constraint declaration. For a generic
  912. // constraint, build a named constraint type referencing this specialization
  913. // of the generic named constraint.
  914. auto constraint_const_inst =
  915. context.local_insts().Get(context.local_constant_values().GetInstId(
  916. constraint_data.constraint_const_id));
  917. if (auto facet_type = constraint_const_inst.TryAs<SemIR::FacetType>()) {
  918. const SemIR::FacetTypeInfo& new_facet_type_info =
  919. context.local_facet_types().Get(facet_type->facet_type_id);
  920. return std::get<SemIR::SpecificNamedConstraint>(
  921. *new_facet_type_info.TryAsSingleExtend());
  922. } else {
  923. auto generic_constraint_type =
  924. context.local_types().GetAs<SemIR::GenericNamedConstraintType>(
  925. constraint_const_inst.type_id());
  926. auto specific_id =
  927. GetOrAddLocalSpecific(context, import_specific_constraint.specific_id,
  928. constraint_data.specific_data);
  929. return {generic_constraint_type.named_constraint_id, specific_id};
  930. }
  931. }
  932. static auto GetLocalNameScopeIdImpl(ImportRefResolver& resolver,
  933. SemIR::ConstantId const_id)
  934. -> SemIR::NameScopeId {
  935. if (!const_id.has_value()) {
  936. return SemIR::NameScopeId::None;
  937. }
  938. auto const_inst_id = resolver.local_constant_values().GetInstId(const_id);
  939. auto name_scope_inst = resolver.local_insts().Get(const_inst_id);
  940. CARBON_KIND_SWITCH(name_scope_inst) {
  941. case CARBON_KIND(SemIR::Namespace inst): {
  942. return inst.name_scope_id;
  943. }
  944. case CARBON_KIND(SemIR::ClassType inst): {
  945. return resolver.local_classes().Get(inst.class_id).scope_id;
  946. }
  947. case CARBON_KIND(SemIR::FacetType inst): {
  948. const SemIR::FacetTypeInfo& facet_type_info =
  949. resolver.local_facet_types().Get(inst.facet_type_id);
  950. if (auto single = facet_type_info.TryAsSingleExtend()) {
  951. // This is the facet type produced by an interface or named constraint
  952. // declaration.
  953. CARBON_KIND_SWITCH(*single) {
  954. case CARBON_KIND(SemIR::SpecificInterface interface): {
  955. return resolver.local_interfaces()
  956. .Get(interface.interface_id)
  957. .scope_id;
  958. }
  959. case CARBON_KIND(SemIR::SpecificNamedConstraint constraint): {
  960. return resolver.local_named_constraints()
  961. .Get(constraint.named_constraint_id)
  962. .scope_id;
  963. }
  964. }
  965. }
  966. break;
  967. }
  968. case CARBON_KIND(SemIR::ImplDecl inst): {
  969. return resolver.local_impls().Get(inst.impl_id).scope_id;
  970. }
  971. case SemIR::StructValue::Kind: {
  972. auto type_inst =
  973. resolver.local_types().GetAsInst(name_scope_inst.type_id());
  974. CARBON_KIND_SWITCH(type_inst) {
  975. case CARBON_KIND(SemIR::GenericClassType inst): {
  976. return resolver.local_classes().Get(inst.class_id).scope_id;
  977. }
  978. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  979. return resolver.local_interfaces().Get(inst.interface_id).scope_id;
  980. }
  981. default: {
  982. break;
  983. }
  984. }
  985. break;
  986. }
  987. default: {
  988. if (const_inst_id == SemIR::ErrorInst::InstId) {
  989. return SemIR::NameScopeId::None;
  990. }
  991. break;
  992. }
  993. }
  994. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  995. name_scope_inst);
  996. }
  997. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  998. // unresolved constants to the resolver's work stack.
  999. static auto GetLocalNameScopeId(ImportRefResolver& resolver,
  1000. SemIR::NameScopeId name_scope_id)
  1001. -> SemIR::NameScopeId {
  1002. // Get the instruction that created the scope.
  1003. auto [inst_id, inst] =
  1004. resolver.import_name_scopes().GetInstIfValid(name_scope_id);
  1005. if (!inst) {
  1006. // Map scopes that aren't associated with an instruction to `None`. For now,
  1007. // such scopes aren't used, and we don't have a good way to remap them.
  1008. return SemIR::NameScopeId::None;
  1009. }
  1010. // Get the constant value for the scope.
  1011. auto const_id = GetLocalConstantId(resolver, inst_id);
  1012. if (!const_id.has_value()) {
  1013. return SemIR::NameScopeId::None;
  1014. }
  1015. auto result = GetLocalNameScopeIdImpl(resolver, const_id);
  1016. CARBON_CHECK(result.has_value());
  1017. return result;
  1018. }
  1019. // Given an imported entity base, returns an incomplete, local version of it.
  1020. //
  1021. // Most fields are set in the third phase once they're imported. Import enough
  1022. // of the parameter lists that we know whether this interface is a generic
  1023. // interface and can build the right constant value for it.
  1024. //
  1025. // TODO: Support extern.
  1026. static auto GetIncompleteLocalEntityBase(
  1027. ImportContext& context, SemIR::InstId decl_id,
  1028. const SemIR::EntityWithParamsBase& import_base)
  1029. -> SemIR::EntityWithParamsBase {
  1030. // Translate the extern_library_id if present.
  1031. auto extern_library_id = SemIR::LibraryNameId::None;
  1032. if (import_base.extern_library_id.has_value()) {
  1033. if (import_base.extern_library_id.index >= 0) {
  1034. auto val = context.import_string_literal_values().Get(
  1035. import_base.extern_library_id.AsStringLiteralValueId());
  1036. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  1037. context.local_string_literal_values().Add(val));
  1038. } else {
  1039. extern_library_id = import_base.extern_library_id;
  1040. }
  1041. }
  1042. return {
  1043. .name_id = GetLocalNameId(context, import_base.name_id),
  1044. .parent_scope_id = SemIR::NameScopeId::None,
  1045. .generic_id =
  1046. MakeIncompleteGeneric(context, decl_id, import_base.generic_id),
  1047. .first_param_node_id = Parse::NodeId::None,
  1048. .last_param_node_id = Parse::NodeId::None,
  1049. .pattern_block_id = SemIR::InstBlockId::None,
  1050. .implicit_param_patterns_id =
  1051. import_base.implicit_param_patterns_id.has_value()
  1052. ? SemIR::InstBlockId::Empty
  1053. : SemIR::InstBlockId::None,
  1054. .param_patterns_id = import_base.param_patterns_id.has_value()
  1055. ? SemIR::InstBlockId::Empty
  1056. : SemIR::InstBlockId::None,
  1057. .is_extern = import_base.is_extern,
  1058. .extern_library_id = extern_library_id,
  1059. .non_owning_decl_id = import_base.non_owning_decl_id.has_value()
  1060. ? decl_id
  1061. : SemIR::InstId::None,
  1062. .first_owning_decl_id = import_base.first_owning_decl_id.has_value()
  1063. ? decl_id
  1064. : SemIR::InstId::None,
  1065. };
  1066. }
  1067. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  1068. // lookup.
  1069. static auto AddNameScopeImportRefs(ImportContext& context,
  1070. const SemIR::NameScope& import_scope,
  1071. SemIR::NameScope& new_scope) -> void {
  1072. for (auto entry : import_scope.entries()) {
  1073. SemIR::ScopeLookupResult result = entry.result;
  1074. if (result.is_poisoned()) {
  1075. continue;
  1076. }
  1077. auto ref_id = AddImportRef(context, result.target_inst_id());
  1078. new_scope.AddRequired({.name_id = GetLocalNameId(context, entry.name_id),
  1079. .result = SemIR::ScopeLookupResult::MakeFound(
  1080. ref_id, result.access_kind())});
  1081. }
  1082. for (auto scope_inst_id : import_scope.extended_scopes()) {
  1083. new_scope.AddExtendedScope(AddImportRef(context, scope_inst_id));
  1084. }
  1085. }
  1086. // Given a block ID for a list of associated entities of a witness, returns a
  1087. // version localized to the current IR.
  1088. static auto AddAssociatedEntities(ImportContext& context,
  1089. SemIR::NameScopeId local_name_scope_id,
  1090. SemIR::InstBlockId associated_entities_id)
  1091. -> SemIR::InstBlockId {
  1092. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  1093. return SemIR::InstBlockId::Empty;
  1094. }
  1095. auto associated_entities =
  1096. context.import_inst_blocks().Get(associated_entities_id);
  1097. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  1098. new_associated_entities.reserve(associated_entities.size());
  1099. for (auto inst_id : associated_entities) {
  1100. // Determine the name of the associated entity, by switching on its kind.
  1101. SemIR::NameId import_name_id = SemIR::NameId::None;
  1102. if (auto assoc_const_decl =
  1103. context.import_insts().TryGetAs<SemIR::AssociatedConstantDecl>(
  1104. inst_id)) {
  1105. const auto& assoc_const = context.import_associated_constants().Get(
  1106. assoc_const_decl->assoc_const_id);
  1107. import_name_id = assoc_const.name_id;
  1108. } else if (auto function_decl =
  1109. context.import_insts().TryGetAs<SemIR::FunctionDecl>(
  1110. inst_id)) {
  1111. const auto& function =
  1112. context.import_functions().Get(function_decl->function_id);
  1113. import_name_id = function.name_id;
  1114. } else if (auto import_ref =
  1115. context.import_insts().TryGetAs<SemIR::AnyImportRef>(
  1116. inst_id)) {
  1117. import_name_id =
  1118. context.import_entity_names().Get(import_ref->entity_name_id).name_id;
  1119. } else {
  1120. // We don't need `GetWithAttachedType` here because we don't access the
  1121. // type.
  1122. CARBON_FATAL("Unhandled associated entity kind: {0}",
  1123. context.import_insts().Get(inst_id).kind());
  1124. }
  1125. auto name_id = GetLocalNameId(context, import_name_id);
  1126. auto entity_name_id = context.local_entity_names().Add(
  1127. {.name_id = name_id, .parent_scope_id = local_name_scope_id});
  1128. new_associated_entities.push_back(
  1129. AddImportRef(context, inst_id, entity_name_id));
  1130. }
  1131. return context.local_inst_blocks().Add(new_associated_entities);
  1132. }
  1133. namespace {
  1134. namespace Internal {
  1135. // Internal concept for instruction kinds that produce unique constants.
  1136. template <typename InstT>
  1137. concept HasUniqueConstantKind =
  1138. InstT::Kind.constant_kind() == SemIR::InstConstantKind::AlwaysUnique ||
  1139. InstT::Kind.constant_kind() == SemIR::InstConstantKind::ConditionalUnique;
  1140. } // namespace Internal
  1141. // The result of attempting to resolve an imported instruction to a constant.
  1142. struct ResolveResult {
  1143. // The new constant value, if known.
  1144. SemIR::ConstantId const_id;
  1145. // Newly created declaration whose value is being resolved, if any.
  1146. SemIR::InstId decl_id = SemIR::InstId::None;
  1147. // Whether resolution has been attempted once and needs to be retried.
  1148. bool retry = false;
  1149. // Produces a resolve result that tries resolving this instruction again. If
  1150. // `const_id` is specified, then this is the end of the second phase, and the
  1151. // constant value will be passed to the next resolution attempt. Otherwise,
  1152. // this is the end of the first phase.
  1153. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::None,
  1154. SemIR::InstId decl_id = SemIR::InstId::None)
  1155. -> ResolveResult {
  1156. return {.const_id = const_id, .decl_id = decl_id, .retry = true};
  1157. }
  1158. // Produces a resolve result that provides the given constant value. Requires
  1159. // that there is no new work.
  1160. static auto Done(SemIR::ConstantId const_id,
  1161. SemIR::InstId decl_id = SemIR::InstId::None)
  1162. -> ResolveResult {
  1163. return {.const_id = const_id, .decl_id = decl_id};
  1164. }
  1165. // Produces a resolve result that provides the given constant value. Retries
  1166. // instead if work has been added.
  1167. static auto RetryOrDone(ImportRefResolver& resolver,
  1168. SemIR::ConstantId const_id) -> ResolveResult {
  1169. if (resolver.HasNewWork()) {
  1170. return Retry();
  1171. }
  1172. return Done(const_id);
  1173. }
  1174. // Adds `inst` to the local context as a deduplicated constant and returns a
  1175. // successful `ResolveResult`. Requires that there is no new work.
  1176. //
  1177. // This implements phases 2 and 3 of resolving the inst (as described on
  1178. // `ImportRefResolver`) for the common case where those phases are combined.
  1179. // Cases where that isn't applicable should instead use
  1180. // `AddPlaceholderImportedInst` and `ReplacePlaceholderImportedInst`.
  1181. //
  1182. // This should not be used for instructions that represent declarations, or
  1183. // other instructions with `constant_kind == InstConstantKind::Unique`,
  1184. // because they should not be deduplicated.
  1185. template <typename InstT>
  1186. requires(!Internal::HasUniqueConstantKind<InstT>)
  1187. static auto Deduplicated(ImportRefResolver& resolver, InstT inst)
  1188. -> ResolveResult {
  1189. CARBON_CHECK(!resolver.HasNewWork());
  1190. // AddImportedConstant produces an unattached constant, so its type must
  1191. // be unattached as well.
  1192. inst.type_id =
  1193. resolver.local_context().types().GetUnattachedType(inst.type_id);
  1194. auto const_id = AddImportedConstant(resolver.local_context(), inst);
  1195. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1196. return Done(const_id);
  1197. }
  1198. // Adds `inst` to the local context as a unique constant and returns a
  1199. // successful `ResolveResult`. `import_inst_id` is the corresponding inst ID
  1200. // in the local context. Requires that there is no new work.
  1201. //
  1202. // This implements phases 2 and 3 of resolving the inst (as described on
  1203. // `ImportRefResolver`) for the common case where those phases are combined.
  1204. // Cases where that isn't applicable should instead use
  1205. // `AddPlaceholderImportedInst` and `ReplacePlaceholderImportedInst`.
  1206. //
  1207. // This should only be used for instructions that represent declarations, or
  1208. // other instructions with `constant_kind == InstConstantKind::Unique`,
  1209. // because it does not perform deduplication.
  1210. template <typename InstT>
  1211. requires Internal::HasUniqueConstantKind<InstT>
  1212. static auto Unique(ImportRefResolver& resolver, SemIR::InstId import_inst_id,
  1213. InstT inst) -> ResolveResult {
  1214. CARBON_CHECK(!resolver.HasNewWork());
  1215. auto inst_id = AddPlaceholderImportedInst(resolver, import_inst_id, inst);
  1216. auto const_id = SetConstantValue(resolver.local_context(), inst_id, inst);
  1217. CARBON_CHECK(const_id.is_constant(), "{0} is not constant", inst);
  1218. return Done(const_id, inst_id);
  1219. }
  1220. };
  1221. } // namespace
  1222. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1223. SemIR::AdaptDecl inst,
  1224. SemIR::InstId import_inst_id) -> ResolveResult {
  1225. auto adapted_type_const_id =
  1226. GetLocalConstantId(resolver, inst.adapted_type_inst_id);
  1227. if (resolver.HasNewWork()) {
  1228. return ResolveResult::Retry();
  1229. }
  1230. auto adapted_type_inst_id = AddLoadedImportRefForType(
  1231. resolver, inst.adapted_type_inst_id, adapted_type_const_id);
  1232. // Create a corresponding instruction to represent the declaration.
  1233. return ResolveResult::Unique<SemIR::AdaptDecl>(
  1234. resolver, import_inst_id, {.adapted_type_inst_id = adapted_type_inst_id});
  1235. }
  1236. template <typename ParamPatternT>
  1237. requires SemIR::Internal::HasInstCategory<SemIR::AnyParamPattern,
  1238. ParamPatternT>
  1239. static auto TryResolveTypedInst(ImportRefResolver& resolver, ParamPatternT inst,
  1240. SemIR::InstId import_inst_id) -> ResolveResult {
  1241. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1242. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  1243. if (resolver.HasNewWork()) {
  1244. return ResolveResult::Retry();
  1245. }
  1246. return ResolveResult::Unique<ParamPatternT>(
  1247. resolver, import_inst_id,
  1248. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1249. type_const_id),
  1250. .subpattern_id = subpattern_id,
  1251. .index = inst.index});
  1252. }
  1253. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1254. SemIR::ArrayType inst) -> ResolveResult {
  1255. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1256. auto element_type_inst_id =
  1257. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  1258. auto bound_id = GetLocalConstantInstId(resolver, inst.bound_id);
  1259. if (resolver.HasNewWork()) {
  1260. return ResolveResult::Retry();
  1261. }
  1262. return ResolveResult::Deduplicated<SemIR::ArrayType>(
  1263. resolver, {.type_id = SemIR::TypeType::TypeId,
  1264. .bound_id = bound_id,
  1265. .element_type_inst_id = element_type_inst_id});
  1266. }
  1267. static auto MakeAssociatedConstant(
  1268. ImportContext& context, const SemIR::AssociatedConstant& import_assoc_const,
  1269. SemIR::TypeId type_id)
  1270. -> std::pair<SemIR::AssociatedConstantId, SemIR::ConstantId> {
  1271. SemIR::AssociatedConstantDecl assoc_const_decl = {
  1272. .type_id = type_id,
  1273. .assoc_const_id = SemIR::AssociatedConstantId::None,
  1274. .decl_block_id = SemIR::InstBlockId::Empty};
  1275. auto assoc_const_decl_id = AddPlaceholderImportedInst(
  1276. context, import_assoc_const.decl_id, assoc_const_decl);
  1277. assoc_const_decl.assoc_const_id = context.local_associated_constants().Add({
  1278. .name_id = GetLocalNameId(context, import_assoc_const.name_id),
  1279. .parent_scope_id = SemIR::NameScopeId::None,
  1280. .decl_id = assoc_const_decl_id,
  1281. .generic_id = MakeIncompleteGeneric(context, assoc_const_decl_id,
  1282. import_assoc_const.generic_id),
  1283. .default_value_id =
  1284. import_assoc_const.default_value_id.has_value()
  1285. ? AddImportRef(context, import_assoc_const.default_value_id)
  1286. : SemIR::InstId::None,
  1287. });
  1288. // Write the associated constant ID into the AssociatedConstantDecl.
  1289. auto const_id = ReplacePlaceholderImportedInst(context, assoc_const_decl_id,
  1290. assoc_const_decl);
  1291. return {assoc_const_decl.assoc_const_id, const_id};
  1292. }
  1293. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1294. SemIR::AssociatedConstantDecl inst,
  1295. SemIR::ConstantId const_id) -> ResolveResult {
  1296. const auto& import_assoc_const =
  1297. resolver.import_associated_constants().Get(inst.assoc_const_id);
  1298. SemIR::AssociatedConstantId assoc_const_id =
  1299. SemIR::AssociatedConstantId::None;
  1300. if (!const_id.has_value()) {
  1301. // In the first phase, import the type of the associated constant.
  1302. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1303. if (resolver.HasNewWork()) {
  1304. return ResolveResult::Retry();
  1305. }
  1306. // In the second phase, create the associated constant and its declaration.
  1307. auto type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1308. type_const_id);
  1309. std::tie(assoc_const_id, const_id) =
  1310. MakeAssociatedConstant(resolver, import_assoc_const, type_id);
  1311. } else {
  1312. // In the third phase, compute the associated constant ID from the constant
  1313. // value of the declaration.
  1314. assoc_const_id =
  1315. resolver.local_insts()
  1316. .GetAs<SemIR::AssociatedConstantDecl>(
  1317. resolver.local_constant_values().GetInstId(const_id))
  1318. .assoc_const_id;
  1319. }
  1320. // Load the values to populate the entity with.
  1321. auto parent_scope_id =
  1322. GetLocalNameScopeId(resolver, import_assoc_const.parent_scope_id);
  1323. auto generic_data =
  1324. GetLocalGenericData(resolver, import_assoc_const.generic_id);
  1325. auto& new_assoc_const =
  1326. resolver.local_associated_constants().Get(assoc_const_id);
  1327. if (resolver.HasNewWork()) {
  1328. return ResolveResult::Retry(const_id, new_assoc_const.decl_id);
  1329. }
  1330. // Populate the entity.
  1331. new_assoc_const.parent_scope_id = parent_scope_id;
  1332. SetGenericData(resolver, import_assoc_const.generic_id,
  1333. new_assoc_const.generic_id, generic_data);
  1334. return ResolveResult::Done(const_id, new_assoc_const.decl_id);
  1335. }
  1336. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1337. SemIR::AssociatedEntity inst) -> ResolveResult {
  1338. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1339. if (resolver.HasNewWork()) {
  1340. return ResolveResult::Retry();
  1341. }
  1342. // Add a lazy reference to the target declaration.
  1343. auto decl_id = AddImportRef(resolver, inst.decl_id);
  1344. return ResolveResult::Deduplicated<SemIR::AssociatedEntity>(
  1345. resolver,
  1346. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1347. type_const_id),
  1348. .index = inst.index,
  1349. .decl_id = decl_id});
  1350. }
  1351. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1352. SemIR::AssociatedEntityType inst)
  1353. -> ResolveResult {
  1354. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1355. auto data =
  1356. GetLocalSpecificInterfaceData(resolver, inst.GetSpecificInterface());
  1357. if (resolver.HasNewWork()) {
  1358. return ResolveResult::Retry();
  1359. }
  1360. auto specific_interface =
  1361. GetLocalSpecificInterface(resolver, inst.GetSpecificInterface(), data);
  1362. return ResolveResult::Deduplicated<SemIR::AssociatedEntityType>(
  1363. resolver, {.type_id = SemIR::TypeType::TypeId,
  1364. .interface_id = specific_interface.interface_id,
  1365. .interface_specific_id = specific_interface.specific_id});
  1366. }
  1367. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1368. SemIR::BaseDecl inst,
  1369. SemIR::InstId import_inst_id) -> ResolveResult {
  1370. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1371. auto base_type_const_id =
  1372. GetLocalConstantId(resolver, inst.base_type_inst_id);
  1373. if (resolver.HasNewWork()) {
  1374. return ResolveResult::Retry();
  1375. }
  1376. auto base_type_inst_id = AddLoadedImportRefForType(
  1377. resolver, inst.base_type_inst_id, base_type_const_id);
  1378. // Create a corresponding instruction to represent the declaration.
  1379. return ResolveResult::Unique<SemIR::BaseDecl>(
  1380. resolver, import_inst_id,
  1381. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1382. type_const_id),
  1383. .base_type_inst_id = base_type_inst_id,
  1384. .index = inst.index});
  1385. }
  1386. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1387. SemIR::AliasBinding inst) -> ResolveResult {
  1388. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1389. return ResolveResult::RetryOrDone(resolver, value_id);
  1390. }
  1391. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1392. SemIR::SymbolicBinding inst) -> ResolveResult {
  1393. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1394. if (resolver.HasNewWork()) {
  1395. return ResolveResult::Retry();
  1396. }
  1397. auto entity_name_id =
  1398. GetLocalSymbolicEntityNameId(resolver, inst.entity_name_id);
  1399. return ResolveResult::Deduplicated<SemIR::SymbolicBinding>(
  1400. resolver,
  1401. {.type_id =
  1402. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1403. .entity_name_id = entity_name_id,
  1404. .value_id = SemIR::InstId::None});
  1405. }
  1406. template <typename BindingPatternT>
  1407. requires SemIR::Internal::HasInstCategory<SemIR::AnyBindingPattern,
  1408. BindingPatternT>
  1409. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1410. BindingPatternT inst,
  1411. SemIR::InstId import_inst_id) -> ResolveResult {
  1412. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1413. const auto& import_entity_name =
  1414. resolver.import_entity_names().Get(inst.entity_name_id);
  1415. auto parent_scope_id =
  1416. GetLocalNameScopeId(resolver, import_entity_name.parent_scope_id);
  1417. if (resolver.HasNewWork()) {
  1418. return ResolveResult::Retry();
  1419. }
  1420. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1421. auto entity_name_id = resolver.local_entity_names().Add(
  1422. {.name_id = name_id,
  1423. .parent_scope_id = parent_scope_id,
  1424. .bind_index_value = import_entity_name.bind_index().index,
  1425. .is_template = import_entity_name.is_template});
  1426. return ResolveResult::Unique<BindingPatternT>(
  1427. resolver, import_inst_id,
  1428. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1429. type_const_id),
  1430. .entity_name_id = entity_name_id});
  1431. }
  1432. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1433. SemIR::BoolLiteral inst) -> ResolveResult {
  1434. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1435. SemIR::BoolType::TypeInstId);
  1436. CARBON_CHECK(!resolver.HasNewWork());
  1437. return ResolveResult::Deduplicated<SemIR::BoolLiteral>(
  1438. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1439. SemIR::BoolType::TypeInstId),
  1440. .value = inst.value});
  1441. }
  1442. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1443. SemIR::BoundMethod inst) -> ResolveResult {
  1444. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1445. SemIR::BoundMethodType::TypeInstId);
  1446. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1447. auto function_decl_id =
  1448. GetLocalConstantInstId(resolver, inst.function_decl_id);
  1449. if (resolver.HasNewWork()) {
  1450. return ResolveResult::Retry();
  1451. }
  1452. return ResolveResult::Deduplicated<SemIR::BoundMethod>(
  1453. resolver,
  1454. {.type_id = GetSingletonType(resolver.local_context(),
  1455. SemIR::BoundMethodType::TypeInstId),
  1456. .object_id = object_id,
  1457. .function_decl_id = function_decl_id});
  1458. }
  1459. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1460. -> ResolveResult {
  1461. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1462. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1463. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1464. if (resolver.HasNewWork()) {
  1465. return ResolveResult::Retry();
  1466. }
  1467. return ResolveResult::Deduplicated<SemIR::Call>(
  1468. resolver,
  1469. {.type_id =
  1470. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1471. .callee_id = callee_id,
  1472. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1473. }
  1474. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1475. SemIR::CharLiteralValue inst) -> ResolveResult {
  1476. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1477. SemIR::CharLiteralType::TypeInstId);
  1478. CARBON_CHECK(!resolver.HasNewWork());
  1479. return ResolveResult::Deduplicated<SemIR::CharLiteralValue>(
  1480. resolver,
  1481. {.type_id = GetSingletonType(resolver.local_context(),
  1482. SemIR::CharLiteralType::TypeInstId),
  1483. .value = inst.value});
  1484. }
  1485. static auto AddPlaceholderNameScope(ImportContext& context)
  1486. -> SemIR::NameScopeId {
  1487. return context.local_name_scopes().Add(
  1488. SemIR::InstId::None, SemIR::NameId::None, SemIR::NameScopeId::None);
  1489. }
  1490. // Makes an incomplete class. This is necessary even with classes with a
  1491. // complete declaration, because things such as `Self` may refer back to the
  1492. // type.
  1493. static auto MakeIncompleteClass(ImportContext& context,
  1494. const SemIR::Class& import_class,
  1495. SemIR::SpecificId enclosing_specific_id)
  1496. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1497. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::TypeId,
  1498. .class_id = SemIR::ClassId::None,
  1499. .decl_block_id = SemIR::InstBlockId::Empty};
  1500. auto class_decl_id = AddPlaceholderImportedInst(
  1501. context, import_class.latest_decl_id(), class_decl);
  1502. // Regardless of whether ClassDecl is a complete type, we first need an
  1503. // incomplete type so that any references have something to point at.
  1504. class_decl.class_id = context.local_classes().Add(
  1505. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1506. {.self_type_id = SemIR::TypeId::None,
  1507. .inheritance_kind = import_class.inheritance_kind,
  1508. .is_dynamic = import_class.is_dynamic,
  1509. .scope_id = import_class.is_complete()
  1510. ? AddPlaceholderNameScope(context)
  1511. : SemIR::NameScopeId::None}});
  1512. if (import_class.has_parameters()) {
  1513. class_decl.type_id = GetGenericClassType(
  1514. context.local_context(), class_decl.class_id, enclosing_specific_id);
  1515. }
  1516. // Write the class ID into the ClassDecl.
  1517. auto self_const_id =
  1518. ReplacePlaceholderImportedInst(context, class_decl_id, class_decl);
  1519. return {class_decl.class_id, self_const_id};
  1520. }
  1521. static auto InitializeNameScopeAndImportRefs(
  1522. ImportContext& context, const SemIR::NameScope& import_scope,
  1523. SemIR::NameScope& new_scope, SemIR::InstId decl_id, SemIR::NameId name_id,
  1524. SemIR::NameScopeId parent_scope_id) {
  1525. new_scope.Set(decl_id, name_id, parent_scope_id);
  1526. AddNameScopeImportRefs(context, import_scope, new_scope);
  1527. }
  1528. // Fills out the class definition for an incomplete class.
  1529. static auto AddClassDefinition(ImportContext& context,
  1530. const SemIR::Class& import_class,
  1531. SemIR::Class& new_class,
  1532. SemIR::InstId complete_type_witness_id,
  1533. SemIR::InstId base_id, SemIR::InstId adapt_id,
  1534. SemIR::InstId vtable_decl_id) -> void {
  1535. new_class.definition_id = new_class.first_owning_decl_id;
  1536. new_class.complete_type_witness_id = complete_type_witness_id;
  1537. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1538. const auto& import_scope =
  1539. context.import_name_scopes().Get(import_class.scope_id);
  1540. // Push a block so that we can add scoped instructions to it.
  1541. context.local_context().inst_block_stack().Push();
  1542. InitializeNameScopeAndImportRefs(
  1543. context, import_scope, new_scope, new_class.first_owning_decl_id,
  1544. SemIR::NameId::None, new_class.parent_scope_id);
  1545. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1546. if (import_class.base_id.has_value()) {
  1547. new_class.base_id = base_id;
  1548. }
  1549. if (import_class.adapt_id.has_value()) {
  1550. new_class.adapt_id = adapt_id;
  1551. }
  1552. if (import_class.vtable_decl_id.has_value()) {
  1553. new_class.vtable_decl_id = vtable_decl_id;
  1554. }
  1555. }
  1556. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1557. SemIR::ClassDecl inst,
  1558. SemIR::ConstantId class_const_id)
  1559. -> ResolveResult {
  1560. // TODO: The handling of interfaces repeats a lot with the handling of
  1561. // classes, and will likely also be repeated for named constraints and
  1562. // choice types. Factor out some of this functionality.
  1563. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1564. SemIR::ClassId class_id = SemIR::ClassId::None;
  1565. if (!class_const_id.has_value()) {
  1566. auto import_specific_id = SemIR::SpecificId::None;
  1567. if (auto import_generic_class_type =
  1568. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1569. inst.type_id)) {
  1570. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1571. }
  1572. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1573. if (resolver.HasNewWork()) {
  1574. // This is the end of the first phase. Don't make a new class yet if
  1575. // we already have new work.
  1576. return ResolveResult::Retry();
  1577. }
  1578. // On the second phase, create a forward declaration of the class for any
  1579. // recursive references.
  1580. auto enclosing_specific_id =
  1581. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1582. std::tie(class_id, class_const_id) =
  1583. MakeIncompleteClass(resolver, import_class, enclosing_specific_id);
  1584. } else {
  1585. // On the third phase, compute the class ID from the constant
  1586. // value of the declaration.
  1587. auto class_const_inst = resolver.local_insts().Get(
  1588. resolver.local_constant_values().GetInstId(class_const_id));
  1589. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1590. class_id = class_type->class_id;
  1591. } else {
  1592. auto generic_class_type =
  1593. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1594. class_const_inst.type_id());
  1595. class_id = generic_class_type.class_id;
  1596. }
  1597. }
  1598. // Load constants for the definition.
  1599. auto parent_scope_id =
  1600. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1601. auto implicit_param_patterns = GetLocalInstBlockContents(
  1602. resolver, import_class.implicit_param_patterns_id);
  1603. auto param_patterns =
  1604. GetLocalInstBlockContents(resolver, import_class.param_patterns_id);
  1605. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1606. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1607. auto complete_type_witness_const_id =
  1608. import_class.complete_type_witness_id.has_value()
  1609. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1610. : SemIR::ConstantId::None;
  1611. auto base_id = import_class.base_id.has_value()
  1612. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1613. : SemIR::InstId::None;
  1614. auto adapt_id = import_class.adapt_id.has_value()
  1615. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1616. : SemIR::InstId::None;
  1617. auto vtable_decl_id =
  1618. import_class.vtable_decl_id.has_value()
  1619. ? AddImportRef(resolver, import_class.vtable_decl_id)
  1620. : SemIR::InstId::None;
  1621. auto& new_class = resolver.local_classes().Get(class_id);
  1622. if (resolver.HasNewWork()) {
  1623. return ResolveResult::Retry(class_const_id, new_class.first_decl_id());
  1624. }
  1625. new_class.parent_scope_id = parent_scope_id;
  1626. new_class.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1627. resolver, import_class.implicit_param_patterns_id,
  1628. implicit_param_patterns);
  1629. new_class.param_patterns_id = GetLocalCanonicalInstBlockId(
  1630. resolver, import_class.param_patterns_id, param_patterns);
  1631. SetGenericData(resolver, import_class.generic_id, new_class.generic_id,
  1632. generic_data);
  1633. new_class.self_type_id =
  1634. resolver.local_context().types().GetTypeIdForTypeConstantId(
  1635. self_const_id);
  1636. if (import_class.is_complete()) {
  1637. auto complete_type_witness_id = AddLoadedImportRef(
  1638. resolver,
  1639. GetSingletonType(resolver.local_context(),
  1640. SemIR::WitnessType::TypeInstId),
  1641. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1642. AddClassDefinition(resolver, import_class, new_class,
  1643. complete_type_witness_id, base_id, adapt_id,
  1644. vtable_decl_id);
  1645. }
  1646. return ResolveResult::Done(class_const_id, new_class.first_decl_id());
  1647. }
  1648. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1649. SemIR::ClassType inst) -> ResolveResult {
  1650. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1651. auto class_const_id = GetLocalConstantId(
  1652. resolver,
  1653. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1654. if (class_const_id == SemIR::ErrorInst::ConstantId) {
  1655. // TODO: It should be possible to remove this once C++ imports work.
  1656. return ResolveResult::Done(class_const_id);
  1657. }
  1658. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1659. if (resolver.HasNewWork()) {
  1660. return ResolveResult::Retry();
  1661. }
  1662. // Find the corresponding class type. For a non-generic class, this is the
  1663. // type of the class declaration. For a generic class, build a class type
  1664. // referencing this specialization of the generic class.
  1665. auto class_const_inst = resolver.local_insts().Get(
  1666. resolver.local_constant_values().GetInstId(class_const_id));
  1667. if (class_const_inst.Is<SemIR::ClassType>()) {
  1668. return ResolveResult::Done(class_const_id);
  1669. } else {
  1670. auto generic_class_type =
  1671. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1672. class_const_inst.type_id());
  1673. auto specific_id =
  1674. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1675. return ResolveResult::Deduplicated<SemIR::ClassType>(
  1676. resolver, {.type_id = SemIR::TypeType::TypeId,
  1677. .class_id = generic_class_type.class_id,
  1678. .specific_id = specific_id});
  1679. }
  1680. }
  1681. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1682. SemIR::CompleteTypeWitness inst)
  1683. -> ResolveResult {
  1684. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1685. SemIR::WitnessType::TypeInstId);
  1686. auto object_repr_type_inst_id =
  1687. GetLocalTypeInstId(resolver, inst.object_repr_type_inst_id);
  1688. if (resolver.HasNewWork()) {
  1689. return ResolveResult::Retry();
  1690. }
  1691. return ResolveResult::Deduplicated<SemIR::CompleteTypeWitness>(
  1692. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  1693. SemIR::WitnessType::TypeInstId),
  1694. .object_repr_type_inst_id = object_repr_type_inst_id});
  1695. }
  1696. template <typename InstT>
  1697. requires SemIR::Internal::HasInstCategory<SemIR::AnyQualifiedType, InstT>
  1698. static auto TryResolveTypedInst(ImportRefResolver& resolver, InstT inst)
  1699. -> ResolveResult {
  1700. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1701. auto inner_id = GetLocalTypeInstId(resolver, inst.inner_id);
  1702. if (resolver.HasNewWork()) {
  1703. return ResolveResult::Retry();
  1704. }
  1705. return ResolveResult::Deduplicated<InstT>(
  1706. resolver, {.type_id = SemIR::TypeType::TypeId, .inner_id = inner_id});
  1707. }
  1708. static auto HandleUnsupportedCppOverloadSet(ImportRefResolver& resolver,
  1709. SemIR::CppOverloadSetId id) {
  1710. // Supporting C++ overload resolution of imported functions is a large task,
  1711. // which might require serializing and deserializing AST for using decl ids,
  1712. // using modules and/or linking ASTs.
  1713. resolver.local_context().TODO(
  1714. SemIR::LocId::None,
  1715. llvm::formatv(
  1716. "Unsupported: Importing C++ function `{0}` indirectly",
  1717. resolver.import_ir().names().GetAsStringIfIdentifier(
  1718. resolver.import_ir().cpp_overload_sets().Get(id).name_id)));
  1719. return ResolveResult::Done(SemIR::ErrorInst::ConstantId,
  1720. SemIR::ErrorInst::InstId);
  1721. }
  1722. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1723. SemIR::CppOverloadSetType inst)
  1724. -> ResolveResult {
  1725. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1726. }
  1727. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1728. SemIR::CppOverloadSetValue inst)
  1729. -> ResolveResult {
  1730. return HandleUnsupportedCppOverloadSet(resolver, inst.overload_set_id);
  1731. }
  1732. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1733. SemIR::ExportDecl inst) -> ResolveResult {
  1734. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1735. return ResolveResult::RetryOrDone(resolver, value_id);
  1736. }
  1737. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1738. SemIR::FieldDecl inst,
  1739. SemIR::InstId import_inst_id) -> ResolveResult {
  1740. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1741. if (resolver.HasNewWork()) {
  1742. return ResolveResult::Retry();
  1743. }
  1744. return ResolveResult::Unique<SemIR::FieldDecl>(
  1745. resolver, import_inst_id,
  1746. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  1747. const_id),
  1748. .name_id = GetLocalNameId(resolver, inst.name_id),
  1749. .index = inst.index});
  1750. }
  1751. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1752. SemIR::FloatLiteralValue inst)
  1753. -> ResolveResult {
  1754. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1755. SemIR::FloatLiteralType::TypeInstId);
  1756. CARBON_CHECK(!resolver.HasNewWork());
  1757. auto real_id = resolver.local_ir().reals().Add(
  1758. resolver.import_ir().reals().Get(inst.real_id));
  1759. return ResolveResult::Deduplicated<SemIR::FloatLiteralValue>(
  1760. resolver,
  1761. {.type_id = GetSingletonType(resolver.local_context(),
  1762. SemIR::FloatLiteralType::TypeInstId),
  1763. .real_id = real_id});
  1764. }
  1765. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1766. SemIR::FloatType inst) -> ResolveResult {
  1767. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1768. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  1769. if (resolver.HasNewWork()) {
  1770. return ResolveResult::Retry();
  1771. }
  1772. return ResolveResult::Deduplicated<SemIR::FloatType>(
  1773. resolver, {.type_id = SemIR::TypeType::TypeId,
  1774. .bit_width_id = bit_width_id,
  1775. .float_kind = inst.float_kind});
  1776. }
  1777. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1778. SemIR::FloatValue inst) -> ResolveResult {
  1779. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1780. if (resolver.HasNewWork()) {
  1781. return ResolveResult::Retry();
  1782. }
  1783. auto float_id = resolver.local_ir().floats().Add(
  1784. resolver.import_ir().floats().Get(inst.float_id));
  1785. return ResolveResult::Deduplicated<SemIR::FloatValue>(
  1786. resolver,
  1787. {.type_id =
  1788. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  1789. .float_id = float_id});
  1790. }
  1791. // Make a declaration of a function. This is done as a separate step from
  1792. // importing the function declaration in order to resolve cycles.
  1793. static auto MakeFunctionDecl(ImportContext& context,
  1794. const SemIR::Function& import_function,
  1795. SemIR::SpecificId specific_id)
  1796. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1797. SemIR::FunctionDecl function_decl = {
  1798. .type_id = SemIR::TypeId::None,
  1799. .function_id = SemIR::FunctionId::None,
  1800. .decl_block_id = SemIR::InstBlockId::Empty};
  1801. auto function_decl_id = AddPlaceholderImportedInst(
  1802. context, import_function.first_decl_id(), function_decl);
  1803. // Start with an incomplete function.
  1804. function_decl.function_id = context.local_functions().Add(
  1805. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  1806. {.call_params_id = SemIR::InstBlockId::None,
  1807. .return_slot_pattern_id = SemIR::InstId::None,
  1808. .virtual_modifier = import_function.virtual_modifier,
  1809. .virtual_index = import_function.virtual_index}});
  1810. // Directly add the function type constant. Don't use `GetFunctionType`
  1811. // because that will evaluate the function type, which we can't do if the
  1812. // specific's value block is still pending.
  1813. auto type_const_id = AddImportedConstant(
  1814. context.local_context(),
  1815. SemIR::FunctionType{.type_id = SemIR::TypeType::TypeId,
  1816. .function_id = function_decl.function_id,
  1817. .specific_id = specific_id});
  1818. function_decl.type_id =
  1819. context.local_types().GetTypeIdForTypeConstantId(type_const_id);
  1820. // Write the function ID and type into the FunctionDecl.
  1821. auto function_const_id =
  1822. ReplacePlaceholderImportedInst(context, function_decl_id, function_decl);
  1823. return {function_decl.function_id, function_const_id};
  1824. }
  1825. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1826. SemIR::FunctionDecl inst,
  1827. SemIR::ConstantId function_const_id)
  1828. -> ResolveResult {
  1829. const auto& import_function =
  1830. resolver.import_functions().Get(inst.function_id);
  1831. SemIR::FunctionId function_id = SemIR::FunctionId::None;
  1832. if (!function_const_id.has_value()) {
  1833. auto import_specific_id = resolver.import_types()
  1834. .GetAs<SemIR::FunctionType>(inst.type_id)
  1835. .specific_id;
  1836. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1837. if (resolver.HasNewWork()) {
  1838. // This is the end of the first phase. Don't make a new function yet if
  1839. // we already have new work.
  1840. return ResolveResult::Retry();
  1841. }
  1842. // On the second phase, create a forward declaration of the interface.
  1843. auto specific_id =
  1844. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1845. std::tie(function_id, function_const_id) =
  1846. MakeFunctionDecl(resolver, import_function, specific_id);
  1847. } else {
  1848. // On the third phase, compute the function ID from the constant value of
  1849. // the declaration.
  1850. auto function_const_inst = resolver.local_insts().Get(
  1851. resolver.local_constant_values().GetInstId(function_const_id));
  1852. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  1853. function_const_inst.type_id());
  1854. function_id = function_type.function_id;
  1855. }
  1856. auto return_type_const_id = SemIR::ConstantId::None;
  1857. if (import_function.return_slot_pattern_id.has_value()) {
  1858. return_type_const_id = GetLocalConstantId(
  1859. resolver, resolver.import_insts().GetAttachedType(
  1860. import_function.return_slot_pattern_id));
  1861. }
  1862. auto parent_scope_id =
  1863. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  1864. auto implicit_param_patterns = GetLocalInstBlockContents(
  1865. resolver, import_function.implicit_param_patterns_id);
  1866. auto param_patterns =
  1867. GetLocalInstBlockContents(resolver, import_function.param_patterns_id);
  1868. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  1869. auto self_param_id =
  1870. GetLocalConstantInstId(resolver, import_function.self_param_id);
  1871. auto return_slot_pattern_id =
  1872. GetLocalConstantInstId(resolver, import_function.return_slot_pattern_id);
  1873. auto& new_function = resolver.local_functions().Get(function_id);
  1874. if (resolver.HasNewWork()) {
  1875. return ResolveResult::Retry(function_const_id,
  1876. new_function.first_decl_id());
  1877. }
  1878. // Add the function declaration.
  1879. new_function.parent_scope_id = parent_scope_id;
  1880. new_function.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  1881. resolver, import_function.implicit_param_patterns_id,
  1882. implicit_param_patterns);
  1883. new_function.self_param_id = self_param_id;
  1884. new_function.param_patterns_id = GetLocalCanonicalInstBlockId(
  1885. resolver, import_function.param_patterns_id, param_patterns);
  1886. new_function.return_slot_pattern_id = return_slot_pattern_id;
  1887. SetGenericData(resolver, import_function.generic_id, new_function.generic_id,
  1888. generic_data);
  1889. if (import_function.definition_id.has_value()) {
  1890. new_function.definition_id = new_function.first_owning_decl_id;
  1891. }
  1892. switch (import_function.special_function_kind) {
  1893. case SemIR::Function::SpecialFunctionKind::None: {
  1894. break;
  1895. }
  1896. case SemIR::Function::SpecialFunctionKind::Builtin: {
  1897. new_function.SetBuiltinFunction(import_function.builtin_function_kind());
  1898. break;
  1899. }
  1900. case SemIR::Function::SpecialFunctionKind::Thunk: {
  1901. auto entity_name_id = resolver.local_entity_names().AddCanonical(
  1902. {.name_id = new_function.name_id,
  1903. .parent_scope_id = new_function.parent_scope_id});
  1904. new_function.SetThunk(AddImportRef(
  1905. resolver, import_function.thunk_decl_id(), entity_name_id));
  1906. break;
  1907. }
  1908. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  1909. resolver.local_context().TODO(SemIR::LocId::None,
  1910. "Unsupported: Importing C++ functions that "
  1911. "require thunks indirectly");
  1912. }
  1913. }
  1914. return ResolveResult::Done(function_const_id, new_function.first_decl_id());
  1915. }
  1916. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1917. SemIR::VtableDecl inst) -> ResolveResult {
  1918. const auto& import_vtable = resolver.import_vtables().Get(inst.vtable_id);
  1919. auto class_const_id =
  1920. GetLocalConstantId(resolver, resolver.import_classes()
  1921. .Get(import_vtable.class_id)
  1922. .first_owning_decl_id);
  1923. auto class_const_inst = resolver.local_insts().Get(
  1924. resolver.local_constant_values().GetInstId(class_const_id));
  1925. // TODO: Ensure the vtable is only imported once, in eg: if there's distinct
  1926. // vtable constants (imported from multiple libraries using the vtable) that
  1927. // refer to the same vtable, the vtable should still be singular.
  1928. auto virtual_functions =
  1929. resolver.import_inst_blocks().Get(import_vtable.virtual_functions_id);
  1930. llvm::SmallVector<SemIR::InstId> lazy_virtual_functions;
  1931. lazy_virtual_functions.reserve(virtual_functions.size());
  1932. for (auto vtable_entry_id : virtual_functions) {
  1933. auto local_attached_constant_id =
  1934. GetLocalConstantId(resolver, vtable_entry_id);
  1935. lazy_virtual_functions.push_back(
  1936. resolver.local_constant_values().GetInstIdIfValid(
  1937. local_attached_constant_id));
  1938. }
  1939. if (resolver.HasNewWork()) {
  1940. return ResolveResult::Retry();
  1941. }
  1942. for (auto [import_vtable_entry_inst_id, local_vtable_entry_inst_id] :
  1943. llvm::zip_equal(virtual_functions, lazy_virtual_functions)) {
  1944. // Use LoadedImportRef for imported symbolic constant vtable entries so they
  1945. // can carry attached constants necessary for applying specifics to these
  1946. // constants when they are used.
  1947. auto local_attached_constant_id =
  1948. resolver.local_constant_values().GetAttached(
  1949. local_vtable_entry_inst_id);
  1950. if (local_attached_constant_id.is_symbolic()) {
  1951. local_vtable_entry_inst_id = AddLoadedImportRef(
  1952. resolver,
  1953. GetSingletonType(resolver.local_context(),
  1954. SemIR::SpecificFunctionType::TypeInstId),
  1955. import_vtable_entry_inst_id, local_attached_constant_id);
  1956. }
  1957. }
  1958. auto class_id = SemIR::ClassId::None;
  1959. if (class_const_inst.Is<SemIR::ClassType>()) {
  1960. class_id = class_const_inst.As<SemIR::ClassType>().class_id;
  1961. } else {
  1962. auto generic_class_type =
  1963. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1964. class_const_inst.type_id());
  1965. class_id = generic_class_type.class_id;
  1966. }
  1967. auto new_vtable_id = resolver.local_vtables().Add(
  1968. {{.class_id = class_id,
  1969. .virtual_functions_id =
  1970. resolver.local_inst_blocks().Add(lazy_virtual_functions)}});
  1971. return ResolveResult::Deduplicated<SemIR::VtableDecl>(
  1972. resolver, {.type_id = GetPointerType(resolver.local_context(),
  1973. SemIR::VtableType::TypeInstId),
  1974. .vtable_id = new_vtable_id});
  1975. }
  1976. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1977. SemIR::VtablePtr inst) -> ResolveResult {
  1978. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1979. auto vtable_const_id = GetLocalConstantId(
  1980. resolver, resolver.import_classes()
  1981. .Get(resolver.import_vtables().Get(inst.vtable_id).class_id)
  1982. .vtable_decl_id);
  1983. auto vtable_const_inst = resolver.local_insts().Get(
  1984. resolver.local_constant_values().GetInstId(vtable_const_id));
  1985. if (resolver.HasNewWork()) {
  1986. return ResolveResult::Retry();
  1987. }
  1988. return ResolveResult::Deduplicated<SemIR::VtablePtr>(
  1989. resolver,
  1990. {.type_id = GetPointerType(resolver.local_context(),
  1991. SemIR::VtableType::TypeInstId),
  1992. .vtable_id = vtable_const_inst.As<SemIR::VtableDecl>().vtable_id,
  1993. .specific_id =
  1994. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data)});
  1995. }
  1996. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1997. SemIR::FunctionType inst) -> ResolveResult {
  1998. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  1999. auto fn_val_id = GetLocalConstantInstId(
  2000. resolver,
  2001. resolver.import_functions().Get(inst.function_id).first_decl_id());
  2002. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2003. if (resolver.HasNewWork()) {
  2004. return ResolveResult::Retry();
  2005. }
  2006. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  2007. return ResolveResult::Deduplicated<SemIR::FunctionType>(
  2008. resolver, {.type_id = SemIR::TypeType::TypeId,
  2009. .function_id = resolver.local_types()
  2010. .GetAs<SemIR::FunctionType>(fn_type_id)
  2011. .function_id,
  2012. .specific_id = GetOrAddLocalSpecific(
  2013. resolver, inst.specific_id, specific_data)});
  2014. }
  2015. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2016. SemIR::FunctionTypeWithSelfType inst)
  2017. -> ResolveResult {
  2018. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2019. auto interface_function_type_id =
  2020. GetLocalTypeInstId(resolver, inst.interface_function_type_id);
  2021. auto self_id = GetLocalConstantInstId(resolver, inst.self_id);
  2022. if (resolver.HasNewWork()) {
  2023. return ResolveResult::Retry();
  2024. }
  2025. return ResolveResult::Deduplicated<SemIR::FunctionTypeWithSelfType>(
  2026. resolver, {.type_id = SemIR::TypeType::TypeId,
  2027. .interface_function_type_id = interface_function_type_id,
  2028. .self_id = self_id});
  2029. }
  2030. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2031. SemIR::GenericClassType inst) -> ResolveResult {
  2032. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2033. auto class_val_id = GetLocalConstantInstId(
  2034. resolver,
  2035. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  2036. if (resolver.HasNewWork()) {
  2037. return ResolveResult::Retry();
  2038. }
  2039. auto class_val = resolver.local_insts().Get(class_val_id);
  2040. CARBON_CHECK(
  2041. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  2042. return ResolveResult::Done(
  2043. resolver.local_types().GetConstantId(class_val.type_id()));
  2044. }
  2045. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2046. SemIR::GenericInterfaceType inst)
  2047. -> ResolveResult {
  2048. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2049. auto interface_val_id = GetLocalConstantInstId(
  2050. resolver,
  2051. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  2052. if (resolver.HasNewWork()) {
  2053. return ResolveResult::Retry();
  2054. }
  2055. auto interface_val = resolver.local_insts().Get(interface_val_id);
  2056. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  2057. interface_val.type_id()));
  2058. return ResolveResult::Done(
  2059. resolver.local_types().GetConstantId(interface_val.type_id()));
  2060. }
  2061. // Make a declaration of an impl. This is done as a separate step from
  2062. // importing the impl definition in order to resolve cycles.
  2063. static auto MakeImplDeclaration(ImportContext& context,
  2064. const SemIR::Impl& import_impl,
  2065. SemIR::InstId witness_id)
  2066. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  2067. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::None,
  2068. .decl_block_id = SemIR::InstBlockId::Empty};
  2069. auto impl_decl_id = AddPlaceholderImportedInst(
  2070. context, import_impl.latest_decl_id(), impl_decl);
  2071. impl_decl.impl_id = context.local_impls().Add(
  2072. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  2073. {.self_id = SemIR::TypeInstId::None,
  2074. .constraint_id = SemIR::TypeInstId::None,
  2075. .interface = SemIR::SpecificInterface::None,
  2076. .witness_id = witness_id,
  2077. .scope_id = import_impl.is_complete() ? AddPlaceholderNameScope(context)
  2078. : SemIR::NameScopeId::None,
  2079. .is_final = import_impl.is_final}});
  2080. // Write the impl ID into the ImplDecl.
  2081. auto impl_const_id =
  2082. ReplacePlaceholderImportedInst(context, impl_decl_id, impl_decl);
  2083. return {impl_decl.impl_id, impl_const_id};
  2084. }
  2085. // Imports the definition of an impl.
  2086. static auto AddImplDefinition(ImportContext& context,
  2087. const SemIR::Impl& import_impl,
  2088. SemIR::Impl& new_impl) -> void {
  2089. new_impl.definition_id = new_impl.first_owning_decl_id;
  2090. new_impl.defined = true;
  2091. if (import_impl.scope_id.has_value()) {
  2092. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  2093. new_scope.Set(new_impl.first_owning_decl_id, SemIR::NameId::None,
  2094. new_impl.parent_scope_id);
  2095. // Import the contents of the definition scope, if we might need it. Name
  2096. // lookup is never performed into this scope by a user of the impl, so
  2097. // this is only necessary in the same library that defined the impl, in
  2098. // order to support defining members of the impl out of line in the impl
  2099. // file when the impl is defined in the API file.
  2100. // TODO: Check to see if this impl is owned by the API file, rather than
  2101. // merely being imported into it.
  2102. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2103. const auto& import_scope =
  2104. context.import_name_scopes().Get(import_impl.scope_id);
  2105. // Push a block so that we can add scoped instructions to it.
  2106. context.local_context().inst_block_stack().Push();
  2107. AddNameScopeImportRefs(context, import_scope, new_scope);
  2108. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  2109. }
  2110. }
  2111. }
  2112. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2113. SemIR::ImplDecl inst,
  2114. SemIR::ConstantId impl_const_id)
  2115. -> ResolveResult {
  2116. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  2117. // functions. Factor out the commonality.
  2118. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2119. auto specific_interface_data =
  2120. GetLocalSpecificInterfaceData(resolver, import_impl.interface);
  2121. SemIR::ImplId impl_id = SemIR::ImplId::None;
  2122. if (!impl_const_id.has_value()) {
  2123. if (resolver.HasNewWork()) {
  2124. // This is the end of the first phase. Don't make a new impl yet if we
  2125. // already have new work.
  2126. return ResolveResult::Retry();
  2127. }
  2128. // On the second phase, create a forward declaration of the impl for any
  2129. // recursive references.
  2130. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  2131. std::tie(impl_id, impl_const_id) =
  2132. MakeImplDeclaration(resolver, import_impl, witness_id);
  2133. } else {
  2134. // On the third phase, compute the impl ID from the "constant value" of
  2135. // the declaration, which is a reference to the created ImplDecl.
  2136. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  2137. resolver.local_constant_values().GetInstId(impl_const_id));
  2138. impl_id = impl_const_inst.impl_id;
  2139. }
  2140. // Load constants for the definition.
  2141. auto parent_scope_id =
  2142. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  2143. auto implicit_param_patterns = GetLocalInstBlockContents(
  2144. resolver, import_impl.implicit_param_patterns_id);
  2145. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  2146. auto self_const_id = GetLocalConstantId(resolver, import_impl.self_id);
  2147. auto constraint_const_id =
  2148. GetLocalConstantId(resolver, import_impl.constraint_id);
  2149. auto& new_impl = resolver.local_impls().Get(impl_id);
  2150. if (resolver.HasNewWork()) {
  2151. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  2152. }
  2153. new_impl.parent_scope_id = parent_scope_id;
  2154. new_impl.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2155. resolver, import_impl.implicit_param_patterns_id,
  2156. implicit_param_patterns);
  2157. SetGenericData(resolver, import_impl.generic_id, new_impl.generic_id,
  2158. generic_data);
  2159. // Create instructions for self and constraint to hold the symbolic constant
  2160. // value for a generic impl.
  2161. new_impl.self_id =
  2162. AddLoadedImportRefForType(resolver, import_impl.self_id, self_const_id);
  2163. new_impl.constraint_id = AddLoadedImportRefForType(
  2164. resolver, import_impl.constraint_id, constraint_const_id);
  2165. new_impl.interface = GetLocalSpecificInterface(
  2166. resolver, import_impl.interface, specific_interface_data);
  2167. if (import_impl.is_complete()) {
  2168. AddImplDefinition(resolver, import_impl, new_impl);
  2169. }
  2170. // If the `impl` is declared in the API file corresponding to the current
  2171. // file, add this to impl lookup so that it can be found by redeclarations
  2172. // in the current file.
  2173. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  2174. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  2175. }
  2176. return ResolveResult::Done(impl_const_id, new_impl.first_decl_id());
  2177. }
  2178. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2179. SemIR::RequireImplsDecl inst) -> ResolveResult {
  2180. const auto& import_require =
  2181. resolver.import_require_impls().Get(inst.require_impls_id);
  2182. // Load dependent constants.
  2183. auto parent_scope_id =
  2184. GetLocalNameScopeId(resolver, import_require.parent_scope_id);
  2185. auto generic_data = GetLocalGenericData(resolver, import_require.generic_id);
  2186. auto self_const_id = GetLocalConstantId(resolver, import_require.self_id);
  2187. auto facet_type_const_id =
  2188. GetLocalConstantId(resolver, import_require.facet_type_inst_id);
  2189. if (resolver.HasNewWork()) {
  2190. return ResolveResult::Retry();
  2191. }
  2192. // Make the decl and structure with placeholder values to be filled in.
  2193. SemIR::RequireImplsDecl require_decl = {
  2194. .require_impls_id = SemIR::RequireImplsId::None,
  2195. .decl_block_id = SemIR::InstBlockId::Empty};
  2196. auto require_decl_id = AddPlaceholderImportedInst(
  2197. resolver, import_require.decl_id, require_decl);
  2198. auto require_impls_id = resolver.local_require_impls().Add(
  2199. {.self_id = SemIR::TypeInstId::None,
  2200. .facet_type_inst_id = SemIR::TypeInstId::None,
  2201. .facet_type_id = SemIR::FacetTypeId::None,
  2202. .decl_id = require_decl_id,
  2203. .parent_scope_id = SemIR::NameScopeId::None,
  2204. .generic_id = MakeIncompleteGeneric(resolver, require_decl_id,
  2205. import_require.generic_id)});
  2206. // Write the RequireImplsId into the RequireImplsDecl.
  2207. require_decl.require_impls_id = require_impls_id;
  2208. auto require_decl_const_id =
  2209. ReplacePlaceholderImportedInst(resolver, require_decl_id, require_decl);
  2210. // Fill in the RequireImpls structure.
  2211. auto& new_require = resolver.local_require_impls().Get(require_impls_id);
  2212. new_require.self_id = AddLoadedImportRefForType(
  2213. resolver, import_require.self_id, self_const_id);
  2214. new_require.facet_type_inst_id = AddLoadedImportRefForType(
  2215. resolver, import_require.facet_type_inst_id, facet_type_const_id);
  2216. auto new_canonical_facet_type_inst_id =
  2217. resolver.local_constant_values().GetConstantInstId(
  2218. new_require.facet_type_inst_id);
  2219. auto new_canonical_facet_type =
  2220. resolver.local_insts().GetAs<SemIR::FacetType>(
  2221. new_canonical_facet_type_inst_id);
  2222. new_require.facet_type_id = new_canonical_facet_type.facet_type_id;
  2223. new_require.extend_self = import_require.extend_self;
  2224. new_require.parent_scope_id = parent_scope_id;
  2225. SetGenericData(resolver, import_require.generic_id, new_require.generic_id,
  2226. generic_data);
  2227. return ResolveResult::Done(require_decl_const_id, require_decl_id);
  2228. }
  2229. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2230. SemIR::ImportRefLoaded /*inst*/,
  2231. SemIR::InstId inst_id) -> ResolveResult {
  2232. // Return the constant for the instruction of the imported constant.
  2233. auto constant_id = resolver.import_constant_values().Get(inst_id);
  2234. CARBON_CHECK(constant_id.has_value(),
  2235. "Loaded import ref has no constant value");
  2236. if (!constant_id.is_constant()) {
  2237. resolver.local_context().TODO(
  2238. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  2239. return ResolveResult::Done(constant_id);
  2240. }
  2241. auto new_constant_id = GetLocalConstantId(resolver, constant_id);
  2242. return ResolveResult::RetryOrDone(resolver, new_constant_id);
  2243. }
  2244. // Make a declaration of an interface. This is done as a separate step from
  2245. // importing the interface definition in order to resolve cycles.
  2246. static auto MakeInterfaceDecl(ImportContext& context,
  2247. const SemIR::Interface& import_interface,
  2248. SemIR::SpecificId enclosing_specific_id)
  2249. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  2250. SemIR::InterfaceDecl interface_decl = {
  2251. .type_id = SemIR::TypeType::TypeId,
  2252. .interface_id = SemIR::InterfaceId::None,
  2253. .decl_block_id = SemIR::InstBlockId::Empty};
  2254. auto interface_decl_id = AddPlaceholderImportedInst(
  2255. context, import_interface.first_owning_decl_id, interface_decl);
  2256. // Start with an incomplete interface.
  2257. interface_decl.interface_id = context.local_interfaces().Add(
  2258. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  2259. import_interface),
  2260. {.scope_id = import_interface.is_complete()
  2261. ? AddPlaceholderNameScope(context)
  2262. : SemIR::NameScopeId::None}});
  2263. if (import_interface.has_parameters()) {
  2264. interface_decl.type_id = GetGenericInterfaceType(
  2265. context.local_context(), interface_decl.interface_id,
  2266. enclosing_specific_id);
  2267. }
  2268. // Write the interface ID into the InterfaceDecl.
  2269. auto interface_const_id = ReplacePlaceholderImportedInst(
  2270. context, interface_decl_id, interface_decl);
  2271. return {interface_decl.interface_id, interface_const_id};
  2272. }
  2273. // Imports the definition for an interface that has been imported as a forward
  2274. // declaration.
  2275. static auto AddInterfaceDefinition(ImportContext& context,
  2276. const SemIR::Interface& import_interface,
  2277. SemIR::Interface& new_interface,
  2278. SemIR::InstId self_param_id) -> void {
  2279. auto& new_scope = context.local_name_scopes().Get(new_interface.scope_id);
  2280. const auto& import_scope =
  2281. context.import_name_scopes().Get(import_interface.scope_id);
  2282. // Push a block so that we can add scoped instructions to it.
  2283. context.local_context().inst_block_stack().Push();
  2284. InitializeNameScopeAndImportRefs(
  2285. context, import_scope, new_scope, new_interface.first_owning_decl_id,
  2286. SemIR::NameId::None, new_interface.parent_scope_id);
  2287. new_scope.set_is_interface_definition();
  2288. new_interface.associated_entities_id = AddAssociatedEntities(
  2289. context, new_interface.scope_id, import_interface.associated_entities_id);
  2290. new_interface.body_block_id =
  2291. context.local_context().inst_block_stack().Pop();
  2292. new_interface.self_param_id = self_param_id;
  2293. CARBON_CHECK(import_scope.extended_scopes().empty(),
  2294. "Interfaces don't currently have extended scopes to support.");
  2295. }
  2296. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2297. SemIR::InterfaceDecl inst,
  2298. SemIR::ConstantId interface_const_id)
  2299. -> ResolveResult {
  2300. const auto& import_interface =
  2301. resolver.import_interfaces().Get(inst.interface_id);
  2302. auto interface_id = SemIR::InterfaceId::None;
  2303. if (!interface_const_id.has_value()) {
  2304. auto import_specific_id = SemIR::SpecificId::None;
  2305. if (auto import_generic_interface_type =
  2306. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  2307. inst.type_id)) {
  2308. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  2309. }
  2310. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2311. if (resolver.HasNewWork()) {
  2312. // This is the end of the first phase. Don't make a new interface yet if
  2313. // we already have new work.
  2314. return ResolveResult::Retry();
  2315. }
  2316. // On the second phase, create a forward declaration of the interface.
  2317. auto enclosing_specific_id =
  2318. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2319. std::tie(interface_id, interface_const_id) =
  2320. MakeInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  2321. } else {
  2322. // On the third phase, compute the interface ID from the constant value of
  2323. // the declaration.
  2324. auto interface_const_inst = resolver.local_insts().Get(
  2325. resolver.local_constant_values().GetInstId(interface_const_id));
  2326. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2327. const SemIR::FacetTypeInfo& facet_type_info =
  2328. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2329. auto single = facet_type_info.TryAsSingleExtend();
  2330. CARBON_CHECK(single);
  2331. interface_id = std::get<SemIR::SpecificInterface>(*single).interface_id;
  2332. } else {
  2333. auto generic_interface_type =
  2334. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2335. interface_const_inst.type_id());
  2336. interface_id = generic_interface_type.interface_id;
  2337. }
  2338. }
  2339. auto parent_scope_id =
  2340. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  2341. auto implicit_param_patterns = GetLocalInstBlockContents(
  2342. resolver, import_interface.implicit_param_patterns_id);
  2343. auto param_patterns =
  2344. GetLocalInstBlockContents(resolver, import_interface.param_patterns_id);
  2345. auto generic_data =
  2346. GetLocalGenericData(resolver, import_interface.generic_id);
  2347. auto require_impls = GetLocalRequireImplsBlockContents(
  2348. resolver, import_interface.require_impls_block_id);
  2349. std::optional<SemIR::InstId> self_param_id;
  2350. if (import_interface.is_complete()) {
  2351. self_param_id =
  2352. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  2353. }
  2354. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  2355. if (resolver.HasNewWork()) {
  2356. return ResolveResult::Retry(interface_const_id,
  2357. new_interface.first_decl_id());
  2358. }
  2359. new_interface.parent_scope_id = parent_scope_id;
  2360. new_interface.implicit_param_patterns_id = GetLocalCanonicalInstBlockId(
  2361. resolver, import_interface.implicit_param_patterns_id,
  2362. implicit_param_patterns);
  2363. new_interface.param_patterns_id = GetLocalCanonicalInstBlockId(
  2364. resolver, import_interface.param_patterns_id, param_patterns);
  2365. new_interface.require_impls_block_id = GetLocalCanonicalRequireImplsBlockId(
  2366. resolver, import_interface.require_impls_block_id, require_impls);
  2367. SetGenericData(resolver, import_interface.generic_id,
  2368. new_interface.generic_id, generic_data);
  2369. if (import_interface.is_complete()) {
  2370. CARBON_CHECK(self_param_id);
  2371. AddInterfaceDefinition(resolver, import_interface, new_interface,
  2372. *self_param_id);
  2373. }
  2374. return ResolveResult::Done(interface_const_id, new_interface.first_decl_id());
  2375. }
  2376. // Make a declaration of a named constraint. This is done as a separate step
  2377. // from importing the constraint definition in order to resolve cycles.
  2378. static auto MakeNamedConstraintDecl(
  2379. ImportContext& context,
  2380. const SemIR::NamedConstraint& import_named_constraint,
  2381. SemIR::SpecificId enclosing_specific_id)
  2382. -> std::pair<SemIR::NamedConstraintId, SemIR::ConstantId> {
  2383. SemIR::NamedConstraintDecl named_constraint_decl = {
  2384. .type_id = SemIR::TypeType::TypeId,
  2385. .named_constraint_id = SemIR::NamedConstraintId::None,
  2386. .decl_block_id = SemIR::InstBlockId::Empty};
  2387. auto named_constraint_decl_id = AddPlaceholderImportedInst(
  2388. context, import_named_constraint.first_owning_decl_id,
  2389. named_constraint_decl);
  2390. // Start with an incomplete interface.
  2391. named_constraint_decl.named_constraint_id =
  2392. context.local_named_constraints().Add(
  2393. {GetIncompleteLocalEntityBase(context, named_constraint_decl_id,
  2394. import_named_constraint),
  2395. {.scope_id = import_named_constraint.is_complete()
  2396. ? AddPlaceholderNameScope(context)
  2397. : SemIR::NameScopeId::None}});
  2398. if (import_named_constraint.has_parameters()) {
  2399. named_constraint_decl.type_id = GetGenericNamedConstraintType(
  2400. context.local_context(), named_constraint_decl.named_constraint_id,
  2401. enclosing_specific_id);
  2402. }
  2403. // Write the interface ID into the InterfaceDecl.
  2404. auto interface_const_id = ReplacePlaceholderImportedInst(
  2405. context, named_constraint_decl_id, named_constraint_decl);
  2406. return {named_constraint_decl.named_constraint_id, interface_const_id};
  2407. }
  2408. // Imports the definition for a named constraint that has been imported as a
  2409. // forward declaration.
  2410. static auto AddNamedConstraintDefinition(
  2411. ImportContext& context,
  2412. const SemIR::NamedConstraint& import_named_constraint,
  2413. SemIR::NamedConstraint& new_named_constraint, SemIR::InstId self_param_id)
  2414. -> void {
  2415. auto& new_scope =
  2416. context.local_name_scopes().Get(new_named_constraint.scope_id);
  2417. const auto& import_scope =
  2418. context.import_name_scopes().Get(import_named_constraint.scope_id);
  2419. // Push a block so that we can add scoped instructions to it.
  2420. context.local_context().inst_block_stack().Push();
  2421. InitializeNameScopeAndImportRefs(context, import_scope, new_scope,
  2422. new_named_constraint.first_owning_decl_id,
  2423. SemIR::NameId::None,
  2424. new_named_constraint.parent_scope_id);
  2425. new_named_constraint.body_block_id =
  2426. context.local_context().inst_block_stack().Pop();
  2427. new_named_constraint.self_param_id = self_param_id;
  2428. new_named_constraint.complete = import_named_constraint.complete;
  2429. CARBON_CHECK(
  2430. import_scope.extended_scopes().empty(),
  2431. "Named constraints don't currently have extended scopes to support.");
  2432. }
  2433. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2434. SemIR::NamedConstraintDecl inst,
  2435. SemIR::ConstantId named_constraint_const_id)
  2436. -> ResolveResult {
  2437. const auto& import_named_constraint =
  2438. resolver.import_named_constraints().Get(inst.named_constraint_id);
  2439. auto named_constraint_id = SemIR::NamedConstraintId::None;
  2440. if (!named_constraint_const_id.has_value()) {
  2441. auto import_specific_id = SemIR::SpecificId::None;
  2442. if (auto import_generic_named_constraint_type =
  2443. resolver.import_types().TryGetAs<SemIR::GenericNamedConstraintType>(
  2444. inst.type_id)) {
  2445. import_specific_id =
  2446. import_generic_named_constraint_type->enclosing_specific_id;
  2447. }
  2448. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  2449. if (resolver.HasNewWork()) {
  2450. // This is the end of the first phase. Don't make a new interface yet if
  2451. // we already have new work.
  2452. return ResolveResult::Retry();
  2453. }
  2454. // On the second phase, create a forward declaration of the interface.
  2455. auto enclosing_specific_id =
  2456. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  2457. std::tie(named_constraint_id, named_constraint_const_id) =
  2458. MakeNamedConstraintDecl(resolver, import_named_constraint,
  2459. enclosing_specific_id);
  2460. } else {
  2461. // On the third phase, compute the interface ID from the constant value of
  2462. // the declaration.
  2463. auto named_constraint_const_inst = resolver.local_insts().Get(
  2464. resolver.local_constant_values().GetInstId(named_constraint_const_id));
  2465. if (auto facet_type =
  2466. named_constraint_const_inst.TryAs<SemIR::FacetType>()) {
  2467. const SemIR::FacetTypeInfo& facet_type_info =
  2468. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2469. auto single = facet_type_info.TryAsSingleExtend();
  2470. CARBON_CHECK(single);
  2471. named_constraint_id =
  2472. std::get<SemIR::SpecificNamedConstraint>(*single).named_constraint_id;
  2473. } else {
  2474. auto generic_named_constraint_type =
  2475. resolver.local_types().GetAs<SemIR::GenericNamedConstraintType>(
  2476. named_constraint_const_inst.type_id());
  2477. named_constraint_id = generic_named_constraint_type.named_constraint_id;
  2478. }
  2479. }
  2480. auto parent_scope_id =
  2481. GetLocalNameScopeId(resolver, import_named_constraint.parent_scope_id);
  2482. auto implicit_param_patterns = GetLocalInstBlockContents(
  2483. resolver, import_named_constraint.implicit_param_patterns_id);
  2484. auto param_patterns = GetLocalInstBlockContents(
  2485. resolver, import_named_constraint.param_patterns_id);
  2486. auto generic_data =
  2487. GetLocalGenericData(resolver, import_named_constraint.generic_id);
  2488. auto require_impls = GetLocalRequireImplsBlockContents(
  2489. resolver, import_named_constraint.require_impls_block_id);
  2490. std::optional<SemIR::InstId> self_param_id;
  2491. if (import_named_constraint.is_complete()) {
  2492. self_param_id =
  2493. GetLocalConstantInstId(resolver, import_named_constraint.self_param_id);
  2494. }
  2495. auto& new_named_constraint =
  2496. resolver.local_named_constraints().Get(named_constraint_id);
  2497. if (resolver.HasNewWork()) {
  2498. return ResolveResult::Retry(named_constraint_const_id,
  2499. new_named_constraint.first_decl_id());
  2500. }
  2501. new_named_constraint.parent_scope_id = parent_scope_id;
  2502. new_named_constraint.implicit_param_patterns_id =
  2503. GetLocalCanonicalInstBlockId(
  2504. resolver, import_named_constraint.implicit_param_patterns_id,
  2505. implicit_param_patterns);
  2506. new_named_constraint.param_patterns_id = GetLocalCanonicalInstBlockId(
  2507. resolver, import_named_constraint.param_patterns_id, param_patterns);
  2508. new_named_constraint.require_impls_block_id =
  2509. GetLocalCanonicalRequireImplsBlockId(
  2510. resolver, import_named_constraint.require_impls_block_id,
  2511. require_impls);
  2512. SetGenericData(resolver, import_named_constraint.generic_id,
  2513. import_named_constraint.generic_id, generic_data);
  2514. if (import_named_constraint.is_complete()) {
  2515. CARBON_CHECK(self_param_id);
  2516. AddNamedConstraintDefinition(resolver, import_named_constraint,
  2517. new_named_constraint, *self_param_id);
  2518. }
  2519. return ResolveResult::Done(named_constraint_const_id,
  2520. new_named_constraint.first_decl_id());
  2521. }
  2522. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2523. SemIR::FacetAccessType inst) -> ResolveResult {
  2524. auto facet_value_inst_id =
  2525. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2526. if (resolver.HasNewWork()) {
  2527. return ResolveResult::Retry();
  2528. }
  2529. return ResolveResult::Deduplicated<SemIR::FacetAccessType>(
  2530. resolver, {.type_id = SemIR::TypeType::TypeId,
  2531. .facet_value_inst_id = facet_value_inst_id});
  2532. }
  2533. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2534. SemIR::FacetType inst) -> ResolveResult {
  2535. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2536. const SemIR::FacetTypeInfo& import_facet_type_info =
  2537. resolver.import_facet_types().Get(inst.facet_type_id);
  2538. for (auto interface : import_facet_type_info.extend_constraints) {
  2539. // We discard this here and recompute it below instead of saving it to avoid
  2540. // allocations.
  2541. GetLocalSpecificInterfaceData(resolver, interface);
  2542. }
  2543. for (auto interface : import_facet_type_info.self_impls_constraints) {
  2544. // We discard this here and recompute it below instead of saving it to avoid
  2545. // allocations.
  2546. GetLocalSpecificInterfaceData(resolver, interface);
  2547. }
  2548. for (auto constraint : import_facet_type_info.extend_named_constraints) {
  2549. // We discard this here and recompute it below instead of saving it to avoid
  2550. // allocations.
  2551. GetLocalSpecificNamedConstraintData(resolver, constraint);
  2552. }
  2553. for (auto constraint : import_facet_type_info.self_impls_named_constraints) {
  2554. // We discard this here and recompute it below instead of saving it to avoid
  2555. // allocations.
  2556. GetLocalSpecificNamedConstraintData(resolver, constraint);
  2557. }
  2558. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  2559. GetLocalConstantInstId(resolver, rewrite.lhs_id);
  2560. GetLocalConstantInstId(resolver, rewrite.rhs_id);
  2561. }
  2562. // TODO: Import named constraints in the facet type.
  2563. if (resolver.HasNewWork()) {
  2564. return ResolveResult::Retry();
  2565. }
  2566. SemIR::FacetTypeInfo local_facet_type_info = {
  2567. .builtin_constraint_mask = import_facet_type_info.builtin_constraint_mask,
  2568. // TODO: Also process the other requirements.
  2569. .other_requirements = import_facet_type_info.other_requirements};
  2570. local_facet_type_info.extend_constraints.reserve(
  2571. import_facet_type_info.extend_constraints.size());
  2572. for (auto interface : import_facet_type_info.extend_constraints) {
  2573. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2574. local_facet_type_info.extend_constraints.push_back(
  2575. GetLocalSpecificInterface(resolver, interface, data));
  2576. }
  2577. local_facet_type_info.self_impls_constraints.reserve(
  2578. import_facet_type_info.self_impls_constraints.size());
  2579. for (auto interface : import_facet_type_info.self_impls_constraints) {
  2580. auto data = GetLocalSpecificInterfaceData(resolver, interface);
  2581. local_facet_type_info.self_impls_constraints.push_back(
  2582. GetLocalSpecificInterface(resolver, interface, data));
  2583. }
  2584. local_facet_type_info.extend_named_constraints.reserve(
  2585. import_facet_type_info.extend_named_constraints.size());
  2586. for (auto constraint : import_facet_type_info.extend_named_constraints) {
  2587. auto data = GetLocalSpecificNamedConstraintData(resolver, constraint);
  2588. local_facet_type_info.extend_named_constraints.push_back(
  2589. GetLocalSpecificNamedConstraint(resolver, constraint, data));
  2590. }
  2591. local_facet_type_info.self_impls_named_constraints.reserve(
  2592. import_facet_type_info.self_impls_named_constraints.size());
  2593. for (auto constraint : import_facet_type_info.self_impls_named_constraints) {
  2594. auto data = GetLocalSpecificNamedConstraintData(resolver, constraint);
  2595. local_facet_type_info.self_impls_named_constraints.push_back(
  2596. GetLocalSpecificNamedConstraint(resolver, constraint, data));
  2597. }
  2598. local_facet_type_info.rewrite_constraints.reserve(
  2599. import_facet_type_info.rewrite_constraints.size());
  2600. for (auto rewrite : import_facet_type_info.rewrite_constraints) {
  2601. local_facet_type_info.rewrite_constraints.push_back(
  2602. {.lhs_id = GetLocalConstantInstId(resolver, rewrite.lhs_id),
  2603. .rhs_id = GetLocalConstantInstId(resolver, rewrite.rhs_id)});
  2604. }
  2605. SemIR::FacetTypeId facet_type_id =
  2606. resolver.local_facet_types().Add(std::move(local_facet_type_info));
  2607. return ResolveResult::Deduplicated<SemIR::FacetType>(
  2608. resolver,
  2609. {.type_id = SemIR::TypeType::TypeId, .facet_type_id = facet_type_id});
  2610. }
  2611. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2612. SemIR::FacetValue inst) -> ResolveResult {
  2613. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2614. auto type_inst_id = GetLocalTypeInstId(resolver, inst.type_inst_id);
  2615. auto witnesses = GetLocalInstBlockContents(resolver, inst.witnesses_block_id);
  2616. if (resolver.HasNewWork()) {
  2617. return ResolveResult::Retry();
  2618. }
  2619. return ResolveResult::Deduplicated<SemIR::FacetValue>(
  2620. resolver,
  2621. {.type_id =
  2622. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2623. .type_inst_id = type_inst_id,
  2624. .witnesses_block_id = GetLocalCanonicalInstBlockId(
  2625. resolver, inst.witnesses_block_id, witnesses)});
  2626. }
  2627. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2628. SemIR::LookupImplWitness inst)
  2629. -> ResolveResult {
  2630. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2631. SemIR::WitnessType::TypeInstId);
  2632. auto query_self_inst_id =
  2633. GetLocalConstantInstId(resolver, inst.query_self_inst_id);
  2634. const auto& import_specific_interface =
  2635. resolver.import_specific_interfaces().Get(
  2636. inst.query_specific_interface_id);
  2637. auto data =
  2638. GetLocalSpecificInterfaceData(resolver, import_specific_interface);
  2639. if (resolver.HasNewWork()) {
  2640. return ResolveResult::Retry();
  2641. }
  2642. auto specific_interface =
  2643. GetLocalSpecificInterface(resolver, import_specific_interface, data);
  2644. auto query_specific_interface_id =
  2645. resolver.local_specific_interfaces().Add(specific_interface);
  2646. return ResolveResult::Deduplicated<SemIR::LookupImplWitness>(
  2647. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2648. SemIR::WitnessType::TypeInstId),
  2649. .query_self_inst_id = query_self_inst_id,
  2650. .query_specific_interface_id = query_specific_interface_id});
  2651. }
  2652. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2653. SemIR::ImplWitness inst) -> ResolveResult {
  2654. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2655. SemIR::WitnessType::TypeInstId);
  2656. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2657. auto witness_table_id =
  2658. GetLocalConstantInstId(resolver, inst.witness_table_id);
  2659. if (resolver.HasNewWork()) {
  2660. return ResolveResult::Retry();
  2661. }
  2662. auto specific_id =
  2663. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2664. return ResolveResult::Deduplicated<SemIR::ImplWitness>(
  2665. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2666. SemIR::WitnessType::TypeInstId),
  2667. .witness_table_id = witness_table_id,
  2668. .specific_id = specific_id});
  2669. }
  2670. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2671. SemIR::ImplWitnessAccess inst)
  2672. -> ResolveResult {
  2673. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2674. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  2675. if (resolver.HasNewWork()) {
  2676. return ResolveResult::Retry();
  2677. }
  2678. return ResolveResult::Deduplicated<SemIR::ImplWitnessAccess>(
  2679. resolver,
  2680. {.type_id =
  2681. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2682. .witness_id = witness_id,
  2683. .index = inst.index});
  2684. }
  2685. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2686. SemIR::ImplWitnessTable inst,
  2687. SemIR::InstId import_inst_id) -> ResolveResult {
  2688. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  2689. auto import_decl_inst_id = import_impl.first_decl_id();
  2690. auto local_decl_inst_id =
  2691. GetLocalConstantInstId(resolver, import_decl_inst_id);
  2692. if (resolver.HasNewWork()) {
  2693. return ResolveResult::Retry();
  2694. }
  2695. auto impl_decl =
  2696. resolver.local_insts().GetAs<SemIR::ImplDecl>(local_decl_inst_id);
  2697. auto impl_id = impl_decl.impl_id;
  2698. auto elements_id = GetLocalImportRefInstBlock(resolver, inst.elements_id);
  2699. // Create a corresponding instruction to represent the table.
  2700. return ResolveResult::Unique<SemIR::ImplWitnessTable>(
  2701. resolver, import_inst_id,
  2702. {.elements_id = elements_id, .impl_id = impl_id});
  2703. }
  2704. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2705. SemIR::IntValue inst) -> ResolveResult {
  2706. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2707. if (resolver.HasNewWork()) {
  2708. return ResolveResult::Retry();
  2709. }
  2710. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  2711. // to add a new canonical int in this IR.
  2712. auto int_id = inst.int_id.is_embedded_value()
  2713. ? inst.int_id
  2714. : resolver.local_ints().AddSigned(
  2715. resolver.import_ints().Get(inst.int_id));
  2716. return ResolveResult::Deduplicated<SemIR::IntValue>(
  2717. resolver,
  2718. {.type_id =
  2719. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2720. .int_id = int_id});
  2721. }
  2722. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2723. SemIR::IntType inst) -> ResolveResult {
  2724. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2725. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  2726. if (resolver.HasNewWork()) {
  2727. return ResolveResult::Retry();
  2728. }
  2729. return ResolveResult::Deduplicated<SemIR::IntType>(
  2730. resolver, {.type_id = SemIR::TypeType::TypeId,
  2731. .int_kind = inst.int_kind,
  2732. .bit_width_id = bit_width_id});
  2733. }
  2734. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2735. SemIR::Namespace inst,
  2736. SemIR::InstId import_inst_id) -> ResolveResult {
  2737. const auto& name_scope =
  2738. resolver.import_name_scopes().Get(inst.name_scope_id);
  2739. // A package from a different file becomes a child of the package here, as it
  2740. // would be if it were imported.
  2741. auto parent_scope_id =
  2742. inst.name_scope_id == SemIR::NameScopeId::Package
  2743. ? SemIR::NameScopeId::Package
  2744. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  2745. if (resolver.HasNewWork()) {
  2746. return ResolveResult::Retry();
  2747. }
  2748. auto namespace_type_id = GetSingletonType(resolver.local_context(),
  2749. SemIR::NamespaceType::TypeInstId);
  2750. auto namespace_decl =
  2751. SemIR::Namespace{.type_id = namespace_type_id,
  2752. .name_scope_id = SemIR::NameScopeId::None,
  2753. .import_id = SemIR::AbsoluteInstId::None};
  2754. auto inst_id =
  2755. AddPlaceholderImportedInst(resolver, import_inst_id, namespace_decl);
  2756. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  2757. namespace_decl.name_scope_id =
  2758. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  2759. // Namespaces from this package are eagerly imported, so anything we load here
  2760. // must be a closed import.
  2761. resolver.local_name_scopes()
  2762. .Get(namespace_decl.name_scope_id)
  2763. .set_is_closed_import(true);
  2764. auto namespace_const_id =
  2765. ReplacePlaceholderImportedInst(resolver, inst_id, namespace_decl);
  2766. return {.const_id = namespace_const_id};
  2767. }
  2768. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2769. SemIR::PatternType inst) -> ResolveResult {
  2770. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2771. auto scrutinee_type_inst_id =
  2772. GetLocalTypeInstId(resolver, inst.scrutinee_type_inst_id);
  2773. if (resolver.HasNewWork()) {
  2774. return ResolveResult::Retry();
  2775. }
  2776. return ResolveResult::Deduplicated<SemIR::PatternType>(
  2777. resolver, {.type_id = SemIR::TypeType::TypeId,
  2778. .scrutinee_type_inst_id = scrutinee_type_inst_id});
  2779. }
  2780. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2781. SemIR::PointerType inst) -> ResolveResult {
  2782. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2783. auto pointee_id = GetLocalTypeInstId(resolver, inst.pointee_id);
  2784. if (resolver.HasNewWork()) {
  2785. return ResolveResult::Retry();
  2786. }
  2787. return ResolveResult::Deduplicated<SemIR::PointerType>(
  2788. resolver, {.type_id = SemIR::TypeType::TypeId, .pointee_id = pointee_id});
  2789. }
  2790. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2791. SemIR::RequireCompleteType inst)
  2792. -> ResolveResult {
  2793. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2794. SemIR::WitnessType::TypeInstId);
  2795. auto complete_type_inst_id =
  2796. GetLocalTypeInstId(resolver, inst.complete_type_inst_id);
  2797. if (resolver.HasNewWork()) {
  2798. return ResolveResult::Retry();
  2799. }
  2800. return ResolveResult::Deduplicated<SemIR::RequireCompleteType>(
  2801. resolver, {.type_id = GetSingletonType(resolver.local_context(),
  2802. SemIR::WitnessType::TypeInstId),
  2803. .complete_type_inst_id = complete_type_inst_id});
  2804. }
  2805. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2806. SemIR::ReturnSlotPattern inst,
  2807. SemIR::InstId import_inst_id) -> ResolveResult {
  2808. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2809. if (resolver.HasNewWork()) {
  2810. return ResolveResult::Retry();
  2811. }
  2812. return ResolveResult::Unique<SemIR::ReturnSlotPattern>(
  2813. resolver, import_inst_id,
  2814. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2815. type_const_id),
  2816. .type_inst_id = SemIR::TypeInstId::None});
  2817. }
  2818. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2819. SemIR::SpecificFunction inst) -> ResolveResult {
  2820. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2821. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2822. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2823. if (resolver.HasNewWork()) {
  2824. return ResolveResult::Retry();
  2825. }
  2826. auto type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2827. type_const_id);
  2828. auto specific_id =
  2829. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2830. return ResolveResult::Deduplicated<SemIR::SpecificFunction>(
  2831. resolver,
  2832. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2833. }
  2834. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2835. SemIR::SpecificImplFunction inst)
  2836. -> ResolveResult {
  2837. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2838. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2839. if (resolver.HasNewWork()) {
  2840. return ResolveResult::Retry();
  2841. }
  2842. auto type_id = GetSingletonType(resolver.local_context(),
  2843. SemIR::SpecificFunctionType::TypeInstId);
  2844. auto specific_id =
  2845. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2846. return ResolveResult::Deduplicated<SemIR::SpecificImplFunction>(
  2847. resolver,
  2848. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2849. }
  2850. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2851. SemIR::StructAccess inst) -> ResolveResult {
  2852. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2853. auto struct_id = GetLocalConstantInstId(resolver, inst.struct_id);
  2854. if (resolver.HasNewWork()) {
  2855. return ResolveResult::Retry();
  2856. }
  2857. // A `struct_access` constant requires its struct operand to have a complete
  2858. // type.
  2859. CompleteTypeOrCheckFail(resolver.local_context(),
  2860. resolver.local_insts().Get(struct_id).type_id());
  2861. return ResolveResult::Deduplicated<SemIR::StructAccess>(
  2862. resolver,
  2863. {.type_id =
  2864. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2865. .struct_id = struct_id,
  2866. .index = inst.index});
  2867. }
  2868. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2869. SemIR::StructType inst) -> ResolveResult {
  2870. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2871. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  2872. llvm::SmallVector<SemIR::TypeInstId> field_type_inst_ids;
  2873. field_type_inst_ids.reserve(orig_fields.size());
  2874. for (auto field : orig_fields) {
  2875. field_type_inst_ids.push_back(
  2876. GetLocalTypeInstId(resolver, field.type_inst_id));
  2877. }
  2878. if (resolver.HasNewWork()) {
  2879. return ResolveResult::Retry();
  2880. }
  2881. // Prepare a vector of fields for GetStructType.
  2882. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  2883. new_fields.reserve(orig_fields.size());
  2884. for (auto [orig_field, field_type_inst_id] :
  2885. llvm::zip_equal(orig_fields, field_type_inst_ids)) {
  2886. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  2887. new_fields.push_back(
  2888. {.name_id = name_id, .type_inst_id = field_type_inst_id});
  2889. }
  2890. return ResolveResult::Deduplicated<SemIR::StructType>(
  2891. resolver, {.type_id = SemIR::TypeType::TypeId,
  2892. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  2893. new_fields)});
  2894. }
  2895. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2896. SemIR::StructValue inst) -> ResolveResult {
  2897. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2898. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2899. if (resolver.HasNewWork()) {
  2900. return ResolveResult::Retry();
  2901. }
  2902. return ResolveResult::Deduplicated<SemIR::StructValue>(
  2903. resolver,
  2904. {.type_id =
  2905. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2906. .elements_id =
  2907. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2908. }
  2909. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2910. SemIR::SymbolicBindingType inst)
  2911. -> ResolveResult {
  2912. auto facet_value_inst_id =
  2913. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2914. if (resolver.HasNewWork()) {
  2915. return ResolveResult::Retry();
  2916. }
  2917. auto entity_name_id =
  2918. GetLocalSymbolicEntityNameId(resolver, inst.entity_name_id);
  2919. return ResolveResult::Deduplicated<SemIR::SymbolicBindingType>(
  2920. resolver, {.type_id = SemIR::TypeType::TypeId,
  2921. .entity_name_id = entity_name_id,
  2922. .facet_value_inst_id = facet_value_inst_id});
  2923. }
  2924. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2925. SemIR::TupleAccess inst) -> ResolveResult {
  2926. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2927. auto tuple_id = GetLocalConstantInstId(resolver, inst.tuple_id);
  2928. if (resolver.HasNewWork()) {
  2929. return ResolveResult::Retry();
  2930. }
  2931. // A `tuple_access` constant requires its struct operand to have a complete
  2932. // type.
  2933. CompleteTypeOrCheckFail(resolver.local_context(),
  2934. resolver.local_insts().Get(tuple_id).type_id());
  2935. return ResolveResult::Deduplicated<SemIR::TupleAccess>(
  2936. resolver,
  2937. {.type_id =
  2938. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2939. .tuple_id = tuple_id,
  2940. .index = inst.index});
  2941. }
  2942. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2943. SemIR::TuplePattern inst,
  2944. SemIR::InstId import_inst_id) -> ResolveResult {
  2945. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2946. auto elements = GetLocalInstBlockContents(resolver, inst.elements_id);
  2947. if (resolver.HasNewWork()) {
  2948. return ResolveResult::Retry();
  2949. }
  2950. return ResolveResult::Unique<SemIR::TuplePattern>(
  2951. resolver, import_inst_id,
  2952. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  2953. type_const_id),
  2954. .elements_id =
  2955. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elements)});
  2956. }
  2957. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2958. SemIR::TupleType inst) -> ResolveResult {
  2959. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2960. auto orig_type_inst_ids =
  2961. resolver.import_inst_blocks().Get(inst.type_elements_id);
  2962. // TODO: It might be nice to make the `InstBlock` in `TupleType` record in the
  2963. // type system that its holding `TypeInstId` elements.
  2964. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  2965. type_inst_ids.reserve(orig_type_inst_ids.size());
  2966. for (auto elem_type_inst_id :
  2967. resolver.import_ir().types().GetBlockAsTypeInstIds(orig_type_inst_ids)) {
  2968. type_inst_ids.push_back(GetLocalTypeInstId(resolver, elem_type_inst_id));
  2969. }
  2970. if (resolver.HasNewWork()) {
  2971. return ResolveResult::Retry();
  2972. }
  2973. return ResolveResult::Deduplicated<SemIR::TupleType>(
  2974. resolver, {.type_id = SemIR::TypeType::TypeId,
  2975. .type_elements_id = GetLocalCanonicalInstBlockId(
  2976. resolver, inst.type_elements_id, type_inst_ids)});
  2977. }
  2978. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2979. SemIR::TupleValue inst) -> ResolveResult {
  2980. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2981. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2982. if (resolver.HasNewWork()) {
  2983. return ResolveResult::Retry();
  2984. }
  2985. return ResolveResult::Deduplicated<SemIR::TupleValue>(
  2986. resolver,
  2987. {.type_id =
  2988. resolver.local_context().types().GetTypeIdForTypeConstantId(type_id),
  2989. .elements_id =
  2990. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2991. }
  2992. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2993. SemIR::UnboundElementType inst)
  2994. -> ResolveResult {
  2995. CARBON_CHECK(inst.type_id == SemIR::TypeType::TypeId);
  2996. auto class_const_inst_id =
  2997. GetLocalTypeInstId(resolver, inst.class_type_inst_id);
  2998. auto elem_const_inst_id =
  2999. GetLocalTypeInstId(resolver, inst.element_type_inst_id);
  3000. if (resolver.HasNewWork()) {
  3001. return ResolveResult::Retry();
  3002. }
  3003. return ResolveResult::Deduplicated<SemIR::UnboundElementType>(
  3004. resolver, {.type_id = SemIR::TypeType::TypeId,
  3005. .class_type_inst_id = class_const_inst_id,
  3006. .element_type_inst_id = elem_const_inst_id});
  3007. }
  3008. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3009. SemIR::VarPattern inst,
  3010. SemIR::InstId import_inst_id) -> ResolveResult {
  3011. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3012. auto subpattern_id = GetLocalConstantInstId(resolver, inst.subpattern_id);
  3013. if (resolver.HasNewWork()) {
  3014. return ResolveResult::Retry();
  3015. }
  3016. return ResolveResult::Unique<SemIR::VarPattern>(
  3017. resolver, import_inst_id,
  3018. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  3019. type_const_id),
  3020. .subpattern_id = subpattern_id});
  3021. }
  3022. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  3023. SemIR::VarStorage inst,
  3024. SemIR::InstId import_inst_id) -> ResolveResult {
  3025. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  3026. auto pattern_id = GetLocalConstantInstId(resolver, inst.pattern_id);
  3027. if (resolver.HasNewWork()) {
  3028. return ResolveResult::Retry();
  3029. }
  3030. return ResolveResult::Unique<SemIR::VarStorage>(
  3031. resolver, import_inst_id,
  3032. {.type_id = resolver.local_context().types().GetTypeIdForTypeConstantId(
  3033. type_const_id),
  3034. .pattern_id = pattern_id});
  3035. }
  3036. // Tries to resolve the InstId, returning a canonical constant when ready, or
  3037. // `None` if more has been added to the stack. This is the same as
  3038. // TryResolveInst, except that it may resolve symbolic constants as canonical
  3039. // constants instead of as constants associated with a particular generic.
  3040. //
  3041. // TODO: Consider refactoring the body to a helper in order to eliminate
  3042. // recursion.
  3043. // NOLINTNEXTLINE(misc-no-recursion)
  3044. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  3045. SemIR::InstId inst_id,
  3046. SemIR::ConstantId const_id)
  3047. -> ResolveResult {
  3048. // These instruction types are imported across multiple phases to arrive at
  3049. // their constant value. We can't just import their constant value instruction
  3050. // directly.
  3051. auto untyped_inst = resolver.import_insts().GetWithAttachedType(inst_id);
  3052. CARBON_KIND_SWITCH(untyped_inst) {
  3053. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  3054. return TryResolveTypedInst(resolver, inst, const_id);
  3055. }
  3056. case CARBON_KIND(SemIR::ClassDecl inst): {
  3057. return TryResolveTypedInst(resolver, inst, const_id);
  3058. }
  3059. case CARBON_KIND(SemIR::FunctionDecl inst): {
  3060. return TryResolveTypedInst(resolver, inst, const_id);
  3061. }
  3062. case CARBON_KIND(SemIR::ImplDecl inst): {
  3063. return TryResolveTypedInst(resolver, inst, const_id);
  3064. }
  3065. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  3066. return TryResolveTypedInst(resolver, inst, const_id);
  3067. }
  3068. case CARBON_KIND(SemIR::NamedConstraintDecl inst): {
  3069. return TryResolveTypedInst(resolver, inst, const_id);
  3070. }
  3071. default:
  3072. break;
  3073. }
  3074. // Other instructions are imported in a single phase (once their dependencies
  3075. // are all imported).
  3076. CARBON_CHECK(!const_id.has_value());
  3077. auto inst_constant_id = resolver.import_constant_values().Get(inst_id);
  3078. if (!inst_constant_id.is_constant()) {
  3079. // TODO: Import of non-constant BindNames happens when importing `let`
  3080. // declarations.
  3081. CARBON_CHECK(resolver.import_insts().Is<SemIR::AnyBinding>(inst_id),
  3082. "TryResolveInst on non-constant instruction {0}", inst_id);
  3083. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  3084. }
  3085. // Import the canonical constant value instruction for `inst_id` directly. We
  3086. // don't try to import the non-canonical `inst_id`.
  3087. auto constant_inst_id =
  3088. resolver.import_constant_values().GetInstId(inst_constant_id);
  3089. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  3090. constant_inst_id) == constant_inst_id,
  3091. "Constant value of constant instruction should refer to "
  3092. "the same instruction");
  3093. if (SemIR::IsSingletonInstId(constant_inst_id)) {
  3094. // Constants for builtins can be directly copied.
  3095. return ResolveResult::Done(
  3096. resolver.local_constant_values().Get(constant_inst_id));
  3097. }
  3098. auto untyped_constant_inst =
  3099. resolver.import_insts().GetWithAttachedType(constant_inst_id);
  3100. CARBON_KIND_SWITCH(untyped_constant_inst) {
  3101. case CARBON_KIND(SemIR::AdaptDecl inst): {
  3102. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3103. }
  3104. case CARBON_KIND(SemIR::ArrayType inst): {
  3105. return TryResolveTypedInst(resolver, inst);
  3106. }
  3107. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  3108. return TryResolveTypedInst(resolver, inst);
  3109. }
  3110. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  3111. return TryResolveTypedInst(resolver, inst);
  3112. }
  3113. case CARBON_KIND(SemIR::BaseDecl inst): {
  3114. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3115. }
  3116. case CARBON_KIND(SemIR::AliasBinding inst): {
  3117. return TryResolveTypedInst(resolver, inst);
  3118. }
  3119. case CARBON_KIND(SemIR::SymbolicBinding inst): {
  3120. return TryResolveTypedInst(resolver, inst);
  3121. }
  3122. case CARBON_KIND(SemIR::BoolLiteral inst): {
  3123. return TryResolveTypedInst(resolver, inst);
  3124. }
  3125. case CARBON_KIND(SemIR::BoundMethod inst): {
  3126. return TryResolveTypedInst(resolver, inst);
  3127. }
  3128. case CARBON_KIND(SemIR::Call inst): {
  3129. return TryResolveTypedInst(resolver, inst);
  3130. }
  3131. case CARBON_KIND(SemIR::CharLiteralValue inst): {
  3132. return TryResolveTypedInst(resolver, inst);
  3133. }
  3134. case CARBON_KIND(SemIR::ClassType inst): {
  3135. return TryResolveTypedInst(resolver, inst);
  3136. }
  3137. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  3138. return TryResolveTypedInst(resolver, inst);
  3139. }
  3140. case CARBON_KIND(SemIR::ConstType inst): {
  3141. return TryResolveTypedInst(resolver, inst);
  3142. }
  3143. case CARBON_KIND(SemIR::CppOverloadSetType inst): {
  3144. return TryResolveTypedInst(resolver, inst);
  3145. }
  3146. case CARBON_KIND(SemIR::CppOverloadSetValue inst): {
  3147. return TryResolveTypedInst(resolver, inst);
  3148. }
  3149. case CARBON_KIND(SemIR::ExportDecl inst): {
  3150. return TryResolveTypedInst(resolver, inst);
  3151. }
  3152. case CARBON_KIND(SemIR::FacetAccessType inst): {
  3153. return TryResolveTypedInst(resolver, inst);
  3154. }
  3155. case CARBON_KIND(SemIR::FacetType inst): {
  3156. return TryResolveTypedInst(resolver, inst);
  3157. }
  3158. case CARBON_KIND(SemIR::FacetValue inst): {
  3159. return TryResolveTypedInst(resolver, inst);
  3160. }
  3161. case CARBON_KIND(SemIR::FieldDecl inst): {
  3162. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3163. }
  3164. case CARBON_KIND(SemIR::FloatLiteralValue inst): {
  3165. return TryResolveTypedInst(resolver, inst);
  3166. }
  3167. case CARBON_KIND(SemIR::FloatType inst): {
  3168. return TryResolveTypedInst(resolver, inst);
  3169. }
  3170. case CARBON_KIND(SemIR::FloatValue inst): {
  3171. return TryResolveTypedInst(resolver, inst);
  3172. }
  3173. case CARBON_KIND(SemIR::FunctionType inst): {
  3174. return TryResolveTypedInst(resolver, inst);
  3175. }
  3176. case CARBON_KIND(SemIR::FunctionTypeWithSelfType inst): {
  3177. return TryResolveTypedInst(resolver, inst);
  3178. }
  3179. case CARBON_KIND(SemIR::GenericClassType inst): {
  3180. return TryResolveTypedInst(resolver, inst);
  3181. }
  3182. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  3183. return TryResolveTypedInst(resolver, inst);
  3184. }
  3185. case CARBON_KIND(SemIR::LookupImplWitness inst): {
  3186. return TryResolveTypedInst(resolver, inst);
  3187. }
  3188. case CARBON_KIND(SemIR::ImplWitness inst): {
  3189. return TryResolveTypedInst(resolver, inst);
  3190. }
  3191. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  3192. return TryResolveTypedInst(resolver, inst);
  3193. }
  3194. case CARBON_KIND(SemIR::ImplWitnessTable inst): {
  3195. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3196. }
  3197. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  3198. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3199. }
  3200. case CARBON_KIND(SemIR::IntValue inst): {
  3201. return TryResolveTypedInst(resolver, inst);
  3202. }
  3203. case CARBON_KIND(SemIR::IntType inst): {
  3204. return TryResolveTypedInst(resolver, inst);
  3205. }
  3206. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  3207. return TryResolveTypedInst(resolver, inst);
  3208. }
  3209. case CARBON_KIND(SemIR::Namespace inst): {
  3210. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3211. }
  3212. case CARBON_KIND(SemIR::OutParamPattern inst): {
  3213. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3214. }
  3215. case CARBON_KIND(SemIR::PartialType inst): {
  3216. return TryResolveTypedInst(resolver, inst);
  3217. }
  3218. case CARBON_KIND(SemIR::PatternType inst): {
  3219. return TryResolveTypedInst(resolver, inst);
  3220. }
  3221. case CARBON_KIND(SemIR::PointerType inst): {
  3222. return TryResolveTypedInst(resolver, inst);
  3223. }
  3224. case CARBON_KIND(SemIR::RefBindingPattern inst): {
  3225. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3226. }
  3227. case CARBON_KIND(SemIR::RefParamPattern inst): {
  3228. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3229. }
  3230. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  3231. return TryResolveTypedInst(resolver, inst);
  3232. }
  3233. case CARBON_KIND(SemIR::RequireImplsDecl inst): {
  3234. return TryResolveTypedInst(resolver, inst);
  3235. }
  3236. case CARBON_KIND(SemIR::ReturnSlotPattern inst): {
  3237. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3238. }
  3239. case CARBON_KIND(SemIR::SpecificFunction inst): {
  3240. return TryResolveTypedInst(resolver, inst);
  3241. }
  3242. case CARBON_KIND(SemIR::SpecificImplFunction inst): {
  3243. return TryResolveTypedInst(resolver, inst);
  3244. }
  3245. case CARBON_KIND(SemIR::StructAccess inst): {
  3246. return TryResolveTypedInst(resolver, inst);
  3247. }
  3248. case CARBON_KIND(SemIR::StructType inst): {
  3249. return TryResolveTypedInst(resolver, inst);
  3250. }
  3251. case CARBON_KIND(SemIR::StructValue inst): {
  3252. return TryResolveTypedInst(resolver, inst);
  3253. }
  3254. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  3255. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3256. }
  3257. case CARBON_KIND(SemIR::SymbolicBindingType inst): {
  3258. return TryResolveTypedInst(resolver, inst);
  3259. }
  3260. case CARBON_KIND(SemIR::TupleAccess inst): {
  3261. return TryResolveTypedInst(resolver, inst);
  3262. }
  3263. case CARBON_KIND(SemIR::TuplePattern inst): {
  3264. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3265. }
  3266. case CARBON_KIND(SemIR::TupleType inst): {
  3267. return TryResolveTypedInst(resolver, inst);
  3268. }
  3269. case CARBON_KIND(SemIR::TupleValue inst): {
  3270. return TryResolveTypedInst(resolver, inst);
  3271. }
  3272. case CARBON_KIND(SemIR::UnboundElementType inst): {
  3273. return TryResolveTypedInst(resolver, inst);
  3274. }
  3275. case CARBON_KIND(SemIR::ValueBindingPattern inst): {
  3276. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3277. }
  3278. case CARBON_KIND(SemIR::ValueParamPattern inst): {
  3279. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3280. }
  3281. case CARBON_KIND(SemIR::VarParamPattern inst): {
  3282. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3283. }
  3284. case CARBON_KIND(SemIR::VarPattern inst): {
  3285. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3286. }
  3287. case CARBON_KIND(SemIR::VarStorage inst): {
  3288. return TryResolveTypedInst(resolver, inst, constant_inst_id);
  3289. }
  3290. case CARBON_KIND(SemIR::VtableDecl inst): {
  3291. return TryResolveTypedInst(resolver, inst);
  3292. }
  3293. case CARBON_KIND(SemIR::VtablePtr inst): {
  3294. return TryResolveTypedInst(resolver, inst);
  3295. }
  3296. default:
  3297. // Found a canonical instruction which needs to be resolved, but which is
  3298. // not yet handled.
  3299. //
  3300. // TODO: Could we turn this into a compile-time error?
  3301. CARBON_FATAL(
  3302. "Missing case in TryResolveInstCanonical for instruction kind {0}",
  3303. untyped_constant_inst.kind());
  3304. }
  3305. }
  3306. // Tries to resolve the InstId, returning a constant when ready, or `None` if
  3307. // more has been added to the stack. A similar API is followed for all
  3308. // following TryResolveTypedInst helper functions.
  3309. //
  3310. // `const_id` is `None` unless we've tried to resolve this instruction
  3311. // before, in which case it's the previous result.
  3312. //
  3313. // TODO: Error is returned when support is missing, but that should go away.
  3314. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  3315. SemIR::ConstantId const_id) -> ResolveResult {
  3316. auto inst_const_id = resolver.import_constant_values().GetAttached(inst_id);
  3317. if (!inst_const_id.has_value() || !inst_const_id.is_symbolic()) {
  3318. return TryResolveInstCanonical(resolver, inst_id, const_id);
  3319. }
  3320. // Try to import the generic. This might add new work.
  3321. const auto& symbolic_const =
  3322. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  3323. auto generic_const_id =
  3324. GetLocalConstantId(resolver, symbolic_const.generic_id);
  3325. auto inner_const_id = SemIR::ConstantId::None;
  3326. if (const_id.has_value()) {
  3327. // For the third phase, extract the constant value that
  3328. // TryResolveInstCanonical produced previously.
  3329. inner_const_id = resolver.local_constant_values().GetAttached(
  3330. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  3331. }
  3332. // Import the constant and rebuild the symbolic constant data.
  3333. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  3334. if (!result.const_id.has_value()) {
  3335. // First phase: TryResolveInstCanoncial needs a retry.
  3336. return result;
  3337. }
  3338. if (!const_id.has_value()) {
  3339. // Second phase: we have created an unattached constant. Create a
  3340. // corresponding attached constant.
  3341. if (symbolic_const.generic_id.has_value()) {
  3342. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  3343. {.inst_id =
  3344. resolver.local_constant_values().GetInstId(result.const_id),
  3345. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  3346. .index = symbolic_const.index,
  3347. .dependence = symbolic_const.dependence});
  3348. if (result.decl_id.has_value()) {
  3349. // Overwrite the unattached symbolic constant given initially to the
  3350. // declaration with its final attached symbolic value.
  3351. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  3352. }
  3353. }
  3354. } else {
  3355. // Third phase: perform a consistency check and produce the constant we
  3356. // created in the second phase.
  3357. CARBON_CHECK(result.const_id == inner_const_id,
  3358. "Constant value changed in third phase.");
  3359. result.const_id = const_id;
  3360. }
  3361. return result;
  3362. }
  3363. auto ImportRefResolver::ResolveOneInst(SemIR::InstId inst_id)
  3364. -> SemIR::ConstantId {
  3365. work_stack_.push_back({.inst_id = inst_id});
  3366. while (!work_stack_.empty()) {
  3367. auto work = work_stack_.back();
  3368. CARBON_CHECK(work.inst_id.has_value());
  3369. // Step 1: check for a constant value.
  3370. auto existing = FindResolvedConstId(work.inst_id);
  3371. if (existing.const_id.has_value() && !work.retry_with_constant_value) {
  3372. work_stack_.pop_back();
  3373. continue;
  3374. }
  3375. // Step 2: resolve the instruction.
  3376. initial_work_ = work_stack_.size();
  3377. auto [new_const_id, _, retry] =
  3378. TryResolveInst(*this, work.inst_id, existing.const_id);
  3379. CARBON_CHECK(!HasNewWork() || retry);
  3380. CARBON_CHECK(
  3381. !existing.const_id.has_value() || existing.const_id == new_const_id,
  3382. "Constant value changed in third phase.");
  3383. if (!existing.const_id.has_value()) {
  3384. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  3385. }
  3386. // Step 3: pop or retry.
  3387. if (retry) {
  3388. work_stack_[initial_work_ - 1].retry_with_constant_value =
  3389. new_const_id.has_value();
  3390. } else {
  3391. work_stack_.pop_back();
  3392. }
  3393. }
  3394. auto constant_id =
  3395. local_constant_values_for_import_insts().GetAttached(inst_id);
  3396. CARBON_CHECK(constant_id.has_value());
  3397. return constant_id;
  3398. }
  3399. // NOLINTNEXTLINE(misc-no-recursion)
  3400. auto ImportRefResolver::ResolveType(SemIR::TypeId import_type_id)
  3401. -> SemIR::TypeId {
  3402. if (!import_type_id.has_value()) {
  3403. return import_type_id;
  3404. }
  3405. auto import_type_const_id = import_ir().types().GetConstantId(import_type_id);
  3406. CARBON_CHECK(import_type_const_id.has_value());
  3407. if (auto import_type_inst_id = import_ir().types().GetAsTypeInstId(
  3408. import_ir().constant_values().GetInstId(import_type_const_id));
  3409. SemIR::IsSingletonInstId(import_type_inst_id)) {
  3410. // Builtins don't require constant resolution; we can use them directly.
  3411. return GetSingletonType(local_context(), import_type_inst_id);
  3412. } else {
  3413. return local_context().types().GetTypeIdForTypeConstantId(
  3414. ResolveConstant(import_type_id.AsConstantId()));
  3415. }
  3416. }
  3417. auto ImportRefResolver::GetLocalConstantValueOrPush(SemIR::InstId inst_id)
  3418. -> SemIR::ConstantId {
  3419. if (!inst_id.has_value()) {
  3420. return SemIR::ConstantId::None;
  3421. }
  3422. auto const_id = local_constant_values_for_import_insts().GetAttached(inst_id);
  3423. if (!const_id.has_value()) {
  3424. work_stack_.push_back({.inst_id = inst_id});
  3425. }
  3426. return const_id;
  3427. }
  3428. auto ImportRefResolver::FindResolvedConstId(SemIR::InstId inst_id)
  3429. -> ResolvedConstId {
  3430. ResolvedConstId result;
  3431. if (auto existing_const_id =
  3432. local_constant_values_for_import_insts().GetAttached(inst_id);
  3433. existing_const_id.has_value()) {
  3434. result.const_id = existing_const_id;
  3435. return result;
  3436. }
  3437. const auto* cursor_ir = &import_ir();
  3438. auto cursor_inst_id = inst_id;
  3439. while (true) {
  3440. auto import_ir_inst_id = cursor_ir->insts().GetImportSource(cursor_inst_id);
  3441. if (!import_ir_inst_id.has_value()) {
  3442. return result;
  3443. }
  3444. auto ir_inst = cursor_ir->import_ir_insts().Get(import_ir_inst_id);
  3445. if (ir_inst.ir_id() == SemIR::ImportIRId::Cpp) {
  3446. local_context().TODO(SemIR::LocId::None,
  3447. "Unsupported: Importing C++ indirectly");
  3448. SetResolvedConstId(inst_id, result.indirect_insts,
  3449. SemIR::ErrorInst::ConstantId);
  3450. result.const_id = SemIR::ErrorInst::ConstantId;
  3451. result.indirect_insts.clear();
  3452. return result;
  3453. }
  3454. const auto* prev_ir = cursor_ir;
  3455. auto prev_inst_id = cursor_inst_id;
  3456. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id()).sem_ir;
  3457. auto cursor_ir_id =
  3458. AddImportIR(local_context(), {.decl_id = SemIR::InstId::None,
  3459. .is_export = false,
  3460. .sem_ir = cursor_ir});
  3461. cursor_inst_id = ir_inst.inst_id();
  3462. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id, "{0}",
  3463. cursor_ir->insts().Get(cursor_inst_id));
  3464. if (auto const_id =
  3465. local_context()
  3466. .import_ir_constant_values()
  3467. [local_context().sem_ir().import_irs().GetRawIndex(
  3468. cursor_ir_id)]
  3469. .GetAttached(cursor_inst_id);
  3470. const_id.has_value()) {
  3471. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  3472. result.const_id = const_id;
  3473. result.indirect_insts.clear();
  3474. return result;
  3475. } else {
  3476. result.indirect_insts.push_back(
  3477. SemIR::ImportIRInst(cursor_ir_id, cursor_inst_id));
  3478. }
  3479. }
  3480. }
  3481. auto ImportRefResolver::SetResolvedConstId(
  3482. SemIR::InstId inst_id, llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  3483. SemIR::ConstantId const_id) -> void {
  3484. local_constant_values_for_import_insts().Set(inst_id, const_id);
  3485. for (auto indirect_inst : indirect_insts) {
  3486. local_context()
  3487. .import_ir_constant_values()
  3488. [local_context().sem_ir().import_irs().GetRawIndex(
  3489. indirect_inst.ir_id())]
  3490. .Set(indirect_inst.inst_id(), const_id);
  3491. }
  3492. }
  3493. // Resolves and returns the local contents for an imported instruction block
  3494. // of constant instructions.
  3495. static auto ResolveLocalInstBlockContents(ImportRefResolver& resolver,
  3496. SemIR::InstBlockId import_block_id)
  3497. -> llvm::SmallVector<SemIR::InstId> {
  3498. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  3499. llvm::SmallVector<SemIR::InstId> inst_ids;
  3500. inst_ids.reserve(import_block.size());
  3501. for (auto import_inst_id : import_block) {
  3502. inst_ids.push_back(resolver.local_constant_values().GetInstId(
  3503. resolver.ResolveOneInst(import_inst_id)));
  3504. }
  3505. return inst_ids;
  3506. }
  3507. // Resolves and returns a local eval block for a region of an imported
  3508. // generic.
  3509. static auto ResolveLocalEvalBlock(ImportRefResolver& resolver,
  3510. const SemIR::Generic& import_generic,
  3511. SemIR::GenericId generic_id,
  3512. SemIR::GenericInstIndex::Region region)
  3513. -> SemIR::InstBlockId {
  3514. auto import_block_id = import_generic.GetEvalBlock(region);
  3515. if (!import_block_id.has_value()) {
  3516. return SemIR::InstBlockId::None;
  3517. }
  3518. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  3519. auto eval_block_id = RebuildGenericEvalBlock(resolver.local_context(),
  3520. generic_id, region, inst_ids);
  3521. // Set the locations of the instructions in the inst block to match those of
  3522. // the imported instructions.
  3523. for (auto [import_inst_id, local_inst_id] :
  3524. llvm::zip_equal(resolver.import_inst_blocks().Get(import_block_id),
  3525. resolver.local_inst_blocks().Get(eval_block_id))) {
  3526. auto import_ir_inst_id = AddImportIRInst(resolver, import_inst_id);
  3527. resolver.local_insts().SetLocId(local_inst_id, import_ir_inst_id);
  3528. }
  3529. return eval_block_id;
  3530. }
  3531. // Fills in the remaining information in a partially-imported generic.
  3532. // NOLINTNEXTLINE(misc-no-recursion)
  3533. static auto FinishPendingGeneric(ImportRefResolver& resolver,
  3534. ImportContext::PendingGeneric pending)
  3535. -> void {
  3536. const auto& import_generic =
  3537. resolver.import_generics().Get(pending.import_id);
  3538. auto& local_generic = resolver.local_generics().Get(pending.local_id);
  3539. // Load the bindings for the generic eagerly; they're used to form the self
  3540. // specific.
  3541. // TODO: Avoid recursion.
  3542. for (auto binding_id :
  3543. resolver.local_inst_blocks().Get(local_generic.bindings_id)) {
  3544. LoadImportRef(resolver.local_context(), binding_id);
  3545. }
  3546. local_generic.decl_block_id =
  3547. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  3548. SemIR::GenericInstIndex::Region::Declaration);
  3549. local_generic.self_specific_id =
  3550. MakeSelfSpecific(resolver.local_context(),
  3551. SemIR::LocId(local_generic.decl_id), pending.local_id);
  3552. resolver.AddPendingSpecific({.import_id = import_generic.self_specific_id,
  3553. .local_id = local_generic.self_specific_id});
  3554. local_generic.definition_block_id =
  3555. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  3556. SemIR::GenericInstIndex::Region::Definition);
  3557. }
  3558. // Resolves and returns a local inst block of constant instructions
  3559. // corresponding to an imported inst block.
  3560. static auto ResolveLocalInstBlock(ImportRefResolver& resolver,
  3561. SemIR::InstBlockId import_block_id)
  3562. -> SemIR::InstBlockId {
  3563. if (!import_block_id.has_value()) {
  3564. return SemIR::InstBlockId::None;
  3565. }
  3566. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  3567. return resolver.local_inst_blocks().Add(inst_ids);
  3568. }
  3569. // Fills in the remaining information in a partially-imported specific.
  3570. static auto FinishPendingSpecific(ImportRefResolver& resolver,
  3571. ImportContext::PendingSpecific pending)
  3572. -> void {
  3573. const auto& import_specific =
  3574. resolver.import_specifics().Get(pending.import_id);
  3575. auto& local_specific = resolver.local_specifics().Get(pending.local_id);
  3576. if (!local_specific.decl_block_id.has_value()) {
  3577. local_specific.decl_block_id =
  3578. ResolveLocalInstBlock(resolver, import_specific.decl_block_id);
  3579. }
  3580. if (!local_specific.definition_block_id.has_value() &&
  3581. import_specific.definition_block_id.has_value()) {
  3582. local_specific.definition_block_id =
  3583. ResolveLocalInstBlock(resolver, import_specific.definition_block_id);
  3584. }
  3585. }
  3586. // Perform any work that we deferred until the end of the main Resolve loop.
  3587. // NOLINTNEXTLINE(misc-no-recursion)
  3588. auto ImportRefResolver::PerformPendingWork() -> void {
  3589. // Note that the individual Finish steps can add new pending work, so keep
  3590. // going until we have no more work to do.
  3591. while (!pending_generics().empty() || !pending_specifics().empty()) {
  3592. // Process generics in the order that we added them because a later
  3593. // generic might refer to an earlier one, and the calls to
  3594. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  3595. // state.
  3596. // TODO: Import the generic eval block rather than calling
  3597. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  3598. for (auto generic_id : GrowingRange(pending_generics())) {
  3599. FinishPendingGeneric(*this, generic_id);
  3600. }
  3601. pending_generics().clear();
  3602. while (!pending_specifics().empty()) {
  3603. FinishPendingSpecific(*this, pending_specifics().pop_back_val());
  3604. }
  3605. }
  3606. }
  3607. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  3608. // loaded (including the one pointed at directly by the ImportRef), and the
  3609. // final instruction's type ID.
  3610. //
  3611. // This addresses cases where an ImportRefUnloaded may point at another
  3612. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  3613. // constant-evaluated version of the instruction to work with.
  3614. static auto GetInstForLoad(Context& context,
  3615. SemIR::ImportIRInstId import_ir_inst_id)
  3616. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  3617. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  3618. {}, SemIR::TypeId::None};
  3619. auto& [import_ir_insts, type_id] = result;
  3620. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  3621. // The first ImportIRInst is added directly because the IR doesn't need to be
  3622. // localized.
  3623. import_ir_insts.push_back(import_ir_inst);
  3624. const auto* cursor_ir =
  3625. context.import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  3626. while (true) {
  3627. auto cursor_inst =
  3628. cursor_ir->insts().GetWithAttachedType(import_ir_inst.inst_id());
  3629. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  3630. if (!import_ref) {
  3631. type_id = cursor_inst.type_id();
  3632. return result;
  3633. }
  3634. import_ir_inst =
  3635. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  3636. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  3637. import_ir_insts.push_back(SemIR::ImportIRInst(
  3638. AddImportIR(context, {.decl_id = SemIR::InstId::None,
  3639. .is_export = false,
  3640. .sem_ir = cursor_ir}),
  3641. import_ir_inst.inst_id()));
  3642. }
  3643. }
  3644. // NOLINTNEXTLINE(misc-no-recursion)
  3645. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  3646. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  3647. if (!inst) {
  3648. return;
  3649. }
  3650. auto [indirect_insts, load_type_id] =
  3651. GetInstForLoad(context, inst->import_ir_inst_id);
  3652. // The last indirect instruction is the one to resolve. Pop it here because
  3653. // Resolve will assign the constant.
  3654. auto load_ir_inst = indirect_insts.pop_back_val();
  3655. ImportRefResolver resolver(&context, load_ir_inst.ir_id());
  3656. // Loading an import ref creates local constants from the import ones, but
  3657. // shouldn't be generating novel instructions in the semir as a side effect of
  3658. // that process. Doing so in a generic context would also cause them to end up
  3659. // in the eval block, which would be doubly wrong.
  3660. context.inst_block_stack().Push();
  3661. auto type_id = resolver.ResolveType(load_type_id);
  3662. auto constant_id = resolver.Resolve(load_ir_inst.inst_id());
  3663. CARBON_CHECK(
  3664. context.inst_block_stack().PeekCurrentBlockContents().empty(),
  3665. "Importing an instruction shouldn't add new instructions to the "
  3666. "local inst block. Found {0} new instructions, first is {1}: {2}.",
  3667. context.inst_block_stack().PeekCurrentBlockContents().size(),
  3668. context.inst_block_stack().PeekCurrentBlockContents().front(),
  3669. context.insts().Get(
  3670. context.inst_block_stack().PeekCurrentBlockContents().front()));
  3671. context.inst_block_stack().PopAndDiscard();
  3672. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  3673. // doesn't use ReplacePlaceholderImportedInst because it would trigger
  3674. // TryEvalInst, which we want to avoid with ImportRefs.
  3675. context.sem_ir().insts().Set(
  3676. inst_id,
  3677. SemIR::ImportRefLoaded{.type_id = type_id,
  3678. .import_ir_inst_id = inst->import_ir_inst_id,
  3679. .entity_name_id = inst->entity_name_id});
  3680. // Store the constant for both the ImportRefLoaded and indirect instructions.
  3681. context.constant_values().Set(inst_id, constant_id);
  3682. for (const auto& import_ir_inst : indirect_insts) {
  3683. context
  3684. .import_ir_constant_values()[context.sem_ir().import_irs().GetRawIndex(
  3685. import_ir_inst.ir_id())]
  3686. .Set(import_ir_inst.inst_id(), constant_id);
  3687. }
  3688. }
  3689. auto ImportImplsFromApiFile(Context& context) -> void {
  3690. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  3691. auto& import_ir = context.import_irs().Get(import_ir_id);
  3692. if (!import_ir.sem_ir) {
  3693. return;
  3694. }
  3695. for (auto [impl_id, _] : import_ir.sem_ir->impls().enumerate()) {
  3696. // Resolve the imported impl to a local impl ID.
  3697. ImportImpl(context, import_ir_id, impl_id);
  3698. }
  3699. }
  3700. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  3701. SemIR::ImplId impl_id) -> void {
  3702. ImportRefResolver resolver(&context, import_ir_id);
  3703. resolver.Resolve(context.import_irs()
  3704. .Get(import_ir_id)
  3705. .sem_ir->impls()
  3706. .Get(impl_id)
  3707. .first_decl_id());
  3708. }
  3709. auto ImportInterface(Context& context, SemIR::ImportIRId import_ir_id,
  3710. SemIR::InterfaceId interface_id) -> SemIR::InterfaceId {
  3711. ImportRefResolver resolver(&context, import_ir_id);
  3712. auto local_id = resolver.Resolve(context.import_irs()
  3713. .Get(import_ir_id)
  3714. .sem_ir->interfaces()
  3715. .Get(interface_id)
  3716. .first_decl_id());
  3717. auto local_inst =
  3718. context.insts().Get(context.constant_values().GetInstId(local_id));
  3719. // A non-generic interface will import as a facet type for that single
  3720. // interface.
  3721. if (auto facet_type = local_inst.TryAs<SemIR::FacetType>()) {
  3722. auto single = context.facet_types()
  3723. .Get(facet_type->facet_type_id)
  3724. .TryAsSingleExtend();
  3725. CARBON_CHECK(single,
  3726. "Importing an interface didn't produce a single interface");
  3727. return std::get<SemIR::SpecificInterface>(*single).interface_id;
  3728. }
  3729. // A generic interface will import as a constant of generic interface type.
  3730. auto generic_interface_type =
  3731. context.types().GetAs<SemIR::GenericInterfaceType>(local_inst.type_id());
  3732. return generic_interface_type.interface_id;
  3733. }
  3734. } // namespace Carbon::Check