import_ref.cpp 195 KB

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