import_ref.cpp 148 KB

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