import_ref.cpp 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475
  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/parse/node_ids.h"
  11. #include "toolchain/sem_ir/constant.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/import_ir.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/inst_kind.h"
  17. #include "toolchain/sem_ir/type_info.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. // Adds the ImportIR, excluding the update to the check_ir_map.
  21. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  22. -> SemIR::ImportIRId {
  23. context.import_ir_constant_values().push_back(
  24. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  25. return context.import_irs().Add(import_ir);
  26. }
  27. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  28. auto ir_id = SemIR::ImportIRId::Invalid;
  29. if (import_ir.sem_ir != nullptr) {
  30. ir_id = AddImportIR(context, import_ir);
  31. } else {
  32. // We don't have a check_ir_id, so add without touching check_ir_map.
  33. ir_id = InternalAddImportIR(context, import_ir);
  34. }
  35. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl,
  36. "ApiForImpl must be the first IR");
  37. }
  38. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  39. -> SemIR::ImportIRId {
  40. auto& ir_id = context.GetImportIRId(*import_ir.sem_ir);
  41. if (!ir_id.is_valid()) {
  42. // Note this updates check_ir_map.
  43. ir_id = InternalAddImportIR(context, import_ir);
  44. } else if (import_ir.is_export) {
  45. // We're processing an `export import`. In case the IR was indirectly added
  46. // as a non-export, mark it as an export.
  47. context.import_irs().Get(ir_id).is_export = true;
  48. }
  49. return ir_id;
  50. }
  51. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  52. SemIR::EntityNameId entity_name_id =
  53. SemIR::EntityNameId::Invalid) -> SemIR::InstId {
  54. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  55. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  56. .entity_name_id = entity_name_id};
  57. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  58. context.MakeImportedLocAndInst(import_ir_inst_id, inst));
  59. // ImportRefs have a dedicated block because this may be called during
  60. // processing where the instruction shouldn't be inserted in the current inst
  61. // block.
  62. context.import_ref_ids().push_back(import_ref_id);
  63. return import_ref_id;
  64. }
  65. // Adds an import_ref instruction for an instruction that we have already loaded
  66. // from an imported IR, with a known constant value. This is useful when the
  67. // instruction has a symbolic constant value, in order to produce an instruction
  68. // that hold that symbolic constant.
  69. static auto AddLoadedImportRef(Context& context,
  70. SemIR::ImportIRInst import_ir_inst,
  71. SemIR::TypeId type_id,
  72. SemIR::ConstantId const_id) -> SemIR::InstId {
  73. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  74. SemIR::ImportRefLoaded inst = {
  75. .type_id = type_id,
  76. .import_ir_inst_id = import_ir_inst_id,
  77. .entity_name_id = SemIR::EntityNameId::Invalid};
  78. auto inst_id = context.AddPlaceholderInstInNoBlock(
  79. context.MakeImportedLocAndInst(import_ir_inst_id, inst));
  80. context.import_ref_ids().push_back(inst_id);
  81. context.constant_values().Set(inst_id, const_id);
  82. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  83. import_ir_inst.inst_id, const_id);
  84. return inst_id;
  85. }
  86. auto GetCanonicalImportIRInst(Context& context, const SemIR::File* cursor_ir,
  87. SemIR::InstId cursor_inst_id)
  88. -> SemIR::ImportIRInst {
  89. while (true) {
  90. auto inst = cursor_ir->insts().Get(cursor_inst_id);
  91. CARBON_KIND_SWITCH(inst) {
  92. case CARBON_KIND(SemIR::ExportDecl bind_export): {
  93. cursor_inst_id = bind_export.value_id;
  94. continue;
  95. }
  96. case SemIR::ImportRefLoaded::Kind:
  97. case SemIR::ImportRefUnloaded::Kind: {
  98. auto import_ref = inst.As<SemIR::AnyImportRef>();
  99. auto import_ir_inst =
  100. cursor_ir->import_ir_insts().Get(import_ref.import_ir_inst_id);
  101. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  102. cursor_inst_id = import_ir_inst.inst_id;
  103. continue;
  104. }
  105. default: {
  106. auto ir_id = SemIR::ImportIRId::Invalid;
  107. if (cursor_ir != &context.sem_ir()) {
  108. // This uses AddImportIR in case it was indirectly found, which can
  109. // happen with two or more steps of exports.
  110. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  111. .is_export = false,
  112. .sem_ir = cursor_ir});
  113. }
  114. return {.ir_id = ir_id, .inst_id = cursor_inst_id};
  115. }
  116. }
  117. }
  118. }
  119. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::InstId prev_id,
  120. SemIR::ImportIRInst prev_import_ir_inst,
  121. SemIR::ImportIRId new_ir_id,
  122. const SemIR::File* new_import_ir,
  123. SemIR::InstId new_inst_id) -> void {
  124. auto new_import_ir_inst =
  125. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  126. if (new_import_ir_inst == prev_import_ir_inst) {
  127. return;
  128. }
  129. auto conflict_id =
  130. AddImportRef(context, {.ir_id = new_ir_id, .inst_id = new_inst_id});
  131. context.DiagnoseDuplicateName(conflict_id, prev_id);
  132. }
  133. // Returns an instruction that has the specified constant value.
  134. static auto GetInstWithConstantValue(const SemIR::File& file,
  135. SemIR::ConstantId const_id)
  136. -> SemIR::InstId {
  137. if (!const_id.is_valid()) {
  138. return SemIR::InstId::Invalid;
  139. }
  140. // For template constants, the corresponding instruction has the desired
  141. // constant value.
  142. if (!const_id.is_symbolic()) {
  143. return file.constant_values().GetInstId(const_id);
  144. }
  145. // For abstract symbolic constants, the corresponding instruction has the
  146. // desired constant value.
  147. const auto& symbolic_const =
  148. file.constant_values().GetSymbolicConstant(const_id);
  149. if (!symbolic_const.generic_id.is_valid()) {
  150. return file.constant_values().GetInstId(const_id);
  151. }
  152. // For a symbolic constant in a generic, pick the corresponding instruction
  153. // out of the eval block for the generic.
  154. const auto& generic = file.generics().Get(symbolic_const.generic_id);
  155. auto block = generic.GetEvalBlock(symbolic_const.index.region());
  156. return file.inst_blocks().Get(block)[symbolic_const.index.index()];
  157. }
  158. // Resolves an instruction from an imported IR into a constant referring to the
  159. // current IR.
  160. //
  161. // Calling Resolve on an instruction operates in an iterative manner, tracking
  162. // Work items on work_stack_. At a high level, the loop is:
  163. //
  164. // 1. If a constant value is already known for the work item and was not set by
  165. // this work item, it's considered resolved.
  166. // - The constant check avoids performance costs of deduplication on add.
  167. // - If we've processed this work item before, then we now process it again.
  168. // It didn't complete last time, even though we have a constant value
  169. // already.
  170. //
  171. // 2. Resolve the instruction (TryResolveInst/TryResolveTypedInst). This is done
  172. // in three phases. The first and second phases can add work to the worklist
  173. // and end in a retry, in which case those phases will be rerun once the
  174. // added work is done. The rerun cannot also end in a retry, so this results
  175. // in at most three calls, but in practice one or two calls is almost always
  176. // sufficient. Due to the chance of a second or third call to TryResolveInst,
  177. // it's important to only perform expensive work once, even when the same
  178. // phase is rerun.
  179. //
  180. // - First phase:
  181. // - Gather all input constants necessary to form the constant value of the
  182. // instruction. Gathering constants directly adds unresolved values to
  183. // work_stack_.
  184. // - If HasNewWork() reports that any work was added, then return Retry():
  185. // this instruction needs another call to complete. Gather the
  186. // now-resolved constants and continue to the next step once the retry
  187. // happens.
  188. //
  189. // - Second phase:
  190. // - Build the constant value of the instruction.
  191. // - Gather all input constants necessary to finish importing the
  192. // instruction. This is only necessary for instructions like classes that
  193. // can be forward-declared. For these instructions, we first import the
  194. // constant value and then later import the rest of the declaration in
  195. // order to break cycles.
  196. // - If HasNewWork() reports that any work was added, then return
  197. // Retry(constant_value): this instruction needs another call to
  198. // complete. Gather the now-resolved constants and continue to the next
  199. // step once the retry happens.
  200. //
  201. // - Third phase:
  202. // - After the second phase, the constant value for the instruction is
  203. // already set, and will be passed back into TryResolve*Inst on retry. It
  204. // should not be created again.
  205. // - Fill in any remaining information to complete the import of the
  206. // instruction. For example, when importing a class declaration, build
  207. // the class scope and information about the definition.
  208. // - Return ResolveAs/ResolveAsConstant to finish the resolution process.
  209. // This will cause the Resolve loop to set a constant value if we didn't
  210. // retry at the end of the second phase.
  211. //
  212. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  213. // remain, and may no longer be at the top of the stack; update the state of
  214. // the work item to track what work still needs to be done.
  215. //
  216. // The same instruction can be enqueued for resolution multiple times. However,
  217. // we will only reach the second phase once: once a constant value is set, only
  218. // the resolution step that set it will retry.
  219. //
  220. // TODO: Fix class `extern` handling and merging, rewrite tests.
  221. // - check/testdata/class/cross_package_import.carbon
  222. // - check/testdata/class/extern.carbon
  223. // TODO: Fix function `extern` handling and merging, rewrite tests.
  224. // - check/testdata/function/declaration/import.carbon
  225. // - check/testdata/packages/cross_package_import.carbon
  226. class ImportRefResolver {
  227. public:
  228. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  229. : context_(context),
  230. import_ir_id_(import_ir_id),
  231. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  232. // Iteratively resolves an imported instruction's inner references until a
  233. // constant ID referencing the current IR is produced. See the class comment
  234. // for more details.
  235. auto ResolveOneInst(SemIR::InstId inst_id) -> SemIR::ConstantId {
  236. work_stack_.push_back({.inst_id = inst_id});
  237. while (!work_stack_.empty()) {
  238. auto work = work_stack_.back();
  239. CARBON_CHECK(work.inst_id.is_valid());
  240. // Step 1: check for a constant value.
  241. auto existing = FindResolvedConstId(work.inst_id);
  242. if (existing.const_id.is_valid() && !work.retry_with_constant_value) {
  243. work_stack_.pop_back();
  244. continue;
  245. }
  246. // Step 2: resolve the instruction.
  247. initial_work_ = work_stack_.size();
  248. auto [new_const_id, retry] =
  249. TryResolveInst(work.inst_id, existing.const_id);
  250. CARBON_CHECK(
  251. !existing.const_id.is_valid() || existing.const_id == new_const_id,
  252. "Constant value changed in third phase.");
  253. if (!existing.const_id.is_valid()) {
  254. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  255. }
  256. // Step 3: pop or retry.
  257. if (retry) {
  258. work_stack_[initial_work_ - 1].retry_with_constant_value =
  259. new_const_id.is_valid();
  260. } else {
  261. work_stack_.pop_back();
  262. }
  263. }
  264. auto constant_id = import_ir_constant_values().Get(inst_id);
  265. CARBON_CHECK(constant_id.is_valid());
  266. return constant_id;
  267. }
  268. // Performs resolution for one instruction and then performs all work we
  269. // deferred.
  270. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  271. auto const_id = ResolveOneInst(inst_id);
  272. PerformPendingWork();
  273. return const_id;
  274. }
  275. // Wraps constant evaluation with logic to handle constants.
  276. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId {
  277. return Resolve(GetInstWithConstantValue(import_ir_, import_const_id));
  278. }
  279. // Wraps constant evaluation with logic to handle types.
  280. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  281. if (!import_type_id.is_valid()) {
  282. return import_type_id;
  283. }
  284. auto import_type_const_id =
  285. import_ir_.types().GetConstantId(import_type_id);
  286. CARBON_CHECK(import_type_const_id.is_valid());
  287. if (auto import_type_inst_id =
  288. import_ir_.constant_values().GetInstId(import_type_const_id);
  289. import_type_inst_id.is_builtin()) {
  290. // Builtins don't require constant resolution; we can use them directly.
  291. return context_.GetBuiltinType(import_type_inst_id.builtin_inst_kind());
  292. } else {
  293. return context_.GetTypeIdForTypeConstant(
  294. ResolveConstant(import_type_id.AsConstantId()));
  295. }
  296. }
  297. private:
  298. // The result of attempting to resolve an imported instruction to a constant.
  299. struct ResolveResult {
  300. // The new constant value, if known.
  301. SemIR::ConstantId const_id;
  302. // Whether resolution has been attempted once and needs to be retried.
  303. bool retry = false;
  304. };
  305. // A step in work_stack_.
  306. struct Work {
  307. // The instruction to work on.
  308. SemIR::InstId inst_id;
  309. // Whether this work item set the constant value for the instruction and
  310. // requested a retry.
  311. bool retry_with_constant_value = false;
  312. };
  313. // The constant found by FindResolvedConstId.
  314. struct ResolvedConstId {
  315. // The constant for the instruction. Invalid if not yet resolved.
  316. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  317. // Instructions which are indirect but equivalent to the current instruction
  318. // being resolved, and should have their constant set to the same. Empty
  319. // when const_id is valid.
  320. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  321. };
  322. // Local information associated with an imported generic.
  323. struct GenericData {
  324. llvm::SmallVector<SemIR::InstId> bindings;
  325. };
  326. // Local information associated with an imported specific.
  327. struct SpecificData {
  328. SemIR::ConstantId generic_const_id;
  329. llvm::SmallVector<SemIR::InstId> args;
  330. };
  331. // A generic that we have partially imported.
  332. struct PendingGeneric {
  333. SemIR::GenericId import_id;
  334. SemIR::GenericId local_id;
  335. };
  336. // A specific that we have partially imported.
  337. struct PendingSpecific {
  338. SemIR::SpecificId import_id;
  339. SemIR::SpecificId local_id;
  340. };
  341. // Looks to see if an instruction has been resolved. If a constant is only
  342. // found indirectly, sets the constant for any indirect steps that don't
  343. // already have the constant. If a constant isn't found, returns the indirect
  344. // instructions so that they can have the resolved constant assigned later.
  345. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  346. ResolvedConstId result;
  347. if (auto existing_const_id = import_ir_constant_values().Get(inst_id);
  348. existing_const_id.is_valid()) {
  349. result.const_id = existing_const_id;
  350. return result;
  351. }
  352. const auto* cursor_ir = &import_ir_;
  353. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  354. auto cursor_inst_id = inst_id;
  355. while (true) {
  356. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  357. if (!loc_id.is_import_ir_inst_id()) {
  358. return result;
  359. }
  360. auto ir_inst =
  361. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  362. const auto* prev_ir = cursor_ir;
  363. auto prev_inst_id = cursor_inst_id;
  364. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  365. cursor_ir_id = context_.GetImportIRId(*cursor_ir);
  366. if (!cursor_ir_id.is_valid()) {
  367. // TODO: Should we figure out a location to assign here?
  368. cursor_ir_id = AddImportIR(context_, {.decl_id = SemIR::InstId::Invalid,
  369. .is_export = false,
  370. .sem_ir = cursor_ir});
  371. }
  372. cursor_inst_id = ir_inst.inst_id;
  373. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id,
  374. "{0}", cursor_ir->insts().Get(cursor_inst_id));
  375. if (auto const_id =
  376. context_.import_ir_constant_values()[cursor_ir_id.index].Get(
  377. cursor_inst_id);
  378. const_id.is_valid()) {
  379. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  380. result.const_id = const_id;
  381. result.indirect_insts.clear();
  382. return result;
  383. } else {
  384. result.indirect_insts.push_back(
  385. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  386. }
  387. }
  388. }
  389. // Sets a resolved constant into the current and indirect instructions.
  390. auto SetResolvedConstId(SemIR::InstId inst_id,
  391. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  392. SemIR::ConstantId const_id) -> void {
  393. import_ir_constant_values().Set(inst_id, const_id);
  394. for (auto indirect_inst : indirect_insts) {
  395. context_.import_ir_constant_values()[indirect_inst.ir_id.index].Set(
  396. indirect_inst.inst_id, const_id);
  397. }
  398. }
  399. // Returns true if new unresolved constants were found as part of this
  400. // `Resolve` step.
  401. auto HasNewWork() -> bool {
  402. CARBON_CHECK(initial_work_ <= work_stack_.size(),
  403. "Work shouldn't decrease");
  404. return initial_work_ < work_stack_.size();
  405. }
  406. auto AddImportIRInst(SemIR::InstId inst_id) -> SemIR::ImportIRInstId {
  407. return context_.import_ir_insts().Add(
  408. {.ir_id = import_ir_id_, .inst_id = inst_id});
  409. }
  410. // Returns the ConstantId for an InstId. Adds unresolved constants to
  411. // work_stack_.
  412. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  413. auto const_id = import_ir_constant_values().Get(inst_id);
  414. if (!const_id.is_valid()) {
  415. work_stack_.push_back({.inst_id = inst_id});
  416. }
  417. return const_id;
  418. }
  419. // Returns the ConstantId for an imported ConstantId. Adds unresolved
  420. // constants to work_stack_.
  421. auto GetLocalConstantId(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  422. return GetLocalConstantId(GetInstWithConstantValue(import_ir_, const_id));
  423. }
  424. // Returns the local constant InstId for an imported InstId.
  425. auto GetLocalConstantInstId(SemIR::InstId inst_id) -> SemIR::InstId {
  426. auto const_id = import_ir_constant_values().Get(inst_id);
  427. if (!const_id.is_valid()) {
  428. work_stack_.push_back({.inst_id = inst_id});
  429. return SemIR::InstId::Invalid;
  430. }
  431. return context_.constant_values().GetInstId(const_id);
  432. }
  433. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  434. // work_stack_.
  435. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  436. return GetLocalConstantId(import_ir_.types().GetConstantId(type_id));
  437. }
  438. template <typename Id>
  439. auto GetLocalConstantIdChecked(Id id) {
  440. auto result = GetLocalConstantId(id);
  441. CARBON_CHECK(result.is_valid());
  442. return result;
  443. }
  444. // Gets the local constant values corresponding to an imported inst block.
  445. auto GetLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  446. -> llvm::SmallVector<SemIR::InstId> {
  447. llvm::SmallVector<SemIR::InstId> inst_ids;
  448. if (!import_block_id.is_valid() ||
  449. import_block_id == SemIR::InstBlockId::Empty) {
  450. return inst_ids;
  451. }
  452. // Import all the values in the block.
  453. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  454. inst_ids.reserve(import_block.size());
  455. for (auto import_inst_id : import_block) {
  456. auto const_id = GetLocalConstantId(import_inst_id);
  457. inst_ids.push_back(context_.constant_values().GetInstIdIfValid(const_id));
  458. }
  459. return inst_ids;
  460. }
  461. // Gets a local instruction block ID corresponding to an imported inst block
  462. // whose contents were already imported, for example by
  463. // GetLocalInstBlockContents.
  464. auto GetLocalInstBlockId(SemIR::InstBlockId import_block_id,
  465. llvm::ArrayRef<SemIR::InstId> contents)
  466. -> SemIR::InstBlockId {
  467. if (!import_block_id.is_valid()) {
  468. return SemIR::InstBlockId::Invalid;
  469. }
  470. return context_.inst_blocks().Add(contents);
  471. }
  472. // Gets a local canonical instruction block ID corresponding to an imported
  473. // inst block whose contents were already imported, for example by
  474. // GetLocalInstBlockContents.
  475. auto GetLocalCanonicalInstBlockId(SemIR::InstBlockId import_block_id,
  476. llvm::ArrayRef<SemIR::InstId> contents)
  477. -> SemIR::InstBlockId {
  478. if (!import_block_id.is_valid()) {
  479. return SemIR::InstBlockId::Invalid;
  480. }
  481. return context_.inst_blocks().AddCanonical(contents);
  482. }
  483. // Gets an incomplete local version of an imported generic. Most fields are
  484. // set in the third phase.
  485. auto MakeIncompleteGeneric(SemIR::InstId decl_id, SemIR::GenericId generic_id)
  486. -> SemIR::GenericId {
  487. if (!generic_id.is_valid()) {
  488. return SemIR::GenericId::Invalid;
  489. }
  490. return context_.generics().Add(
  491. {.decl_id = decl_id,
  492. .bindings_id = SemIR::InstBlockId::Invalid,
  493. .self_specific_id = SemIR::SpecificId::Invalid});
  494. }
  495. // Gets a local version of the data associated with a generic.
  496. auto GetLocalGenericData(SemIR::GenericId generic_id) -> GenericData {
  497. if (!generic_id.is_valid()) {
  498. return GenericData();
  499. }
  500. const auto& generic = import_ir_.generics().Get(generic_id);
  501. return {.bindings = GetLocalInstBlockContents(generic.bindings_id)};
  502. }
  503. // Adds the given local generic data to the given generic.
  504. auto SetGenericData(SemIR::GenericId import_generic_id,
  505. SemIR::GenericId new_generic_id,
  506. const GenericData& generic_data) -> void {
  507. if (!import_generic_id.is_valid()) {
  508. return;
  509. }
  510. const auto& import_generic = import_ir_.generics().Get(import_generic_id);
  511. auto& new_generic = context_.generics().Get(new_generic_id);
  512. new_generic.bindings_id = GetLocalCanonicalInstBlockId(
  513. import_generic.bindings_id, generic_data.bindings);
  514. // Fill in the remaining information in FinishPendingGeneric.
  515. pending_generics_.push_back(
  516. {.import_id = import_generic_id, .local_id = new_generic_id});
  517. }
  518. // Gets a local constant value corresponding to an imported generic ID. May
  519. // add work to the work stack and return `Invalid`.
  520. auto GetLocalConstantId(SemIR::GenericId generic_id) -> SemIR::ConstantId {
  521. if (!generic_id.is_valid()) {
  522. return SemIR::ConstantId::Invalid;
  523. }
  524. auto import_decl_inst_id = import_ir_.generics().Get(generic_id).decl_id;
  525. auto import_decl_inst = import_ir_.insts().Get(import_decl_inst_id);
  526. if (import_decl_inst.Is<SemIR::ImplDecl>()) {
  527. // For an impl declaration, the imported entity can be found via the
  528. // declaration.
  529. return GetLocalConstantId(import_decl_inst_id);
  530. }
  531. // For all other kinds of declaration, the imported entity can be found via
  532. // the type of the declaration.
  533. return GetLocalConstantId(import_decl_inst.type_id());
  534. }
  535. // Gets a local generic ID given the corresponding local constant ID returned
  536. // by GetLocalConstantId for the imported generic. Does not add any new work.
  537. auto GetLocalGenericId(SemIR::ConstantId local_const_id) -> SemIR::GenericId {
  538. if (!local_const_id.is_valid()) {
  539. return SemIR::GenericId::Invalid;
  540. }
  541. auto inst = context_.insts().Get(
  542. context_.constant_values().GetInstId(local_const_id));
  543. CARBON_KIND_SWITCH(inst) {
  544. case CARBON_KIND(SemIR::FunctionType fn_type): {
  545. return context_.functions().Get(fn_type.function_id).generic_id;
  546. }
  547. case CARBON_KIND(SemIR::GenericClassType class_type): {
  548. return context_.classes().Get(class_type.class_id).generic_id;
  549. }
  550. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  551. return context_.interfaces()
  552. .Get(interface_type.interface_id)
  553. .generic_id;
  554. }
  555. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  556. return context_.impls().Get(impl_decl.impl_id).generic_id;
  557. }
  558. default: {
  559. CARBON_FATAL("Unexpected inst for generic declaration: {0}", inst);
  560. }
  561. }
  562. }
  563. // Gets local information about an imported specific.
  564. auto GetLocalSpecificData(SemIR::SpecificId specific_id) -> SpecificData {
  565. if (!specific_id.is_valid()) {
  566. return {.generic_const_id = SemIR::ConstantId::Invalid, .args = {}};
  567. }
  568. const auto& specific = import_ir_.specifics().Get(specific_id);
  569. return {
  570. .generic_const_id = GetLocalConstantId(specific.generic_id),
  571. .args = GetLocalInstBlockContents(specific.args_id),
  572. };
  573. }
  574. // Gets a local specific whose data was already imported by
  575. // GetLocalSpecificData. Does not add any new work.
  576. auto GetOrAddLocalSpecific(SemIR::SpecificId import_specific_id,
  577. const SpecificData& data) -> SemIR::SpecificId {
  578. if (!import_specific_id.is_valid()) {
  579. return SemIR::SpecificId::Invalid;
  580. }
  581. // Form a corresponding local specific ID.
  582. const auto& import_specific =
  583. import_ir_.specifics().Get(import_specific_id);
  584. auto generic_id = GetLocalGenericId(data.generic_const_id);
  585. auto args_id =
  586. GetLocalCanonicalInstBlockId(import_specific.args_id, data.args);
  587. // Get the specific.
  588. auto specific_id = context_.specifics().GetOrAdd(generic_id, args_id);
  589. // Fill in the remaining information in FinishPendingSpecific, if necessary.
  590. auto& specific = context_.specifics().Get(specific_id);
  591. if (!specific.decl_block_id.is_valid() ||
  592. (import_specific.definition_block_id.is_valid() &&
  593. !specific.definition_block_id.is_valid())) {
  594. pending_specifics_.push_back(
  595. {.import_id = import_specific_id, .local_id = specific_id});
  596. }
  597. return specific_id;
  598. }
  599. // Adds unresolved constants for each parameter's type to work_stack_.
  600. auto LoadLocalParamConstantIds(SemIR::InstBlockId param_refs_id) -> void {
  601. if (!param_refs_id.is_valid() ||
  602. param_refs_id == SemIR::InstBlockId::Empty) {
  603. return;
  604. }
  605. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  606. for (auto inst_id : param_refs) {
  607. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id());
  608. // If the parameter is a symbolic binding, build the BindSymbolicName
  609. // constant.
  610. auto bind_id = inst_id;
  611. auto bind_inst = import_ir_.insts().Get(bind_id);
  612. if (bind_inst.Is<SemIR::BindSymbolicName>()) {
  613. GetLocalConstantId(bind_id);
  614. }
  615. }
  616. }
  617. // Adds unresolved constants for each parameter's type to work_stack_.
  618. auto LoadLocalPatternConstantIds(SemIR::InstBlockId param_patterns_id)
  619. -> void {
  620. if (!param_patterns_id.is_valid() ||
  621. param_patterns_id == SemIR::InstBlockId::Empty) {
  622. return;
  623. }
  624. const auto& param_patterns =
  625. import_ir_.inst_blocks().Get(param_patterns_id);
  626. for (auto pattern_id : param_patterns) {
  627. auto pattern_inst = import_ir_.insts().Get(pattern_id);
  628. GetLocalConstantId(pattern_inst.type_id());
  629. if (auto addr = pattern_inst.TryAs<SemIR::AddrPattern>()) {
  630. pattern_id = addr->inner_id;
  631. pattern_inst = import_ir_.insts().Get(pattern_id);
  632. GetLocalConstantId(pattern_inst.type_id());
  633. }
  634. pattern_id = import_ir_.insts()
  635. .GetAs<SemIR::ValueParamPattern>(pattern_id)
  636. .subpattern_id;
  637. pattern_inst = import_ir_.insts().Get(pattern_id);
  638. // If the parameter is a symbolic binding, build the
  639. // SymbolicBindingPattern constant.
  640. if (pattern_inst.Is<SemIR::SymbolicBindingPattern>()) {
  641. GetLocalConstantId(pattern_id);
  642. }
  643. }
  644. }
  645. // Returns a version of param_refs_id localized to the current IR.
  646. //
  647. // Must only be called after a call to GetLocalParamConstantIds(param_refs_id)
  648. // has completed without adding any new work to work_stack_.
  649. //
  650. // TODO: This is inconsistent with the rest of this class, which expects
  651. // the relevant constants to be explicitly passed in. That makes it
  652. // easier to statically detect when an input isn't loaded, but makes it
  653. // harder to support importing more complex inst structures. We should
  654. // take a holistic look at how to balance those concerns. For example,
  655. // could the same function be used to load the constants and use them, with
  656. // a parameter to select between the two?
  657. auto GetLocalParamRefsId(SemIR::InstBlockId param_refs_id)
  658. -> SemIR::InstBlockId {
  659. if (!param_refs_id.is_valid() ||
  660. param_refs_id == SemIR::InstBlockId::Empty) {
  661. return param_refs_id;
  662. }
  663. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  664. llvm::SmallVector<SemIR::InstId> new_param_refs;
  665. for (auto ref_id : param_refs) {
  666. // Figure out the param structure. This echoes
  667. // Function::GetParamFromParamRefId, and could use that function if we
  668. // added `bool addr` and `InstId bind_inst_id` to its return `ParamInfo`.
  669. // TODO: Consider a different parameter handling to simplify import logic.
  670. auto inst = import_ir_.insts().Get(ref_id);
  671. auto bind_id = ref_id;
  672. auto param_id = ref_id;
  673. auto bind_inst = inst.As<SemIR::AnyBindName>();
  674. param_id = bind_inst.value_id;
  675. inst = import_ir_.insts().Get(param_id);
  676. auto param_inst = inst.As<SemIR::ValueParam>();
  677. // Rebuild the param instruction.
  678. auto entity_name =
  679. import_ir_.entity_names().Get(bind_inst.entity_name_id);
  680. auto name_id = GetLocalNameId(entity_name.name_id);
  681. auto type_id = context_.GetTypeIdForTypeConstant(
  682. GetLocalConstantIdChecked(param_inst.type_id));
  683. auto new_param_id = context_.AddInstInNoBlock<SemIR::ValueParam>(
  684. AddImportIRInst(param_id),
  685. {.type_id = type_id,
  686. .runtime_index = param_inst.runtime_index,
  687. .pretty_name_id = GetLocalNameId(param_inst.pretty_name_id)});
  688. switch (bind_inst.kind) {
  689. case SemIR::BindName::Kind: {
  690. auto entity_name_id = context_.entity_names().Add(
  691. {.name_id = name_id,
  692. .parent_scope_id = SemIR::NameScopeId::Invalid,
  693. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  694. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  695. AddImportIRInst(bind_id), {.type_id = type_id,
  696. .entity_name_id = entity_name_id,
  697. .value_id = new_param_id});
  698. break;
  699. }
  700. case SemIR::BindSymbolicName::Kind: {
  701. // We already imported a constant value for this symbolic binding.
  702. // We can reuse most of it, but update the value to point to our
  703. // specific parameter, and preserve the constant value.
  704. auto new_bind_inst = context_.insts().GetAs<SemIR::BindSymbolicName>(
  705. context_.constant_values().GetInstId(
  706. GetLocalConstantIdChecked(bind_id)));
  707. new_bind_inst.value_id = new_param_id;
  708. new_param_id = context_.AddInstInNoBlock(AddImportIRInst(bind_id),
  709. new_bind_inst);
  710. context_.constant_values().Set(new_param_id,
  711. GetLocalConstantIdChecked(bind_id));
  712. break;
  713. }
  714. default: {
  715. CARBON_FATAL("Unexpected kind: {0}", bind_inst.kind);
  716. }
  717. }
  718. new_param_refs.push_back(new_param_id);
  719. }
  720. return context_.inst_blocks().Add(new_param_refs);
  721. }
  722. // Returns a version of param_patterns_id localized to the current IR.
  723. //
  724. // Must only be called after a call to
  725. // LoadLocalPatternConstantIds(param_patterns_id) has completed without adding
  726. // any new work to work_stack_.
  727. auto GetLocalParamPatternsId(SemIR::InstBlockId param_patterns_id)
  728. -> SemIR::InstBlockId {
  729. if (!param_patterns_id.is_valid() ||
  730. param_patterns_id == SemIR::InstBlockId::Empty) {
  731. return param_patterns_id;
  732. }
  733. const auto& param_patterns =
  734. import_ir_.inst_blocks().Get(param_patterns_id);
  735. llvm::SmallVector<SemIR::InstId> new_patterns;
  736. for (auto param_id : param_patterns) {
  737. // Figure out the pattern structure. This echoes
  738. // Function::GetParamPatternInfoFromPatternId.
  739. auto addr_pattern_id = param_id;
  740. auto addr_inst =
  741. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(addr_pattern_id);
  742. auto param_pattern_id = addr_pattern_id;
  743. if (addr_inst) {
  744. param_pattern_id = addr_inst->inner_id;
  745. }
  746. auto param_pattern =
  747. import_ir_.insts().GetAs<SemIR::ValueParamPattern>(param_pattern_id);
  748. auto binding_id = param_pattern.subpattern_id;
  749. auto binding =
  750. import_ir_.insts().GetAs<SemIR::AnyBindingPattern>(binding_id);
  751. // Rebuild the pattern.
  752. auto entity_name = import_ir_.entity_names().Get(binding.entity_name_id);
  753. auto name_id = GetLocalNameId(entity_name.name_id);
  754. auto type_id = context_.GetTypeIdForTypeConstant(
  755. GetLocalConstantIdChecked(binding.type_id));
  756. auto new_param_id = SemIR::InstId::Invalid;
  757. switch (binding.kind) {
  758. case SemIR::BindingPattern::Kind: {
  759. auto entity_name_id = context_.entity_names().Add(
  760. {.name_id = name_id,
  761. .parent_scope_id = SemIR::NameScopeId::Invalid,
  762. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  763. new_param_id = context_.AddInstInNoBlock<SemIR::BindingPattern>(
  764. AddImportIRInst(binding_id),
  765. {.type_id = type_id,
  766. .entity_name_id = entity_name_id,
  767. .bind_name_id = SemIR::InstId::Invalid});
  768. break;
  769. }
  770. case SemIR::SymbolicBindingPattern::Kind: {
  771. // We already imported a constant value for this symbolic binding.
  772. // We can reuse most of it, but update the value to point to our
  773. // specific parameter, and preserve the constant value.
  774. auto bind_const_id = GetLocalConstantIdChecked(binding_id);
  775. auto new_binding_inst =
  776. context_.insts().GetAs<SemIR::SymbolicBindingPattern>(
  777. context_.constant_values().GetInstId(bind_const_id));
  778. new_param_id = context_.AddInstInNoBlock(AddImportIRInst(binding_id),
  779. new_binding_inst);
  780. context_.constant_values().Set(new_param_id, bind_const_id);
  781. break;
  782. }
  783. default: {
  784. CARBON_FATAL("Unexpected kind: ", binding.kind);
  785. }
  786. }
  787. new_param_id = context_.AddInstInNoBlock(
  788. context_.MakeImportedLocAndInst<SemIR::ValueParamPattern>(
  789. AddImportIRInst(param_pattern_id),
  790. {.type_id = type_id,
  791. .subpattern_id = new_param_id,
  792. .runtime_index = param_pattern.runtime_index}));
  793. if (addr_inst) {
  794. type_id = context_.GetTypeIdForTypeConstant(
  795. GetLocalConstantIdChecked(addr_inst->type_id));
  796. new_param_id = context_.AddInstInNoBlock(
  797. context_.MakeImportedLocAndInst<SemIR::AddrPattern>(
  798. AddImportIRInst(addr_pattern_id),
  799. {.type_id = type_id, .inner_id = new_param_id}));
  800. }
  801. new_patterns.push_back(new_param_id);
  802. }
  803. return context_.inst_blocks().Add(new_patterns);
  804. }
  805. // Returns a version of import_return_slot_pattern_id localized to the current
  806. // IR.
  807. auto GetLocalReturnSlotPatternId(SemIR::InstId import_return_slot_pattern_id)
  808. -> SemIR::InstId {
  809. if (!import_return_slot_pattern_id.is_valid()) {
  810. return SemIR::InstId::Invalid;
  811. }
  812. auto param_pattern = import_ir_.insts().GetAs<SemIR::OutParamPattern>(
  813. import_return_slot_pattern_id);
  814. auto return_slot_pattern =
  815. import_ir_.insts().GetAs<SemIR::ReturnSlotPattern>(
  816. param_pattern.subpattern_id);
  817. auto type_id = context_.GetTypeIdForTypeConstant(
  818. GetLocalConstantIdChecked(return_slot_pattern.type_id));
  819. auto new_return_slot_pattern_id = context_.AddInstInNoBlock(
  820. context_.MakeImportedLocAndInst<SemIR::ReturnSlotPattern>(
  821. AddImportIRInst(param_pattern.subpattern_id),
  822. {.type_id = type_id, .type_inst_id = SemIR::InstId::Invalid}));
  823. return context_.AddInstInNoBlock(
  824. context_.MakeImportedLocAndInst<SemIR::OutParamPattern>(
  825. AddImportIRInst(import_return_slot_pattern_id),
  826. {.type_id = type_id,
  827. .subpattern_id = new_return_slot_pattern_id,
  828. .runtime_index = param_pattern.runtime_index}));
  829. }
  830. // Translates a NameId from the import IR to a local NameId.
  831. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  832. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  833. return SemIR::NameId::ForIdentifier(
  834. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  835. }
  836. return import_name_id;
  837. }
  838. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  839. // unresolved constants to the work stack.
  840. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  841. -> SemIR::NameScopeId {
  842. // Get the instruction that created the scope.
  843. auto [inst_id, inst] =
  844. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  845. if (!inst) {
  846. // Map scopes that aren't associated with an instruction to invalid
  847. // scopes. For now, such scopes aren't used, and we don't have a good way
  848. // to remap them.
  849. return SemIR::NameScopeId::Invalid;
  850. }
  851. // Get the constant value for the scope.
  852. auto const_id = SemIR::ConstantId::Invalid;
  853. CARBON_KIND_SWITCH(*inst) {
  854. case SemIR::Namespace::Kind:
  855. // If the namespace has already been imported, we can use its constant.
  856. // However, if it hasn't, we use Invalid instead of adding it to the
  857. // work stack. That's expected to be okay when resolving references.
  858. const_id = import_ir_constant_values().Get(inst_id);
  859. break;
  860. default:
  861. const_id = GetLocalConstantId(inst_id);
  862. }
  863. if (!const_id.is_valid()) {
  864. return SemIR::NameScopeId::Invalid;
  865. }
  866. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  867. auto name_scope_inst = context_.insts().Get(const_inst_id);
  868. CARBON_KIND_SWITCH(name_scope_inst) {
  869. case CARBON_KIND(SemIR::Namespace inst): {
  870. return inst.name_scope_id;
  871. }
  872. case CARBON_KIND(SemIR::ClassType inst): {
  873. return context_.classes().Get(inst.class_id).scope_id;
  874. }
  875. case CARBON_KIND(SemIR::ImplDecl inst): {
  876. return context_.impls().Get(inst.impl_id).scope_id;
  877. }
  878. case CARBON_KIND(SemIR::InterfaceType inst): {
  879. return context_.interfaces().Get(inst.interface_id).scope_id;
  880. }
  881. case SemIR::StructValue::Kind: {
  882. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  883. CARBON_KIND_SWITCH(type_inst) {
  884. case CARBON_KIND(SemIR::GenericClassType inst): {
  885. return context_.classes().Get(inst.class_id).scope_id;
  886. }
  887. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  888. return context_.interfaces().Get(inst.interface_id).scope_id;
  889. }
  890. default: {
  891. break;
  892. }
  893. }
  894. break;
  895. }
  896. default: {
  897. if (const_inst_id == SemIR::InstId::BuiltinError) {
  898. return SemIR::NameScopeId::Invalid;
  899. }
  900. break;
  901. }
  902. }
  903. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  904. name_scope_inst);
  905. }
  906. // Given an imported entity base, returns an incomplete, local version of it.
  907. //
  908. // Most fields are set in the third phase once they're imported. Import enough
  909. // of the parameter lists that we know whether this interface is a generic
  910. // interface and can build the right constant value for it.
  911. //
  912. // TODO: Support extern.
  913. // TODO: Add a better way to represent a generic prior to importing the
  914. // parameters.
  915. auto GetIncompleteLocalEntityBase(
  916. SemIR::InstId decl_id, const SemIR::EntityWithParamsBase& import_base)
  917. -> SemIR::EntityWithParamsBase {
  918. // Translate the extern_library_id if present.
  919. auto extern_library_id = SemIR::LibraryNameId::Invalid;
  920. if (import_base.extern_library_id.is_valid()) {
  921. if (import_base.extern_library_id.index >= 0) {
  922. auto val = import_ir_.string_literal_values().Get(
  923. import_base.extern_library_id.AsStringLiteralValueId());
  924. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  925. context_.string_literal_values().Add(val));
  926. } else {
  927. extern_library_id = import_base.extern_library_id;
  928. }
  929. }
  930. return {
  931. .name_id = GetLocalNameId(import_base.name_id),
  932. .parent_scope_id = SemIR::NameScopeId::Invalid,
  933. .generic_id = MakeIncompleteGeneric(decl_id, import_base.generic_id),
  934. .first_param_node_id = Parse::NodeId::Invalid,
  935. .last_param_node_id = Parse::NodeId::Invalid,
  936. .pattern_block_id = SemIR::InstBlockId::Invalid,
  937. .implicit_param_refs_id = import_base.implicit_param_refs_id.is_valid()
  938. ? SemIR::InstBlockId::Empty
  939. : SemIR::InstBlockId::Invalid,
  940. .implicit_param_patterns_id =
  941. import_base.implicit_param_patterns_id.is_valid()
  942. ? SemIR::InstBlockId::Empty
  943. : SemIR::InstBlockId::Invalid,
  944. .param_refs_id = import_base.param_refs_id.is_valid()
  945. ? SemIR::InstBlockId::Empty
  946. : SemIR::InstBlockId::Invalid,
  947. .param_patterns_id = import_base.param_patterns_id.is_valid()
  948. ? SemIR::InstBlockId::Empty
  949. : SemIR::InstBlockId::Invalid,
  950. .is_extern = import_base.is_extern,
  951. .extern_library_id = extern_library_id,
  952. .non_owning_decl_id = import_base.non_owning_decl_id.is_valid()
  953. ? decl_id
  954. : SemIR::InstId::Invalid,
  955. .first_owning_decl_id = import_base.first_owning_decl_id.is_valid()
  956. ? decl_id
  957. : SemIR::InstId::Invalid,
  958. };
  959. }
  960. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  961. // lookup.
  962. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  963. SemIR::NameScope& new_scope) -> void {
  964. for (auto entry : import_scope.names) {
  965. auto ref_id = AddImportRef(
  966. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id});
  967. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  968. .inst_id = ref_id,
  969. .access_kind = entry.access_kind});
  970. }
  971. }
  972. // Given a block ID for a list of associated entities of a witness, returns a
  973. // version localized to the current IR.
  974. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  975. -> SemIR::InstBlockId {
  976. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  977. return SemIR::InstBlockId::Empty;
  978. }
  979. auto associated_entities =
  980. import_ir_.inst_blocks().Get(associated_entities_id);
  981. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  982. new_associated_entities.reserve(associated_entities.size());
  983. for (auto inst_id : associated_entities) {
  984. new_associated_entities.push_back(
  985. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id}));
  986. }
  987. return context_.inst_blocks().Add(new_associated_entities);
  988. }
  989. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  990. // more has been added to the stack. A similar API is followed for all
  991. // following TryResolveTypedInst helper functions.
  992. //
  993. // `const_id` is Invalid unless we've tried to resolve this instruction
  994. // before, in which case it's the previous result.
  995. //
  996. // TODO: Error is returned when support is missing, but that should go away.
  997. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  998. -> ResolveResult {
  999. auto inst_const_id = import_ir_.constant_values().Get(inst_id);
  1000. if (!inst_const_id.is_valid() || !inst_const_id.is_symbolic()) {
  1001. return TryResolveInstCanonical(inst_id, const_id);
  1002. }
  1003. // Try to import the generic. This might add new work.
  1004. const auto& symbolic_const =
  1005. import_ir_.constant_values().GetSymbolicConstant(inst_const_id);
  1006. auto generic_const_id = GetLocalConstantId(symbolic_const.generic_id);
  1007. auto inner_const_id = SemIR::ConstantId::Invalid;
  1008. if (const_id.is_valid()) {
  1009. // For the third phase, extract the constant value that
  1010. // TryResolveInstCanonical produced previously.
  1011. inner_const_id = context_.constant_values().Get(
  1012. context_.constant_values().GetSymbolicConstant(const_id).inst_id);
  1013. }
  1014. // Import the constant and rebuild the symbolic constant data.
  1015. auto result = TryResolveInstCanonical(inst_id, inner_const_id);
  1016. if (!result.const_id.is_valid()) {
  1017. // First phase: TryResolveInstCanoncial needs a retry.
  1018. return result;
  1019. }
  1020. if (!const_id.is_valid()) {
  1021. // Second phase: we have created an abstract constant. Create a
  1022. // corresponding generic constant.
  1023. if (symbolic_const.generic_id.is_valid()) {
  1024. result.const_id = context_.constant_values().AddSymbolicConstant(
  1025. {.inst_id = context_.constant_values().GetInstId(result.const_id),
  1026. .generic_id = GetLocalGenericId(generic_const_id),
  1027. .index = symbolic_const.index});
  1028. }
  1029. } else {
  1030. // Third phase: perform a consistency check and produce the constant we
  1031. // created in the second phase.
  1032. CARBON_CHECK(result.const_id == inner_const_id,
  1033. "Constant value changed in third phase.");
  1034. result.const_id = const_id;
  1035. }
  1036. return result;
  1037. }
  1038. // Tries to resolve the InstId, returning a canonical constant when ready, or
  1039. // Invalid if more has been added to the stack. This is the same as
  1040. // TryResolveInst, except that it may resolve symbolic constants as canonical
  1041. // constants instead of as constants associated with a particular generic.
  1042. auto TryResolveInstCanonical(SemIR::InstId inst_id,
  1043. SemIR::ConstantId const_id) -> ResolveResult {
  1044. if (inst_id.is_builtin()) {
  1045. CARBON_CHECK(!const_id.is_valid());
  1046. // Constants for builtins can be directly copied.
  1047. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  1048. }
  1049. auto untyped_inst = import_ir_.insts().Get(inst_id);
  1050. CARBON_KIND_SWITCH(untyped_inst) {
  1051. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  1052. return TryResolveTypedInst(inst);
  1053. }
  1054. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  1055. return TryResolveTypedInst(inst);
  1056. }
  1057. case CARBON_KIND(SemIR::BaseDecl inst): {
  1058. return TryResolveTypedInst(inst, inst_id);
  1059. }
  1060. case CARBON_KIND(SemIR::BindAlias inst): {
  1061. return TryResolveTypedInst(inst);
  1062. }
  1063. case SemIR::BindName::Kind: {
  1064. // TODO: Should we be resolving BindNames at all?
  1065. return ResolveAsConstant(SemIR::ConstantId::NotConstant);
  1066. }
  1067. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  1068. return TryResolveTypedInst(inst);
  1069. }
  1070. case CARBON_KIND(SemIR::ClassDecl inst): {
  1071. return TryResolveTypedInst(inst, const_id);
  1072. }
  1073. case CARBON_KIND(SemIR::ClassType inst): {
  1074. return TryResolveTypedInst(inst);
  1075. }
  1076. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  1077. return TryResolveTypedInst(inst);
  1078. }
  1079. case CARBON_KIND(SemIR::ConstType inst): {
  1080. return TryResolveTypedInst(inst);
  1081. }
  1082. case CARBON_KIND(SemIR::ExportDecl inst): {
  1083. return TryResolveTypedInst(inst);
  1084. }
  1085. case CARBON_KIND(SemIR::FieldDecl inst): {
  1086. return TryResolveTypedInst(inst, inst_id);
  1087. }
  1088. case CARBON_KIND(SemIR::FunctionDecl inst): {
  1089. return TryResolveTypedInst(inst, const_id);
  1090. }
  1091. case CARBON_KIND(SemIR::FunctionType inst): {
  1092. return TryResolveTypedInst(inst);
  1093. }
  1094. case CARBON_KIND(SemIR::GenericClassType inst): {
  1095. return TryResolveTypedInst(inst);
  1096. }
  1097. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  1098. return TryResolveTypedInst(inst);
  1099. }
  1100. case CARBON_KIND(SemIR::ImplDecl inst): {
  1101. return TryResolveTypedInst(inst, const_id);
  1102. }
  1103. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  1104. return TryResolveTypedInst(inst, inst_id);
  1105. }
  1106. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  1107. return TryResolveTypedInst(inst, const_id);
  1108. }
  1109. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  1110. return TryResolveTypedInst(inst);
  1111. }
  1112. case CARBON_KIND(SemIR::InterfaceType inst): {
  1113. return TryResolveTypedInst(inst);
  1114. }
  1115. case CARBON_KIND(SemIR::IntValue inst): {
  1116. return TryResolveTypedInst(inst);
  1117. }
  1118. case CARBON_KIND(SemIR::IntType inst): {
  1119. return TryResolveTypedInst(inst);
  1120. }
  1121. case CARBON_KIND(SemIR::PointerType inst): {
  1122. return TryResolveTypedInst(inst);
  1123. }
  1124. case CARBON_KIND(SemIR::SpecificFunction inst): {
  1125. return TryResolveTypedInst(inst);
  1126. }
  1127. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  1128. return TryResolveTypedInst(inst);
  1129. }
  1130. case CARBON_KIND(SemIR::StructType inst): {
  1131. return TryResolveTypedInst(inst);
  1132. }
  1133. case CARBON_KIND(SemIR::StructValue inst): {
  1134. return TryResolveTypedInst(inst);
  1135. }
  1136. case CARBON_KIND(SemIR::TupleType inst): {
  1137. return TryResolveTypedInst(inst);
  1138. }
  1139. case CARBON_KIND(SemIR::TupleValue inst): {
  1140. return TryResolveTypedInst(inst);
  1141. }
  1142. case CARBON_KIND(SemIR::UnboundElementType inst): {
  1143. return TryResolveTypedInst(inst);
  1144. }
  1145. default:
  1146. context_.TODO(
  1147. SemIR::LocId(AddImportIRInst(inst_id)),
  1148. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  1149. return {.const_id = SemIR::ConstantId::Error};
  1150. }
  1151. }
  1152. // Produces a resolve result that tries resolving this instruction again. If
  1153. // `const_id` is specified, then this is the end of the second phase, and the
  1154. // constant value will be passed to the next resolution attempt. Otherwise,
  1155. // this is the end of the first phase.
  1156. auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  1157. -> ResolveResult {
  1158. CARBON_CHECK(HasNewWork());
  1159. return {.const_id = const_id, .retry = true};
  1160. }
  1161. // Produces a resolve result that provides the given constant value. Requires
  1162. // that there is no new work.
  1163. auto ResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  1164. CARBON_CHECK(!HasNewWork());
  1165. return {.const_id = const_id};
  1166. }
  1167. // Produces a resolve result that provides the given constant value. Retries
  1168. // instead if work has been added.
  1169. auto RetryOrResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  1170. if (HasNewWork()) {
  1171. return Retry();
  1172. }
  1173. return ResolveAsConstant(const_id);
  1174. }
  1175. // Produces a resolve result for the given instruction that describes a
  1176. // constant value. This should only be used for instructions that describe
  1177. // constants, and not for instructions that represent declarations. For a
  1178. // declaration, we need an associated location, so AddInstInNoBlock should be
  1179. // used instead. Requires that there is no new work.
  1180. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  1181. CARBON_CHECK(!HasNewWork());
  1182. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  1183. CARBON_CHECK(result.is_constant(), "{0} is not constant", inst);
  1184. return {.const_id = result};
  1185. }
  1186. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  1187. template <typename InstT>
  1188. auto ResolveAs(InstT inst) -> ResolveResult {
  1189. return ResolveAsUntyped(inst);
  1190. }
  1191. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  1192. auto type_const_id = GetLocalConstantId(inst.type_id);
  1193. if (HasNewWork()) {
  1194. return Retry();
  1195. }
  1196. // Add a lazy reference to the target declaration.
  1197. auto decl_id = AddImportRef(
  1198. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id});
  1199. return ResolveAs<SemIR::AssociatedEntity>(
  1200. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1201. .index = inst.index,
  1202. .decl_id = decl_id});
  1203. }
  1204. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  1205. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1206. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  1207. auto interface_inst_id = GetLocalConstantId(inst.interface_type_id);
  1208. if (HasNewWork()) {
  1209. return Retry();
  1210. }
  1211. return ResolveAs<SemIR::AssociatedEntityType>(
  1212. {.type_id = SemIR::TypeId::TypeType,
  1213. .interface_type_id =
  1214. context_.GetTypeIdForTypeConstant(interface_inst_id),
  1215. .entity_type_id =
  1216. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  1217. }
  1218. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  1219. -> ResolveResult {
  1220. auto type_const_id = GetLocalConstantId(inst.type_id);
  1221. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  1222. if (HasNewWork()) {
  1223. return Retry();
  1224. }
  1225. // Import the instruction in order to update contained base_type_id and
  1226. // track the import location.
  1227. auto inst_id = context_.AddInstInNoBlock(
  1228. context_.MakeImportedLocAndInst<SemIR::BaseDecl>(
  1229. AddImportIRInst(import_inst_id),
  1230. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1231. .base_type_id =
  1232. context_.GetTypeIdForTypeConstant(base_type_const_id),
  1233. .index = inst.index}));
  1234. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  1235. }
  1236. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  1237. auto value_id = GetLocalConstantId(inst.value_id);
  1238. return RetryOrResolveAsConstant(value_id);
  1239. }
  1240. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  1241. auto type_id = GetLocalConstantId(inst.type_id);
  1242. if (HasNewWork()) {
  1243. return Retry();
  1244. }
  1245. const auto& import_entity_name =
  1246. import_ir_.entity_names().Get(inst.entity_name_id);
  1247. auto name_id = GetLocalNameId(import_entity_name.name_id);
  1248. auto entity_name_id = context_.entity_names().Add(
  1249. {.name_id = name_id,
  1250. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1251. .bind_index = import_entity_name.bind_index});
  1252. return ResolveAs<SemIR::BindSymbolicName>(
  1253. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1254. .entity_name_id = entity_name_id,
  1255. .value_id = SemIR::InstId::Invalid});
  1256. }
  1257. auto TryResolveTypedInst(SemIR::SymbolicBindingPattern inst)
  1258. -> ResolveResult {
  1259. auto type_id = GetLocalConstantId(inst.type_id);
  1260. if (HasNewWork()) {
  1261. return Retry();
  1262. }
  1263. const auto& import_entity_name =
  1264. import_ir_.entity_names().Get(inst.entity_name_id);
  1265. auto name_id = GetLocalNameId(import_entity_name.name_id);
  1266. auto entity_name_id = context_.entity_names().Add(
  1267. {.name_id = name_id,
  1268. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1269. .bind_index = import_entity_name.bind_index});
  1270. return ResolveAs<SemIR::SymbolicBindingPattern>(
  1271. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1272. .entity_name_id = entity_name_id,
  1273. .bind_name_id = SemIR::InstId::Invalid});
  1274. }
  1275. // Makes an incomplete class. This is necessary even with classes with a
  1276. // complete declaration, because things such as `Self` may refer back to the
  1277. // type.
  1278. auto MakeIncompleteClass(const SemIR::Class& import_class,
  1279. SemIR::SpecificId enclosing_specific_id)
  1280. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1281. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  1282. .class_id = SemIR::ClassId::Invalid,
  1283. .decl_block_id = SemIR::InstBlockId::Empty};
  1284. auto class_decl_id =
  1285. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1286. AddImportIRInst(import_class.latest_decl_id()), class_decl));
  1287. // Regardless of whether ClassDecl is a complete type, we first need an
  1288. // incomplete type so that any references have something to point at.
  1289. class_decl.class_id = context_.classes().Add(
  1290. {GetIncompleteLocalEntityBase(class_decl_id, import_class),
  1291. {.self_type_id = SemIR::TypeId::Invalid,
  1292. .inheritance_kind = import_class.inheritance_kind}});
  1293. if (import_class.has_parameters()) {
  1294. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id,
  1295. enclosing_specific_id);
  1296. }
  1297. // Write the class ID into the ClassDecl.
  1298. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  1299. auto self_const_id = context_.constant_values().Get(class_decl_id);
  1300. return {class_decl.class_id, self_const_id};
  1301. }
  1302. // Fills out the class definition for an incomplete class.
  1303. auto AddClassDefinition(const SemIR::Class& import_class,
  1304. SemIR::Class& new_class,
  1305. SemIR::InstId complete_type_witness_id,
  1306. SemIR::InstId base_id) -> void {
  1307. new_class.definition_id = new_class.first_owning_decl_id;
  1308. new_class.complete_type_witness_id = complete_type_witness_id;
  1309. new_class.scope_id = context_.name_scopes().Add(
  1310. new_class.first_owning_decl_id, SemIR::NameId::Invalid,
  1311. new_class.parent_scope_id);
  1312. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  1313. const auto& import_scope =
  1314. import_ir_.name_scopes().Get(import_class.scope_id);
  1315. // Push a block so that we can add scoped instructions to it.
  1316. context_.inst_block_stack().Push();
  1317. AddNameScopeImportRefs(import_scope, new_scope);
  1318. new_class.body_block_id = context_.inst_block_stack().Pop();
  1319. if (import_class.base_id.is_valid()) {
  1320. new_class.base_id = base_id;
  1321. // Add the base scope to extended scopes.
  1322. auto base_inst_id = context_.types().GetInstId(
  1323. context_.insts()
  1324. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  1325. .base_type_id);
  1326. const auto& base_class = context_.classes().Get(
  1327. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  1328. new_scope.extended_scopes.push_back(base_class.scope_id);
  1329. }
  1330. CARBON_CHECK(new_scope.extended_scopes.size() ==
  1331. import_scope.extended_scopes.size());
  1332. }
  1333. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  1334. SemIR::ConstantId class_const_id) -> ResolveResult {
  1335. // TODO: The handling of interfaces repeats a lot with the handling of
  1336. // classes, and will likely also be repeated for named constraints and
  1337. // choice types. Factor out some of this functionality.
  1338. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  1339. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1340. if (!class_const_id.is_valid()) {
  1341. auto import_specific_id = SemIR::SpecificId::Invalid;
  1342. if (auto import_generic_class_type =
  1343. import_ir_.types().TryGetAs<SemIR::GenericClassType>(
  1344. inst.type_id)) {
  1345. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1346. }
  1347. auto specific_data = GetLocalSpecificData(import_specific_id);
  1348. if (HasNewWork()) {
  1349. // This is the end of the first phase. Don't make a new class yet if
  1350. // we already have new work.
  1351. return Retry();
  1352. }
  1353. // On the second phase, create a forward declaration of the class for any
  1354. // recursive references.
  1355. auto enclosing_specific_id =
  1356. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1357. std::tie(class_id, class_const_id) =
  1358. MakeIncompleteClass(import_class, enclosing_specific_id);
  1359. } else {
  1360. // On the third phase, compute the class ID from the constant
  1361. // value of the declaration.
  1362. auto class_const_inst = context_.insts().Get(
  1363. context_.constant_values().GetInstId(class_const_id));
  1364. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1365. class_id = class_type->class_id;
  1366. } else {
  1367. auto generic_class_type =
  1368. context_.types().GetAs<SemIR::GenericClassType>(
  1369. class_const_inst.type_id());
  1370. class_id = generic_class_type.class_id;
  1371. }
  1372. }
  1373. // Load constants for the definition.
  1374. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  1375. LoadLocalParamConstantIds(import_class.implicit_param_refs_id);
  1376. LoadLocalPatternConstantIds(import_class.implicit_param_patterns_id);
  1377. LoadLocalParamConstantIds(import_class.param_refs_id);
  1378. LoadLocalPatternConstantIds(import_class.param_patterns_id);
  1379. auto generic_data = GetLocalGenericData(import_class.generic_id);
  1380. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  1381. auto complete_type_witness_id =
  1382. import_class.complete_type_witness_id.is_valid()
  1383. ? GetLocalConstantInstId(import_class.complete_type_witness_id)
  1384. : SemIR::InstId::Invalid;
  1385. auto base_id = import_class.base_id.is_valid()
  1386. ? GetLocalConstantInstId(import_class.base_id)
  1387. : SemIR::InstId::Invalid;
  1388. if (HasNewWork()) {
  1389. return Retry(class_const_id);
  1390. }
  1391. auto& new_class = context_.classes().Get(class_id);
  1392. new_class.parent_scope_id = parent_scope_id;
  1393. new_class.implicit_param_refs_id =
  1394. GetLocalParamRefsId(import_class.implicit_param_refs_id);
  1395. new_class.implicit_param_patterns_id =
  1396. GetLocalParamPatternsId(import_class.implicit_param_patterns_id);
  1397. new_class.param_refs_id = GetLocalParamRefsId(import_class.param_refs_id);
  1398. new_class.param_patterns_id =
  1399. GetLocalParamPatternsId(import_class.param_patterns_id);
  1400. SetGenericData(import_class.generic_id, new_class.generic_id, generic_data);
  1401. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  1402. if (import_class.is_defined()) {
  1403. AddClassDefinition(import_class, new_class, complete_type_witness_id,
  1404. base_id);
  1405. }
  1406. return ResolveAsConstant(class_const_id);
  1407. }
  1408. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  1409. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1410. auto class_const_id = GetLocalConstantId(
  1411. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1412. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1413. if (HasNewWork()) {
  1414. return Retry();
  1415. }
  1416. // Find the corresponding class type. For a non-generic class, this is the
  1417. // type of the class declaration. For a generic class, build a class type
  1418. // referencing this specialization of the generic class.
  1419. auto class_const_inst = context_.insts().Get(
  1420. context_.constant_values().GetInstId(class_const_id));
  1421. if (class_const_inst.Is<SemIR::ClassType>()) {
  1422. return ResolveAsConstant(class_const_id);
  1423. } else {
  1424. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  1425. class_const_inst.type_id());
  1426. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1427. return ResolveAs<SemIR::ClassType>(
  1428. {.type_id = SemIR::TypeId::TypeType,
  1429. .class_id = generic_class_type.class_id,
  1430. .specific_id = specific_id});
  1431. }
  1432. }
  1433. auto TryResolveTypedInst(SemIR::CompleteTypeWitness inst) -> ResolveResult {
  1434. CARBON_CHECK(import_ir_.types().GetInstId(inst.type_id) ==
  1435. SemIR::InstId::BuiltinWitnessType);
  1436. auto object_repr_const_id = GetLocalConstantId(inst.object_repr_id);
  1437. if (HasNewWork()) {
  1438. return Retry();
  1439. }
  1440. auto object_repr_id =
  1441. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  1442. return ResolveAs<SemIR::CompleteTypeWitness>(
  1443. {.type_id =
  1444. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1445. .object_repr_id = object_repr_id});
  1446. }
  1447. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  1448. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1449. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  1450. if (HasNewWork()) {
  1451. return Retry();
  1452. }
  1453. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  1454. return ResolveAs<SemIR::ConstType>(
  1455. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  1456. }
  1457. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  1458. auto value_id = GetLocalConstantId(inst.value_id);
  1459. return RetryOrResolveAsConstant(value_id);
  1460. }
  1461. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  1462. -> ResolveResult {
  1463. auto const_id = GetLocalConstantId(inst.type_id);
  1464. if (HasNewWork()) {
  1465. return Retry();
  1466. }
  1467. auto inst_id = context_.AddInstInNoBlock(
  1468. context_.MakeImportedLocAndInst<SemIR::FieldDecl>(
  1469. AddImportIRInst(import_inst_id),
  1470. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  1471. .name_id = GetLocalNameId(inst.name_id),
  1472. .index = inst.index}));
  1473. return {.const_id = context_.constant_values().Get(inst_id)};
  1474. }
  1475. // Make a declaration of a function. This is done as a separate step from
  1476. // importing the function declaration in order to resolve cycles.
  1477. auto MakeFunctionDecl(const SemIR::Function& import_function,
  1478. SemIR::SpecificId specific_id)
  1479. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1480. SemIR::FunctionDecl function_decl = {
  1481. .type_id = SemIR::TypeId::Invalid,
  1482. .function_id = SemIR::FunctionId::Invalid,
  1483. .decl_block_id = SemIR::InstBlockId::Empty};
  1484. auto function_decl_id =
  1485. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1486. AddImportIRInst(import_function.first_decl_id()), function_decl));
  1487. // Start with an incomplete function.
  1488. function_decl.function_id = context_.functions().Add(
  1489. {GetIncompleteLocalEntityBase(function_decl_id, import_function),
  1490. {.return_slot_pattern_id = SemIR::InstId::Invalid,
  1491. .return_slot_id = SemIR::InstId::Invalid,
  1492. .builtin_function_kind = import_function.builtin_function_kind}});
  1493. function_decl.type_id =
  1494. context_.GetFunctionType(function_decl.function_id, specific_id);
  1495. // Write the function ID and type into the FunctionDecl.
  1496. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1497. return {function_decl.function_id,
  1498. context_.constant_values().Get(function_decl_id)};
  1499. }
  1500. auto TryResolveTypedInst(SemIR::FunctionDecl inst,
  1501. SemIR::ConstantId function_const_id)
  1502. -> ResolveResult {
  1503. const auto& import_function = import_ir_.functions().Get(inst.function_id);
  1504. SemIR::FunctionId function_id = SemIR::FunctionId::Invalid;
  1505. if (!function_const_id.is_valid()) {
  1506. auto import_specific_id = import_ir_.types()
  1507. .GetAs<SemIR::FunctionType>(inst.type_id)
  1508. .specific_id;
  1509. auto specific_data = GetLocalSpecificData(import_specific_id);
  1510. if (HasNewWork()) {
  1511. // This is the end of the first phase. Don't make a new function yet if
  1512. // we already have new work.
  1513. return Retry();
  1514. }
  1515. // On the second phase, create a forward declaration of the interface.
  1516. auto specific_id =
  1517. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1518. std::tie(function_id, function_const_id) =
  1519. MakeFunctionDecl(import_function, specific_id);
  1520. } else {
  1521. // On the third phase, compute the function ID from the constant value of
  1522. // the declaration.
  1523. auto function_const_inst = context_.insts().Get(
  1524. context_.constant_values().GetInstId(function_const_id));
  1525. auto function_type = context_.types().GetAs<SemIR::FunctionType>(
  1526. function_const_inst.type_id());
  1527. function_id = function_type.function_id;
  1528. }
  1529. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1530. if (import_function.return_slot_id.is_valid()) {
  1531. return_type_const_id = GetLocalConstantId(
  1532. import_ir_.insts().Get(import_function.return_slot_id).type_id());
  1533. }
  1534. auto parent_scope_id = GetLocalNameScopeId(import_function.parent_scope_id);
  1535. LoadLocalParamConstantIds(import_function.implicit_param_refs_id);
  1536. LoadLocalPatternConstantIds(import_function.implicit_param_patterns_id);
  1537. LoadLocalParamConstantIds(import_function.param_refs_id);
  1538. LoadLocalPatternConstantIds(import_function.param_patterns_id);
  1539. auto generic_data = GetLocalGenericData(import_function.generic_id);
  1540. if (HasNewWork()) {
  1541. return Retry(function_const_id);
  1542. }
  1543. // Add the function declaration.
  1544. auto& new_function = context_.functions().Get(function_id);
  1545. new_function.parent_scope_id = parent_scope_id;
  1546. new_function.implicit_param_refs_id =
  1547. GetLocalParamRefsId(import_function.implicit_param_refs_id);
  1548. new_function.implicit_param_patterns_id =
  1549. GetLocalParamPatternsId(import_function.implicit_param_patterns_id);
  1550. new_function.param_refs_id =
  1551. GetLocalParamRefsId(import_function.param_refs_id);
  1552. new_function.param_patterns_id =
  1553. GetLocalParamPatternsId(import_function.param_patterns_id);
  1554. new_function.return_slot_pattern_id =
  1555. GetLocalReturnSlotPatternId(import_function.return_slot_pattern_id);
  1556. SetGenericData(import_function.generic_id, new_function.generic_id,
  1557. generic_data);
  1558. if (import_function.return_slot_id.is_valid()) {
  1559. // Recreate the return slot from scratch.
  1560. // TODO: Once we import function definitions, we'll need to make sure we
  1561. // use the same return storage variable in the declaration and definition.
  1562. new_function.return_slot_id =
  1563. context_.AddInstInNoBlock<SemIR::VarStorage>(
  1564. AddImportIRInst(import_function.return_slot_id),
  1565. {.type_id =
  1566. context_.GetTypeIdForTypeConstant(return_type_const_id),
  1567. .name_id = SemIR::NameId::ReturnSlot});
  1568. }
  1569. if (import_function.definition_id.is_valid()) {
  1570. new_function.definition_id = new_function.first_owning_decl_id;
  1571. }
  1572. return ResolveAsConstant(function_const_id);
  1573. }
  1574. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1575. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1576. auto fn_val_id = GetLocalConstantInstId(
  1577. import_ir_.functions().Get(inst.function_id).first_decl_id());
  1578. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1579. if (HasNewWork()) {
  1580. return Retry();
  1581. }
  1582. auto fn_type_id = context_.insts().Get(fn_val_id).type_id();
  1583. return ResolveAs<SemIR::FunctionType>(
  1584. {.type_id = SemIR::TypeId::TypeType,
  1585. .function_id = context_.types()
  1586. .GetAs<SemIR::FunctionType>(fn_type_id)
  1587. .function_id,
  1588. .specific_id =
  1589. GetOrAddLocalSpecific(inst.specific_id, specific_data)});
  1590. }
  1591. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1592. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1593. auto class_val_id = GetLocalConstantInstId(
  1594. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1595. if (HasNewWork()) {
  1596. return Retry();
  1597. }
  1598. auto class_val = context_.insts().Get(class_val_id);
  1599. CARBON_CHECK(
  1600. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1601. return ResolveAsConstant(
  1602. context_.types().GetConstantId(class_val.type_id()));
  1603. }
  1604. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1605. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1606. auto interface_val_id = GetLocalConstantInstId(
  1607. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1608. if (HasNewWork()) {
  1609. return Retry();
  1610. }
  1611. auto interface_val = context_.insts().Get(interface_val_id);
  1612. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1613. interface_val.type_id()));
  1614. return ResolveAsConstant(
  1615. context_.types().GetConstantId(interface_val.type_id()));
  1616. }
  1617. // Make a declaration of an impl. This is done as a separate step from
  1618. // importing the impl definition in order to resolve cycles.
  1619. auto MakeImplDeclaration(const SemIR::Impl& import_impl)
  1620. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  1621. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::Invalid,
  1622. .decl_block_id = SemIR::InstBlockId::Empty};
  1623. auto impl_decl_id =
  1624. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1625. AddImportIRInst(import_impl.latest_decl_id()), impl_decl));
  1626. impl_decl.impl_id = context_.impls().Add(
  1627. {GetIncompleteLocalEntityBase(impl_decl_id, import_impl),
  1628. {.self_id = SemIR::InstId::Invalid,
  1629. .constraint_id = SemIR::InstId::Invalid,
  1630. .witness_id = SemIR::InstId::Invalid}});
  1631. // Write the impl ID into the ImplDecl.
  1632. context_.ReplaceInstBeforeConstantUse(impl_decl_id, impl_decl);
  1633. return {impl_decl.impl_id, context_.constant_values().Get(impl_decl_id)};
  1634. }
  1635. // Imports the definition of an impl.
  1636. auto AddImplDefinition(const SemIR::Impl& import_impl, SemIR::Impl& new_impl,
  1637. SemIR::InstId witness_id) -> void {
  1638. new_impl.definition_id = new_impl.first_owning_decl_id;
  1639. new_impl.witness_id = witness_id;
  1640. if (import_impl.scope_id.is_valid()) {
  1641. new_impl.scope_id = context_.name_scopes().Add(
  1642. new_impl.first_owning_decl_id, SemIR::NameId::Invalid,
  1643. new_impl.parent_scope_id);
  1644. // Import the contents of the definition scope, if we might need it. Name
  1645. // lookup is never performed into this scope by a user of the impl, so
  1646. // this is only necessary in the same library that defined the impl, in
  1647. // order to support defining members of the impl out of line in the impl
  1648. // file when the impl is defined in the API file.
  1649. // TODO: Check to see if this impl is owned by the API file, rather than
  1650. // merely being imported into it.
  1651. if (import_ir_id_ == SemIR::ImportIRId::ApiForImpl) {
  1652. auto& new_scope = context_.name_scopes().Get(new_impl.scope_id);
  1653. const auto& import_scope =
  1654. import_ir_.name_scopes().Get(import_impl.scope_id);
  1655. // Push a block so that we can add scoped instructions to it.
  1656. context_.inst_block_stack().Push();
  1657. AddNameScopeImportRefs(import_scope, new_scope);
  1658. new_impl.body_block_id = context_.inst_block_stack().Pop();
  1659. }
  1660. }
  1661. }
  1662. auto TryResolveTypedInst(SemIR::ImplDecl inst,
  1663. SemIR::ConstantId impl_const_id) -> ResolveResult {
  1664. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  1665. // functions. Factor out the commonality.
  1666. const auto& import_impl = import_ir_.impls().Get(inst.impl_id);
  1667. SemIR::ImplId impl_id = SemIR::ImplId::Invalid;
  1668. if (!impl_const_id.is_valid()) {
  1669. if (HasNewWork()) {
  1670. // This is the end of the first phase. Don't make a new impl yet if we
  1671. // already have new work.
  1672. return Retry();
  1673. }
  1674. // On the second phase, create a forward declaration of the impl for any
  1675. // recursive references.
  1676. std::tie(impl_id, impl_const_id) = MakeImplDeclaration(import_impl);
  1677. } else {
  1678. // On the third phase, compute the impl ID from the "constant value" of
  1679. // the declaration, which is a reference to the created ImplDecl.
  1680. auto impl_const_inst = context_.insts().GetAs<SemIR::ImplDecl>(
  1681. context_.constant_values().GetInstId(impl_const_id));
  1682. impl_id = impl_const_inst.impl_id;
  1683. }
  1684. // Load constants for the definition.
  1685. auto parent_scope_id = GetLocalNameScopeId(import_impl.parent_scope_id);
  1686. LoadLocalParamConstantIds(import_impl.implicit_param_refs_id);
  1687. LoadLocalPatternConstantIds(import_impl.implicit_param_patterns_id);
  1688. auto generic_data = GetLocalGenericData(import_impl.generic_id);
  1689. auto self_const_id = GetLocalConstantId(
  1690. import_ir_.constant_values().Get(import_impl.self_id));
  1691. auto constraint_const_id = GetLocalConstantId(
  1692. import_ir_.constant_values().Get(import_impl.constraint_id));
  1693. if (HasNewWork()) {
  1694. return Retry(impl_const_id);
  1695. }
  1696. auto& new_impl = context_.impls().Get(impl_id);
  1697. new_impl.parent_scope_id = parent_scope_id;
  1698. new_impl.implicit_param_refs_id =
  1699. GetLocalParamRefsId(import_impl.implicit_param_refs_id);
  1700. new_impl.implicit_param_patterns_id =
  1701. GetLocalParamPatternsId(import_impl.implicit_param_patterns_id);
  1702. CARBON_CHECK(!import_impl.param_refs_id.is_valid() &&
  1703. !new_impl.param_refs_id.is_valid());
  1704. SetGenericData(import_impl.generic_id, new_impl.generic_id, generic_data);
  1705. // Create instructions for self and constraint to hold the symbolic constant
  1706. // value for a generic impl.
  1707. new_impl.self_id = AddLoadedImportRef(
  1708. context_, {.ir_id = import_ir_id_, .inst_id = import_impl.self_id},
  1709. SemIR::TypeId::TypeType, self_const_id);
  1710. new_impl.constraint_id = AddLoadedImportRef(
  1711. context_,
  1712. {.ir_id = import_ir_id_, .inst_id = import_impl.constraint_id},
  1713. SemIR::TypeId::TypeType, constraint_const_id);
  1714. if (import_impl.is_defined()) {
  1715. auto witness_id = AddImportRef(
  1716. context_,
  1717. {.ir_id = import_ir_id_, .inst_id = import_impl.witness_id});
  1718. AddImplDefinition(import_impl, new_impl, witness_id);
  1719. }
  1720. // If the `impl` is declared in the API file corresponding to the current
  1721. // file, add this to impl lookup so that it can be found by redeclarations
  1722. // in the current file.
  1723. if (import_ir_id_ == SemIR::ImportIRId::ApiForImpl) {
  1724. context_.impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  1725. }
  1726. return ResolveAsConstant(impl_const_id);
  1727. }
  1728. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1729. SemIR::InstId inst_id) -> ResolveResult {
  1730. // Return the constant for the instruction of the imported constant.
  1731. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1732. if (!constant_id.is_valid()) {
  1733. return ResolveAsConstant(SemIR::ConstantId::Error);
  1734. }
  1735. if (!constant_id.is_constant()) {
  1736. context_.TODO(inst_id,
  1737. "Non-constant ImportRefLoaded (comes up with var)");
  1738. return ResolveAsConstant(SemIR::ConstantId::Error);
  1739. }
  1740. auto new_constant_id =
  1741. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1742. return RetryOrResolveAsConstant(new_constant_id);
  1743. }
  1744. // Make a declaration of an interface. This is done as a separate step from
  1745. // importing the interface definition in order to resolve cycles.
  1746. auto MakeInterfaceDecl(const SemIR::Interface& import_interface,
  1747. SemIR::SpecificId enclosing_specific_id)
  1748. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1749. SemIR::InterfaceDecl interface_decl = {
  1750. .type_id = SemIR::TypeId::TypeType,
  1751. .interface_id = SemIR::InterfaceId::Invalid,
  1752. .decl_block_id = SemIR::InstBlockId::Empty};
  1753. auto interface_decl_id =
  1754. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1755. AddImportIRInst(import_interface.first_owning_decl_id),
  1756. interface_decl));
  1757. // Start with an incomplete interface.
  1758. interface_decl.interface_id = context_.interfaces().Add(
  1759. {GetIncompleteLocalEntityBase(interface_decl_id, import_interface),
  1760. {}});
  1761. if (import_interface.has_parameters()) {
  1762. interface_decl.type_id = context_.GetGenericInterfaceType(
  1763. interface_decl.interface_id, enclosing_specific_id);
  1764. }
  1765. // Write the interface ID into the InterfaceDecl.
  1766. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1767. return {interface_decl.interface_id,
  1768. context_.constant_values().Get(interface_decl_id)};
  1769. }
  1770. // Imports the definition for an interface that has been imported as a forward
  1771. // declaration.
  1772. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1773. SemIR::Interface& new_interface,
  1774. SemIR::InstId self_param_id) -> void {
  1775. new_interface.scope_id = context_.name_scopes().Add(
  1776. new_interface.first_owning_decl_id, SemIR::NameId::Invalid,
  1777. new_interface.parent_scope_id);
  1778. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1779. const auto& import_scope =
  1780. import_ir_.name_scopes().Get(import_interface.scope_id);
  1781. // Push a block so that we can add scoped instructions to it.
  1782. context_.inst_block_stack().Push();
  1783. AddNameScopeImportRefs(import_scope, new_scope);
  1784. new_interface.associated_entities_id =
  1785. AddAssociatedEntities(import_interface.associated_entities_id);
  1786. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1787. new_interface.self_param_id = self_param_id;
  1788. CARBON_CHECK(import_scope.extended_scopes.empty(),
  1789. "Interfaces don't currently have extended scopes to support.");
  1790. }
  1791. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1792. SemIR::ConstantId interface_const_id)
  1793. -> ResolveResult {
  1794. const auto& import_interface =
  1795. import_ir_.interfaces().Get(inst.interface_id);
  1796. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1797. if (!interface_const_id.is_valid()) {
  1798. auto import_specific_id = SemIR::SpecificId::Invalid;
  1799. if (auto import_generic_interface_type =
  1800. import_ir_.types().TryGetAs<SemIR::GenericInterfaceType>(
  1801. inst.type_id)) {
  1802. import_specific_id =
  1803. import_generic_interface_type->enclosing_specific_id;
  1804. }
  1805. auto specific_data = GetLocalSpecificData(import_specific_id);
  1806. if (HasNewWork()) {
  1807. // This is the end of the first phase. Don't make a new interface yet if
  1808. // we already have new work.
  1809. return Retry();
  1810. }
  1811. // On the second phase, create a forward declaration of the interface.
  1812. auto enclosing_specific_id =
  1813. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1814. std::tie(interface_id, interface_const_id) =
  1815. MakeInterfaceDecl(import_interface, enclosing_specific_id);
  1816. } else {
  1817. // On the third phase, compute the interface ID from the constant value of
  1818. // the declaration.
  1819. auto interface_const_inst = context_.insts().Get(
  1820. context_.constant_values().GetInstId(interface_const_id));
  1821. if (auto interface_type =
  1822. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1823. interface_id = interface_type->interface_id;
  1824. } else {
  1825. auto generic_interface_type =
  1826. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1827. interface_const_inst.type_id());
  1828. interface_id = generic_interface_type.interface_id;
  1829. }
  1830. }
  1831. auto parent_scope_id =
  1832. GetLocalNameScopeId(import_interface.parent_scope_id);
  1833. LoadLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1834. LoadLocalPatternConstantIds(import_interface.implicit_param_patterns_id);
  1835. LoadLocalParamConstantIds(import_interface.param_refs_id);
  1836. LoadLocalPatternConstantIds(import_interface.param_patterns_id);
  1837. auto generic_data = GetLocalGenericData(import_interface.generic_id);
  1838. std::optional<SemIR::InstId> self_param_id;
  1839. if (import_interface.is_defined()) {
  1840. self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1841. }
  1842. if (HasNewWork()) {
  1843. return Retry(interface_const_id);
  1844. }
  1845. auto& new_interface = context_.interfaces().Get(interface_id);
  1846. new_interface.parent_scope_id = parent_scope_id;
  1847. new_interface.implicit_param_refs_id =
  1848. GetLocalParamRefsId(import_interface.implicit_param_refs_id);
  1849. new_interface.implicit_param_patterns_id =
  1850. GetLocalParamPatternsId(import_interface.implicit_param_patterns_id);
  1851. new_interface.param_refs_id =
  1852. GetLocalParamRefsId(import_interface.param_refs_id);
  1853. new_interface.param_patterns_id =
  1854. GetLocalParamPatternsId(import_interface.param_patterns_id);
  1855. SetGenericData(import_interface.generic_id, new_interface.generic_id,
  1856. generic_data);
  1857. if (import_interface.is_defined()) {
  1858. CARBON_CHECK(self_param_id);
  1859. AddInterfaceDefinition(import_interface, new_interface, *self_param_id);
  1860. }
  1861. return ResolveAsConstant(interface_const_id);
  1862. }
  1863. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1864. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1865. auto interface_const_id = GetLocalConstantId(
  1866. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1867. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1868. if (HasNewWork()) {
  1869. return Retry();
  1870. }
  1871. // Find the corresponding interface type. For a non-generic interface, this
  1872. // is the type of the interface declaration. For a generic interface, build
  1873. // a interface type referencing this specialization of the generic
  1874. // interface.
  1875. auto interface_const_inst = context_.insts().Get(
  1876. context_.constant_values().GetInstId(interface_const_id));
  1877. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1878. return ResolveAsConstant(interface_const_id);
  1879. } else {
  1880. auto generic_interface_type =
  1881. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1882. interface_const_inst.type_id());
  1883. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1884. return ResolveAs<SemIR::InterfaceType>(
  1885. {.type_id = SemIR::TypeId::TypeType,
  1886. .interface_id = generic_interface_type.interface_id,
  1887. .specific_id = specific_id});
  1888. }
  1889. }
  1890. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1891. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1892. if (HasNewWork()) {
  1893. return Retry();
  1894. }
  1895. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1896. return ResolveAs<SemIR::InterfaceWitness>(
  1897. {.type_id =
  1898. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1899. .elements_id = elements_id});
  1900. }
  1901. auto TryResolveTypedInst(SemIR::IntValue inst) -> ResolveResult {
  1902. auto type_id = GetLocalConstantId(inst.type_id);
  1903. if (HasNewWork()) {
  1904. return Retry();
  1905. }
  1906. return ResolveAs<SemIR::IntValue>(
  1907. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1908. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1909. }
  1910. auto TryResolveTypedInst(SemIR::IntType inst) -> ResolveResult {
  1911. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1912. auto bit_width_id = GetLocalConstantInstId(inst.bit_width_id);
  1913. if (HasNewWork()) {
  1914. return Retry();
  1915. }
  1916. return ResolveAs<SemIR::IntType>({.type_id = SemIR::TypeId::TypeType,
  1917. .int_kind = inst.int_kind,
  1918. .bit_width_id = bit_width_id});
  1919. }
  1920. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1921. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1922. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1923. if (HasNewWork()) {
  1924. return Retry();
  1925. }
  1926. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1927. return ResolveAs<SemIR::PointerType>(
  1928. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1929. }
  1930. auto TryResolveTypedInst(SemIR::SpecificFunction inst) -> ResolveResult {
  1931. auto type_const_id = GetLocalConstantId(inst.type_id);
  1932. auto callee_id = GetLocalConstantInstId(inst.callee_id);
  1933. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1934. if (HasNewWork()) {
  1935. return Retry();
  1936. }
  1937. auto type_id = context_.GetTypeIdForTypeConstant(type_const_id);
  1938. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1939. return ResolveAs<SemIR::SpecificFunction>({.type_id = type_id,
  1940. .callee_id = callee_id,
  1941. .specific_id = specific_id});
  1942. }
  1943. auto TryResolveTypedInst(SemIR::StructType inst) -> ResolveResult {
  1944. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1945. auto orig_fields = import_ir_.struct_type_fields().Get(inst.fields_id);
  1946. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1947. field_const_ids.reserve(orig_fields.size());
  1948. for (auto field : orig_fields) {
  1949. field_const_ids.push_back(GetLocalConstantId(field.type_id));
  1950. }
  1951. if (HasNewWork()) {
  1952. return Retry();
  1953. }
  1954. // Prepare a vector of fields for GetStructType.
  1955. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  1956. new_fields.reserve(orig_fields.size());
  1957. for (auto [orig_field, field_const_id] :
  1958. llvm::zip(orig_fields, field_const_ids)) {
  1959. auto name_id = GetLocalNameId(orig_field.name_id);
  1960. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1961. new_fields.push_back({.name_id = name_id, .type_id = field_type_id});
  1962. }
  1963. return ResolveAs<SemIR::StructType>(
  1964. {.type_id = SemIR::TypeId::TypeType,
  1965. .fields_id = context_.struct_type_fields().AddCanonical(new_fields)});
  1966. }
  1967. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1968. auto type_id = GetLocalConstantId(inst.type_id);
  1969. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1970. if (HasNewWork()) {
  1971. return Retry();
  1972. }
  1973. return ResolveAs<SemIR::StructValue>(
  1974. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1975. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1976. }
  1977. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1978. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1979. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1980. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1981. elem_const_ids.reserve(orig_elem_type_ids.size());
  1982. for (auto elem_type_id : orig_elem_type_ids) {
  1983. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1984. }
  1985. if (HasNewWork()) {
  1986. return Retry();
  1987. }
  1988. // Prepare a vector of the tuple types for GetTupleType.
  1989. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1990. elem_type_ids.reserve(orig_elem_type_ids.size());
  1991. for (auto elem_const_id : elem_const_ids) {
  1992. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1993. }
  1994. return ResolveAsConstant(
  1995. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids)));
  1996. }
  1997. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1998. auto type_id = GetLocalConstantId(inst.type_id);
  1999. auto elems = GetLocalInstBlockContents(inst.elements_id);
  2000. if (HasNewWork()) {
  2001. return Retry();
  2002. }
  2003. return ResolveAs<SemIR::TupleValue>(
  2004. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  2005. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  2006. }
  2007. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  2008. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  2009. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  2010. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  2011. if (HasNewWork()) {
  2012. return Retry();
  2013. }
  2014. return ResolveAs<SemIR::UnboundElementType>(
  2015. {.type_id = SemIR::TypeId::TypeType,
  2016. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  2017. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  2018. }
  2019. // Perform any work that we deferred until the end of the main Resolve loop.
  2020. auto PerformPendingWork() -> void {
  2021. // Note that the individual Finish steps can add new pending work, so keep
  2022. // going until we have no more work to do.
  2023. while (!pending_generics_.empty() || !pending_specifics_.empty()) {
  2024. // Process generics in the order that we added them because a later
  2025. // generic might refer to an earlier one, and the calls to
  2026. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  2027. // state.
  2028. // TODO: Import the generic eval block rather than calling
  2029. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  2030. // NOLINTNEXTLINE(modernize-loop-convert)
  2031. for (size_t i = 0; i != pending_generics_.size(); ++i) {
  2032. FinishPendingGeneric(pending_generics_[i]);
  2033. }
  2034. pending_generics_.clear();
  2035. while (!pending_specifics_.empty()) {
  2036. FinishPendingSpecific(pending_specifics_.pop_back_val());
  2037. }
  2038. }
  2039. }
  2040. // Resolves and returns the local contents for an imported instruction block
  2041. // of constant instructions.
  2042. auto ResolveLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  2043. -> llvm::SmallVector<SemIR::InstId> {
  2044. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  2045. llvm::SmallVector<SemIR::InstId> inst_ids;
  2046. inst_ids.reserve(import_block.size());
  2047. for (auto import_inst_id : import_block) {
  2048. inst_ids.push_back(
  2049. context_.constant_values().GetInstId(ResolveOneInst(import_inst_id)));
  2050. }
  2051. return inst_ids;
  2052. }
  2053. // Resolves and returns a local eval block for a region of an imported
  2054. // generic.
  2055. auto ResolveLocalEvalBlock(const SemIR::Generic& import_generic,
  2056. SemIR::GenericId generic_id,
  2057. SemIR::GenericInstIndex::Region region)
  2058. -> SemIR::InstBlockId {
  2059. auto import_block_id = import_generic.GetEvalBlock(region);
  2060. if (!import_block_id.is_valid()) {
  2061. return SemIR::InstBlockId::Invalid;
  2062. }
  2063. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  2064. return RebuildGenericEvalBlock(context_, generic_id, region, inst_ids);
  2065. }
  2066. // Fills in the remaining information in a partially-imported generic.
  2067. auto FinishPendingGeneric(PendingGeneric pending) -> void {
  2068. const auto& import_generic = import_ir_.generics().Get(pending.import_id);
  2069. // Don't store the local generic between calls: the generics list can be
  2070. // reallocated by ResolveLocalEvalBlock importing more specifics.
  2071. auto decl_block_id =
  2072. ResolveLocalEvalBlock(import_generic, pending.local_id,
  2073. SemIR::GenericInstIndex::Region::Declaration);
  2074. context_.generics().Get(pending.local_id).decl_block_id = decl_block_id;
  2075. auto self_specific_id = MakeSelfSpecific(context_, pending.local_id);
  2076. context_.generics().Get(pending.local_id).self_specific_id =
  2077. self_specific_id;
  2078. pending_specifics_.push_back({.import_id = import_generic.self_specific_id,
  2079. .local_id = self_specific_id});
  2080. auto definition_block_id =
  2081. ResolveLocalEvalBlock(import_generic, pending.local_id,
  2082. SemIR::GenericInstIndex::Region::Definition);
  2083. context_.generics().Get(pending.local_id).definition_block_id =
  2084. definition_block_id;
  2085. }
  2086. // Resolves and returns a local inst block of constant instructions
  2087. // corresponding to an imported inst block.
  2088. auto ResolveLocalInstBlock(SemIR::InstBlockId import_block_id)
  2089. -> SemIR::InstBlockId {
  2090. if (!import_block_id.is_valid()) {
  2091. return SemIR::InstBlockId::Invalid;
  2092. }
  2093. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  2094. return context_.inst_blocks().Add(inst_ids);
  2095. }
  2096. // Fills in the remaining information in a partially-imported specific.
  2097. auto FinishPendingSpecific(PendingSpecific pending) -> void {
  2098. const auto& import_specific = import_ir_.specifics().Get(pending.import_id);
  2099. // Don't store the local specific between calls: the specifics list can be
  2100. // reallocated by ResolveLocalInstBlock importing more specifics.
  2101. if (!context_.specifics().Get(pending.local_id).decl_block_id.is_valid()) {
  2102. auto decl_block_id = ResolveLocalInstBlock(import_specific.decl_block_id);
  2103. context_.specifics().Get(pending.local_id).decl_block_id = decl_block_id;
  2104. }
  2105. if (!context_.specifics()
  2106. .Get(pending.local_id)
  2107. .definition_block_id.is_valid() &&
  2108. import_specific.definition_block_id.is_valid()) {
  2109. auto definition_block_id =
  2110. ResolveLocalInstBlock(import_specific.definition_block_id);
  2111. context_.specifics().Get(pending.local_id).definition_block_id =
  2112. definition_block_id;
  2113. }
  2114. }
  2115. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  2116. return context_.import_ir_constant_values()[import_ir_id_.index];
  2117. }
  2118. Context& context_;
  2119. SemIR::ImportIRId import_ir_id_;
  2120. const SemIR::File& import_ir_;
  2121. llvm::SmallVector<Work> work_stack_;
  2122. // The size of work_stack_ at the start of resolving the current instruction.
  2123. size_t initial_work_ = 0;
  2124. // Generics that we have partially imported but not yet finished importing.
  2125. llvm::SmallVector<PendingGeneric> pending_generics_;
  2126. // Specifics that we have partially imported but not yet finished importing.
  2127. llvm::SmallVector<PendingSpecific> pending_specifics_;
  2128. };
  2129. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  2130. // loaded (including the one pointed at directly by the ImportRef), and the
  2131. // final instruction's type ID.
  2132. //
  2133. // This addresses cases where an ImportRefUnloaded may point at another
  2134. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  2135. // constant-evaluated version of the instruction to work with.
  2136. static auto GetInstForLoad(Context& context,
  2137. SemIR::ImportIRInstId import_ir_inst_id)
  2138. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  2139. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  2140. {}, SemIR::TypeId::Invalid};
  2141. auto& [import_ir_insts, type_id] = result;
  2142. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  2143. // The first ImportIRInst is added directly because the IR doesn't need to be
  2144. // localized.
  2145. import_ir_insts.push_back(import_ir_inst);
  2146. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2147. while (true) {
  2148. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  2149. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  2150. if (!import_ref) {
  2151. type_id = cursor_inst.type_id();
  2152. return result;
  2153. }
  2154. import_ir_inst =
  2155. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  2156. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2157. import_ir_insts.push_back(
  2158. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  2159. .is_export = false,
  2160. .sem_ir = cursor_ir}),
  2161. .inst_id = import_ir_inst.inst_id});
  2162. }
  2163. }
  2164. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  2165. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  2166. if (!inst) {
  2167. return;
  2168. }
  2169. auto [indirect_insts, load_type_id] =
  2170. GetInstForLoad(context, inst->import_ir_inst_id);
  2171. // The last indirect instruction is the one to resolve. Pop it here because
  2172. // Resolve will assign the constant.
  2173. auto load_ir_inst = indirect_insts.pop_back_val();
  2174. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  2175. // The resolver calls into Context to create instructions. Don't register
  2176. // those instructions as part of the enclosing generic scope if they're
  2177. // dependent on a generic parameter.
  2178. context.generic_region_stack().Push();
  2179. auto type_id = resolver.ResolveType(load_type_id);
  2180. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  2181. context.generic_region_stack().Pop();
  2182. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  2183. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  2184. // TryEvalInst, which we want to avoid with ImportRefs.
  2185. context.sem_ir().insts().Set(
  2186. inst_id,
  2187. SemIR::ImportRefLoaded{.type_id = type_id,
  2188. .import_ir_inst_id = inst->import_ir_inst_id,
  2189. .entity_name_id = inst->entity_name_id});
  2190. // Store the constant for both the ImportRefLoaded and indirect instructions.
  2191. context.constant_values().Set(inst_id, constant_id);
  2192. for (const auto& import_ir_inst : indirect_insts) {
  2193. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  2194. import_ir_inst.inst_id, constant_id);
  2195. }
  2196. }
  2197. auto ImportImplsFromApiFile(Context& context) -> void {
  2198. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  2199. auto& import_ir = context.import_irs().Get(import_ir_id);
  2200. if (!import_ir.sem_ir) {
  2201. return;
  2202. }
  2203. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  2204. SemIR::ImplId impl_id(impl_index);
  2205. // Resolve the imported impl to a local impl ID.
  2206. ImportImpl(context, import_ir_id, impl_id);
  2207. }
  2208. }
  2209. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  2210. SemIR::ImplId impl_id) -> void {
  2211. ImportRefResolver resolver(context, import_ir_id);
  2212. context.generic_region_stack().Push();
  2213. resolver.Resolve(context.import_irs()
  2214. .Get(import_ir_id)
  2215. .sem_ir->impls()
  2216. .Get(impl_id)
  2217. .first_decl_id());
  2218. context.generic_region_stack().Pop();
  2219. }
  2220. } // namespace Carbon::Check