import_ref.cpp 179 KB

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