import_ref.cpp 175 KB

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