import_ref.cpp 138 KB

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