import_ref.cpp 138 KB

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