import_ref.cpp 138 KB

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