context.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  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/context.h"
  5. #include <string>
  6. #include <utility>
  7. #include "common/check.h"
  8. #include "common/vlog.h"
  9. #include "llvm/ADT/Sequence.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/decl_name_stack.h"
  12. #include "toolchain/check/eval.h"
  13. #include "toolchain/check/generic_region_stack.h"
  14. #include "toolchain/check/import_ref.h"
  15. #include "toolchain/check/inst_block_stack.h"
  16. #include "toolchain/check/merge.h"
  17. #include "toolchain/diagnostics/diagnostic_emitter.h"
  18. #include "toolchain/lex/tokenized_buffer.h"
  19. #include "toolchain/parse/node_ids.h"
  20. #include "toolchain/parse/node_kind.h"
  21. #include "toolchain/sem_ir/builtin_kind.h"
  22. #include "toolchain/sem_ir/file.h"
  23. #include "toolchain/sem_ir/ids.h"
  24. #include "toolchain/sem_ir/import_ir.h"
  25. #include "toolchain/sem_ir/inst.h"
  26. #include "toolchain/sem_ir/inst_kind.h"
  27. #include "toolchain/sem_ir/name_scope.h"
  28. #include "toolchain/sem_ir/typed_insts.h"
  29. namespace Carbon::Check {
  30. Context::Context(const Lex::TokenizedBuffer& tokens, DiagnosticEmitter& emitter,
  31. const Parse::Tree& parse_tree, SemIR::File& sem_ir,
  32. llvm::raw_ostream* vlog_stream)
  33. : tokens_(&tokens),
  34. emitter_(&emitter),
  35. parse_tree_(&parse_tree),
  36. sem_ir_(&sem_ir),
  37. vlog_stream_(vlog_stream),
  38. node_stack_(parse_tree, vlog_stream),
  39. inst_block_stack_("inst_block_stack_", sem_ir, vlog_stream),
  40. param_and_arg_refs_stack_(sem_ir, vlog_stream, node_stack_),
  41. args_type_info_stack_("args_type_info_stack_", sem_ir, vlog_stream),
  42. decl_name_stack_(this),
  43. scope_stack_(sem_ir_->identifiers()),
  44. global_init_(this) {
  45. // Map the builtin `<error>` and `type` type constants to their corresponding
  46. // special `TypeId` values.
  47. type_ids_for_type_constants_.Insert(
  48. SemIR::ConstantId::ForTemplateConstant(SemIR::InstId::BuiltinError),
  49. SemIR::TypeId::Error);
  50. type_ids_for_type_constants_.Insert(
  51. SemIR::ConstantId::ForTemplateConstant(SemIR::InstId::BuiltinTypeType),
  52. SemIR::TypeId::TypeType);
  53. // TODO: Remove this and add a `VerifyOnFinish` once we properly push and pop
  54. // in the right places.
  55. generic_region_stack().Push();
  56. }
  57. auto Context::TODO(SemIRLoc loc, std::string label) -> bool {
  58. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.",
  59. std::string);
  60. emitter_->Emit(loc, SemanticsTodo, std::move(label));
  61. return false;
  62. }
  63. auto Context::VerifyOnFinish() -> void {
  64. // Information in all the various context objects should be cleaned up as
  65. // various pieces of context go out of scope. At this point, nothing should
  66. // remain.
  67. // node_stack_ will still contain top-level entities.
  68. scope_stack_.VerifyOnFinish();
  69. inst_block_stack_.VerifyOnFinish();
  70. param_and_arg_refs_stack_.VerifyOnFinish();
  71. }
  72. // Finish producing an instruction. Set its constant value, and register it in
  73. // any applicable instruction lists.
  74. auto Context::FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void {
  75. GenericRegionStack::DependencyKind dep_kind =
  76. GenericRegionStack::DependencyKind::None;
  77. // If the instruction has a symbolic constant type, track that we need to
  78. // substitute into it.
  79. if (types().GetConstantId(inst.type_id()).is_symbolic()) {
  80. dep_kind |= GenericRegionStack::DependencyKind::SymbolicType;
  81. }
  82. // If the instruction has a constant value, compute it.
  83. auto const_id = TryEvalInst(*this, inst_id, inst);
  84. constant_values().Set(inst_id, const_id);
  85. if (const_id.is_constant()) {
  86. CARBON_VLOG() << "Constant: " << inst << " -> "
  87. << constant_values().GetInstId(const_id) << "\n";
  88. // If the constant value is symbolic, track that we need to substitute into
  89. // it.
  90. if (const_id.is_symbolic()) {
  91. dep_kind |= GenericRegionStack::DependencyKind::SymbolicConstant;
  92. }
  93. }
  94. // Keep track of dependent instructions.
  95. if (dep_kind != GenericRegionStack::DependencyKind::None) {
  96. // TODO: Also check for template-dependent instructions.
  97. generic_region_stack().AddDependentInst(
  98. {.inst_id = inst_id, .kind = dep_kind});
  99. }
  100. }
  101. auto Context::AddInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  102. -> SemIR::InstId {
  103. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  104. CARBON_VLOG() << "AddInst: " << loc_id_and_inst.inst << "\n";
  105. FinishInst(inst_id, loc_id_and_inst.inst);
  106. return inst_id;
  107. }
  108. auto Context::AddInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId {
  109. auto inst_id = AddInstInNoBlock(loc_id_and_inst);
  110. inst_block_stack_.AddInstId(inst_id);
  111. return inst_id;
  112. }
  113. auto Context::AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  114. -> SemIR::InstId {
  115. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  116. CARBON_VLOG() << "AddPlaceholderInst: " << loc_id_and_inst.inst << "\n";
  117. constant_values().Set(inst_id, SemIR::ConstantId::Invalid);
  118. return inst_id;
  119. }
  120. auto Context::AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst)
  121. -> SemIR::InstId {
  122. auto inst_id = AddPlaceholderInstInNoBlock(loc_id_and_inst);
  123. inst_block_stack_.AddInstId(inst_id);
  124. return inst_id;
  125. }
  126. auto Context::AddConstant(SemIR::Inst inst, bool is_symbolic)
  127. -> SemIR::ConstantId {
  128. auto const_id = constants().GetOrAdd(inst, is_symbolic);
  129. CARBON_VLOG() << "AddConstant: " << inst << "\n";
  130. return const_id;
  131. }
  132. auto Context::ReplaceLocIdAndInstBeforeConstantUse(
  133. SemIR::InstId inst_id, SemIR::LocIdAndInst loc_id_and_inst) -> void {
  134. sem_ir().insts().SetLocIdAndInst(inst_id, loc_id_and_inst);
  135. CARBON_VLOG() << "ReplaceInst: " << inst_id << " -> " << loc_id_and_inst.inst
  136. << "\n";
  137. FinishInst(inst_id, loc_id_and_inst.inst);
  138. }
  139. auto Context::ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
  140. SemIR::Inst inst) -> void {
  141. sem_ir().insts().Set(inst_id, inst);
  142. CARBON_VLOG() << "ReplaceInst: " << inst_id << " -> " << inst << "\n";
  143. FinishInst(inst_id, inst);
  144. }
  145. auto Context::DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def)
  146. -> void {
  147. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  148. "Duplicate name being declared in the same scope.");
  149. CARBON_DIAGNOSTIC(NameDeclPrevious, Note,
  150. "Name is previously declared here.");
  151. emitter_->Build(dup_def, NameDeclDuplicate)
  152. .Note(prev_def, NameDeclPrevious)
  153. .Emit();
  154. }
  155. auto Context::DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id)
  156. -> void {
  157. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.",
  158. SemIR::NameId);
  159. emitter_->Emit(loc, NameNotFound, name_id);
  160. }
  161. auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
  162. DiagnosticBuilder& builder) -> void {
  163. const auto& class_info = classes().Get(class_id);
  164. CARBON_CHECK(!class_info.is_defined()) << "Class is not incomplete";
  165. if (class_info.definition_id.is_valid()) {
  166. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  167. "Class is incomplete within its definition.");
  168. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  169. } else {
  170. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  171. "Class was forward declared here.");
  172. builder.Note(class_info.decl_id, ClassForwardDeclaredHere);
  173. }
  174. }
  175. auto Context::NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  176. DiagnosticBuilder& builder) -> void {
  177. const auto& interface_info = interfaces().Get(interface_id);
  178. CARBON_CHECK(!interface_info.is_defined()) << "Interface is not incomplete";
  179. if (interface_info.is_being_defined()) {
  180. CARBON_DIAGNOSTIC(InterfaceUndefinedWithinDefinition, Note,
  181. "Interface is currently being defined.");
  182. builder.Note(interface_info.definition_id,
  183. InterfaceUndefinedWithinDefinition);
  184. } else {
  185. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  186. "Interface was forward declared here.");
  187. builder.Note(interface_info.decl_id, InterfaceForwardDeclaredHere);
  188. }
  189. }
  190. auto Context::AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id)
  191. -> void {
  192. if (auto existing = scope_stack().LookupOrAddName(name_id, target_id);
  193. existing.is_valid()) {
  194. DiagnoseDuplicateName(target_id, existing);
  195. }
  196. }
  197. auto Context::LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  198. SemIR::NameScopeId scope_id) -> SemIR::InstId {
  199. if (!scope_id.is_valid()) {
  200. // Look for a name in the current scope only. There are two cases where the
  201. // name would be in an outer scope:
  202. //
  203. // - The name is the sole component of the declared name:
  204. //
  205. // class A;
  206. // fn F() {
  207. // class A;
  208. // }
  209. //
  210. // In this case, the inner A is not the same class as the outer A, so
  211. // lookup should not find the outer A.
  212. //
  213. // - The name is a qualifier of some larger declared name:
  214. //
  215. // class A { class B; }
  216. // fn F() {
  217. // class A.B {}
  218. // }
  219. //
  220. // In this case, we're not in the correct scope to define a member of
  221. // class A, so we should reject, and we achieve this by not finding the
  222. // name A from the outer scope.
  223. return scope_stack().LookupInCurrentScope(name_id);
  224. } else {
  225. // We do not look into `extend`ed scopes here. A qualified name in a
  226. // declaration must specify the exact scope in which the name was originally
  227. // introduced:
  228. //
  229. // base class A { fn F(); }
  230. // class B { extend base: A; }
  231. //
  232. // // Error, no `F` in `B`.
  233. // fn B.F() {}
  234. return LookupNameInExactScope(loc_id, name_id, scope_id,
  235. name_scopes().Get(scope_id));
  236. }
  237. }
  238. auto Context::LookupUnqualifiedName(Parse::NodeId node_id,
  239. SemIR::NameId name_id) -> LookupResult {
  240. // TODO: Check for shadowed lookup results.
  241. // Find the results from ancestor lexical scopes. These will be combined with
  242. // results from non-lexical scopes such as namespaces and classes.
  243. auto [lexical_result, non_lexical_scopes] =
  244. scope_stack().LookupInLexicalScopes(name_id);
  245. // Walk the non-lexical scopes and perform lookups into each of them.
  246. for (auto [index, lookup_scope_id] : llvm::reverse(non_lexical_scopes)) {
  247. // Enclosing non-lexical scopes cannot correspond to an instance of a
  248. // generic, so it's always OK to pass an invalid generic instance here.
  249. // Note that the lookup result might still be found in an extended scope, so
  250. // it can be in a generic instance.
  251. if (auto non_lexical_result = LookupQualifiedName(
  252. node_id, name_id,
  253. {.name_scope_id = lookup_scope_id,
  254. .instance_id = SemIR::GenericInstanceId::Invalid},
  255. /*required=*/false);
  256. non_lexical_result.inst_id.is_valid()) {
  257. return non_lexical_result;
  258. }
  259. }
  260. if (lexical_result.is_valid()) {
  261. // A lexical scope never needs an associated generic instance. If there's a
  262. // lexically enclosing generic, then it also encloses the point of use of
  263. // the name.
  264. return {.instance_id = SemIR::GenericInstanceId::Invalid,
  265. .inst_id = lexical_result};
  266. }
  267. // We didn't find anything at all.
  268. DiagnoseNameNotFound(node_id, name_id);
  269. return {.instance_id = SemIR::GenericInstanceId::Invalid,
  270. .inst_id = SemIR::InstId::BuiltinError};
  271. }
  272. // Handles lookup through the import_ir_scopes for LookupNameInExactScope.
  273. static auto LookupInImportIRScopes(Context& context, SemIRLoc loc,
  274. SemIR::NameId name_id,
  275. SemIR::NameScopeId scope_id,
  276. const SemIR::NameScope& scope)
  277. -> SemIR::InstId {
  278. auto identifier_id = name_id.AsIdentifierId();
  279. llvm::StringRef identifier;
  280. if (identifier_id.is_valid()) {
  281. identifier = context.identifiers().Get(identifier_id);
  282. }
  283. DiagnosticAnnotationScope annotate_diagnostics(
  284. &context.emitter(), [&](auto& builder) {
  285. CARBON_DIAGNOSTIC(InNameLookup, Note, "In name lookup for `{0}`.",
  286. SemIR::NameId);
  287. builder.Note(loc, InNameLookup, name_id);
  288. });
  289. auto result_id = SemIR::InstId::Invalid;
  290. std::optional<SemIR::ImportIRInst> canonical_result_inst;
  291. for (auto [import_ir_id, import_scope_id] : scope.import_ir_scopes) {
  292. auto& import_ir = context.import_irs().Get(import_ir_id);
  293. // Determine the NameId in the import IR.
  294. SemIR::NameId import_name_id = name_id;
  295. if (identifier_id.is_valid()) {
  296. auto import_identifier_id =
  297. import_ir.sem_ir->identifiers().Lookup(identifier);
  298. if (!import_identifier_id.is_valid()) {
  299. // Name doesn't exist in the import IR.
  300. continue;
  301. }
  302. import_name_id = SemIR::NameId::ForIdentifier(import_identifier_id);
  303. }
  304. // Look up the name in the import scope.
  305. const auto& import_scope =
  306. import_ir.sem_ir->name_scopes().Get(import_scope_id);
  307. auto lookup = import_scope.name_map.Lookup(import_name_id);
  308. if (!lookup) {
  309. // Name doesn't exist in the import scope.
  310. continue;
  311. }
  312. const auto& import_scope_entry = import_scope.names[lookup.value()];
  313. auto import_inst =
  314. import_ir.sem_ir->insts().Get(import_scope_entry.inst_id);
  315. if (import_inst.Is<SemIR::AnyImportRef>()) {
  316. // This entity was added to name lookup by using an import, and is not
  317. // exported.
  318. continue;
  319. }
  320. if (import_scope_entry.access_kind != SemIR::AccessKind::Public) {
  321. // Ignore cross-package non-public names.
  322. continue;
  323. }
  324. if (result_id.is_valid()) {
  325. // On a conflict, we verify the canonical instruction is the same.
  326. if (!canonical_result_inst) {
  327. canonical_result_inst =
  328. GetCanonicalImportIRInst(context, &context.sem_ir(), result_id);
  329. }
  330. VerifySameCanonicalImportIRInst(
  331. context, result_id, *canonical_result_inst, import_ir_id,
  332. import_ir.sem_ir, import_scope_entry.inst_id);
  333. } else {
  334. // Add the first result found.
  335. auto bind_name_id = context.bind_names().Add(
  336. {.name_id = name_id,
  337. .parent_scope_id = scope_id,
  338. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  339. result_id = AddImportRef(
  340. context,
  341. {.ir_id = import_ir_id, .inst_id = import_scope_entry.inst_id},
  342. bind_name_id);
  343. LoadImportRef(context, result_id);
  344. }
  345. }
  346. return result_id;
  347. }
  348. auto Context::LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  349. SemIR::NameScopeId scope_id,
  350. const SemIR::NameScope& scope)
  351. -> SemIR::InstId {
  352. if (auto lookup = scope.name_map.Lookup(name_id)) {
  353. auto inst_id = scope.names[lookup.value()].inst_id;
  354. LoadImportRef(*this, inst_id);
  355. return inst_id;
  356. }
  357. if (!scope.import_ir_scopes.empty()) {
  358. return LookupInImportIRScopes(*this, loc, name_id, scope_id, scope);
  359. }
  360. return SemIR::InstId::Invalid;
  361. }
  362. auto Context::LookupQualifiedName(Parse::NodeId node_id, SemIR::NameId name_id,
  363. LookupScope scope, bool required)
  364. -> LookupResult {
  365. llvm::SmallVector<LookupScope> scopes = {scope};
  366. LookupResult result = {.instance_id = SemIR::GenericInstanceId::Invalid,
  367. .inst_id = SemIR::InstId::Invalid};
  368. bool has_error = false;
  369. // Walk this scope and, if nothing is found here, the scopes it extends.
  370. while (!scopes.empty()) {
  371. auto [scope_id, instance_id] = scopes.pop_back_val();
  372. const auto& scope = name_scopes().Get(scope_id);
  373. has_error |= scope.has_error;
  374. auto scope_result_id =
  375. LookupNameInExactScope(node_id, name_id, scope_id, scope);
  376. if (!scope_result_id.is_valid()) {
  377. // Nothing found in this scope: also look in its extended scopes.
  378. auto extended = scope.extended_scopes;
  379. scopes.reserve(scopes.size() + extended.size());
  380. for (auto extended_id : llvm::reverse(extended)) {
  381. // TODO: Track a constant describing the extended scope, and substitute
  382. // into it to determine its corresponding generic instance.
  383. scopes.push_back({.name_scope_id = extended_id,
  384. .instance_id = SemIR::GenericInstanceId::Invalid});
  385. }
  386. continue;
  387. }
  388. // If this is our second lookup result, diagnose an ambiguity.
  389. if (result.inst_id.is_valid()) {
  390. // TODO: This is currently not reachable because the only scope that can
  391. // extend is a class scope, and it can only extend a single base class.
  392. // Add test coverage once this is possible.
  393. CARBON_DIAGNOSTIC(
  394. NameAmbiguousDueToExtend, Error,
  395. "Ambiguous use of name `{0}` found in multiple extended scopes.",
  396. SemIR::NameId);
  397. emitter_->Emit(node_id, NameAmbiguousDueToExtend, name_id);
  398. // TODO: Add notes pointing to the scopes.
  399. return {.instance_id = SemIR::GenericInstanceId::Invalid,
  400. .inst_id = SemIR::InstId::BuiltinError};
  401. }
  402. result.inst_id = scope_result_id;
  403. result.instance_id = instance_id;
  404. }
  405. if (required && !result.inst_id.is_valid()) {
  406. if (!has_error) {
  407. DiagnoseNameNotFound(node_id, name_id);
  408. }
  409. return {.instance_id = SemIR::GenericInstanceId::Invalid,
  410. .inst_id = SemIR::InstId::BuiltinError};
  411. }
  412. return result;
  413. }
  414. // Returns the scope of the Core package, or Invalid if it's not found.
  415. //
  416. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  417. // name lookup to find it.
  418. static auto GetCorePackage(Context& context, SemIRLoc loc)
  419. -> SemIR::NameScopeId {
  420. auto core_ident_id = context.identifiers().Add("Core");
  421. auto packaging = context.parse_tree().packaging_decl();
  422. if (packaging && packaging->names.package_id == core_ident_id) {
  423. return SemIR::NameScopeId::Package;
  424. }
  425. auto core_name_id = SemIR::NameId::ForIdentifier(core_ident_id);
  426. // Look up `package.Core`.
  427. auto core_inst_id = context.LookupNameInExactScope(
  428. loc, core_name_id, SemIR::NameScopeId::Package,
  429. context.name_scopes().Get(SemIR::NameScopeId::Package));
  430. if (!core_inst_id.is_valid()) {
  431. context.DiagnoseNameNotFound(loc, core_name_id);
  432. return SemIR::NameScopeId::Invalid;
  433. }
  434. // We expect it to be a namespace.
  435. if (auto namespace_inst =
  436. context.insts().TryGetAs<SemIR::Namespace>(core_inst_id)) {
  437. return namespace_inst->name_scope_id;
  438. }
  439. // TODO: This should really diagnose the name issue.
  440. context.DiagnoseNameNotFound(loc, core_name_id);
  441. return SemIR::NameScopeId::Invalid;
  442. }
  443. auto Context::LookupNameInCore(SemIRLoc loc, llvm::StringRef name)
  444. -> SemIR::InstId {
  445. auto core_package_id = GetCorePackage(*this, loc);
  446. if (!core_package_id.is_valid()) {
  447. return SemIR::InstId::BuiltinError;
  448. }
  449. auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
  450. auto inst_id = LookupNameInExactScope(loc, name_id, core_package_id,
  451. name_scopes().Get(core_package_id));
  452. if (!inst_id.is_valid()) {
  453. DiagnoseNameNotFound(loc, name_id);
  454. return SemIR::InstId::BuiltinError;
  455. }
  456. // Look through import_refs and aliases.
  457. return constant_values().GetConstantInstId(inst_id);
  458. }
  459. template <typename BranchNode, typename... Args>
  460. static auto AddDominatedBlockAndBranchImpl(Context& context,
  461. Parse::NodeId node_id, Args... args)
  462. -> SemIR::InstBlockId {
  463. if (!context.inst_block_stack().is_current_block_reachable()) {
  464. return SemIR::InstBlockId::Unreachable;
  465. }
  466. auto block_id = context.inst_blocks().AddDefaultValue();
  467. context.AddInst<BranchNode>(node_id, {block_id, args...});
  468. return block_id;
  469. }
  470. auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
  471. -> SemIR::InstBlockId {
  472. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
  473. }
  474. auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  475. SemIR::InstId arg_id)
  476. -> SemIR::InstBlockId {
  477. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
  478. arg_id);
  479. }
  480. auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  481. SemIR::InstId cond_id)
  482. -> SemIR::InstBlockId {
  483. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
  484. cond_id);
  485. }
  486. auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  487. -> void {
  488. CARBON_CHECK(num_blocks >= 2) << "no convergence";
  489. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  490. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  491. if (inst_block_stack().is_current_block_reachable()) {
  492. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  493. new_block_id = inst_blocks().AddDefaultValue();
  494. }
  495. AddInst<SemIR::Branch>(node_id, {.target_id = new_block_id});
  496. }
  497. inst_block_stack().Pop();
  498. }
  499. inst_block_stack().Push(new_block_id);
  500. }
  501. auto Context::AddConvergenceBlockWithArgAndPush(
  502. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  503. -> SemIR::InstId {
  504. CARBON_CHECK(block_args.size() >= 2) << "no convergence";
  505. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  506. for (auto arg_id : block_args) {
  507. if (inst_block_stack().is_current_block_reachable()) {
  508. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  509. new_block_id = inst_blocks().AddDefaultValue();
  510. }
  511. AddInst<SemIR::BranchWithArg>(
  512. node_id, {.target_id = new_block_id, .arg_id = arg_id});
  513. }
  514. inst_block_stack().Pop();
  515. }
  516. inst_block_stack().Push(new_block_id);
  517. // Acquire the result value.
  518. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  519. return AddInst<SemIR::BlockArg>(
  520. node_id, {.type_id = result_type_id, .block_id = new_block_id});
  521. }
  522. auto Context::SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  523. SemIR::InstId cond_id,
  524. SemIR::InstId if_true,
  525. SemIR::InstId if_false)
  526. -> void {
  527. CARBON_CHECK(insts().Is<SemIR::BlockArg>(select_id));
  528. // Determine the constant result based on the condition value.
  529. SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
  530. auto cond_const_id = constant_values().Get(cond_id);
  531. if (!cond_const_id.is_template()) {
  532. // Symbolic or non-constant condition means a non-constant result.
  533. } else if (auto literal = insts().TryGetAs<SemIR::BoolLiteral>(
  534. constant_values().GetInstId(cond_const_id))) {
  535. const_id = constant_values().Get(literal.value().value.ToBool() ? if_true
  536. : if_false);
  537. } else {
  538. CARBON_CHECK(cond_const_id == SemIR::ConstantId::Error)
  539. << "Unexpected constant branch condition.";
  540. const_id = SemIR::ConstantId::Error;
  541. }
  542. if (const_id.is_constant()) {
  543. CARBON_VLOG() << "Constant: " << insts().Get(select_id) << " -> "
  544. << constant_values().GetInstId(const_id) << "\n";
  545. constant_values().Set(select_id, const_id);
  546. }
  547. }
  548. auto Context::AddCurrentCodeBlockToFunction(Parse::NodeId node_id) -> void {
  549. CARBON_CHECK(!inst_block_stack().empty()) << "no current code block";
  550. if (return_scope_stack().empty()) {
  551. CARBON_CHECK(node_id.is_valid())
  552. << "No current function, but node_id not provided";
  553. TODO(node_id,
  554. "Control flow expressions are currently only supported inside "
  555. "functions.");
  556. return;
  557. }
  558. if (!inst_block_stack().is_current_block_reachable()) {
  559. // Don't include unreachable blocks in the function.
  560. return;
  561. }
  562. auto function_id =
  563. insts()
  564. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  565. .function_id;
  566. functions()
  567. .Get(function_id)
  568. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  569. }
  570. auto Context::is_current_position_reachable() -> bool {
  571. if (!inst_block_stack().is_current_block_reachable()) {
  572. return false;
  573. }
  574. // Our current position is at the end of a reachable block. That position is
  575. // reachable unless the previous instruction is a terminator instruction.
  576. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  577. if (block_contents.empty()) {
  578. return true;
  579. }
  580. const auto& last_inst = insts().Get(block_contents.back());
  581. return last_inst.kind().terminator_kind() !=
  582. SemIR::TerminatorKind::Terminator;
  583. }
  584. auto Context::Finalize() -> void {
  585. // Pop information for the file-level scope.
  586. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  587. scope_stack().Pop();
  588. // Finalizes the list of exports on the IR.
  589. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  590. // Finalizes the ImportRef inst block.
  591. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  592. // Finalizes __global_init.
  593. global_init_.Finalize();
  594. }
  595. namespace {
  596. // Worklist-based type completion mechanism.
  597. //
  598. // When attempting to complete a type, we may find other types that also need to
  599. // be completed: types nested within that type, and the value representation of
  600. // the type. In order to complete a type without recursing arbitrarily deeply,
  601. // we use a worklist of tasks:
  602. //
  603. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  604. // nested within a type to the work list.
  605. // - A `BuildValueRepr` step computes the value representation for a
  606. // type, once all of its nested types are complete, and marks the type as
  607. // complete.
  608. class TypeCompleter {
  609. public:
  610. TypeCompleter(
  611. Context& context,
  612. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  613. diagnoser)
  614. : context_(context), diagnoser_(diagnoser) {}
  615. // Attempts to complete the given type. Returns true if it is now complete,
  616. // false if it could not be completed.
  617. auto Complete(SemIR::TypeId type_id) -> bool {
  618. Push(type_id);
  619. while (!work_list_.empty()) {
  620. if (!ProcessStep()) {
  621. return false;
  622. }
  623. }
  624. return true;
  625. }
  626. private:
  627. // Adds `type_id` to the work list, if it's not already complete.
  628. auto Push(SemIR::TypeId type_id) -> void {
  629. if (!context_.types().IsComplete(type_id)) {
  630. work_list_.push_back(
  631. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  632. }
  633. }
  634. // Runs the next step.
  635. auto ProcessStep() -> bool {
  636. auto [type_id, phase] = work_list_.back();
  637. // We might have enqueued the same type more than once. Just skip the
  638. // type if it's already complete.
  639. if (context_.types().IsComplete(type_id)) {
  640. work_list_.pop_back();
  641. return true;
  642. }
  643. auto inst_id = context_.types().GetInstId(type_id);
  644. auto inst = context_.insts().Get(inst_id);
  645. auto old_work_list_size = work_list_.size();
  646. switch (phase) {
  647. case Phase::AddNestedIncompleteTypes:
  648. if (!AddNestedIncompleteTypes(inst)) {
  649. return false;
  650. }
  651. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  652. << "AddNestedIncompleteTypes should not remove work items";
  653. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  654. break;
  655. case Phase::BuildValueRepr: {
  656. auto value_rep = BuildValueRepr(type_id, inst);
  657. context_.sem_ir().CompleteType(type_id, value_rep);
  658. CARBON_CHECK(old_work_list_size == work_list_.size())
  659. << "BuildValueRepr should not change work items";
  660. work_list_.pop_back();
  661. // Also complete the value representation type, if necessary. This
  662. // should never fail: the value representation shouldn't require any
  663. // additional nested types to be complete.
  664. if (!context_.types().IsComplete(value_rep.type_id)) {
  665. work_list_.push_back(
  666. {.type_id = value_rep.type_id, .phase = Phase::BuildValueRepr});
  667. }
  668. // For a pointer representation, the pointee also needs to be complete.
  669. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  670. if (value_rep.type_id == SemIR::TypeId::Error) {
  671. break;
  672. }
  673. auto pointee_type_id =
  674. context_.sem_ir().GetPointeeType(value_rep.type_id);
  675. if (!context_.types().IsComplete(pointee_type_id)) {
  676. work_list_.push_back(
  677. {.type_id = pointee_type_id, .phase = Phase::BuildValueRepr});
  678. }
  679. }
  680. break;
  681. }
  682. }
  683. return true;
  684. }
  685. // Adds any types nested within `type_inst` that need to be complete for
  686. // `type_inst` to be complete to our work list.
  687. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  688. CARBON_KIND_SWITCH(type_inst) {
  689. case CARBON_KIND(SemIR::ArrayType inst): {
  690. Push(inst.element_type_id);
  691. break;
  692. }
  693. case CARBON_KIND(SemIR::StructType inst): {
  694. for (auto field_id : context_.inst_blocks().Get(inst.fields_id)) {
  695. Push(context_.insts()
  696. .GetAs<SemIR::StructTypeField>(field_id)
  697. .field_type_id);
  698. }
  699. break;
  700. }
  701. case CARBON_KIND(SemIR::TupleType inst): {
  702. for (auto element_type_id :
  703. context_.type_blocks().Get(inst.elements_id)) {
  704. Push(element_type_id);
  705. }
  706. break;
  707. }
  708. case CARBON_KIND(SemIR::ClassType inst): {
  709. auto& class_info = context_.classes().Get(inst.class_id);
  710. if (!class_info.is_defined()) {
  711. if (diagnoser_) {
  712. auto builder = (*diagnoser_)();
  713. context_.NoteIncompleteClass(inst.class_id, builder);
  714. builder.Emit();
  715. }
  716. return false;
  717. }
  718. // TODO: Trigger generic resolution here for a generic class.
  719. Push(class_info.object_repr_id);
  720. break;
  721. }
  722. case CARBON_KIND(SemIR::ConstType inst): {
  723. Push(inst.inner_id);
  724. break;
  725. }
  726. default:
  727. break;
  728. }
  729. return true;
  730. }
  731. // Makes an empty value representation, which is used for types that have no
  732. // state, such as empty structs and tuples.
  733. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  734. return {.kind = SemIR::ValueRepr::None,
  735. .type_id = context_.GetTupleType({})};
  736. }
  737. // Makes a value representation that uses pass-by-copy, copying the given
  738. // type.
  739. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  740. SemIR::ValueRepr::AggregateKind aggregate_kind =
  741. SemIR::ValueRepr::NotAggregate) const
  742. -> SemIR::ValueRepr {
  743. return {.kind = SemIR::ValueRepr::Copy,
  744. .aggregate_kind = aggregate_kind,
  745. .type_id = rep_id};
  746. }
  747. // Makes a value representation that uses pass-by-address with the given
  748. // pointee type.
  749. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  750. SemIR::ValueRepr::AggregateKind aggregate_kind =
  751. SemIR::ValueRepr::NotAggregate) const
  752. -> SemIR::ValueRepr {
  753. // TODO: Should we add `const` qualification to `pointee_id`?
  754. return {.kind = SemIR::ValueRepr::Pointer,
  755. .aggregate_kind = aggregate_kind,
  756. .type_id = context_.GetPointerType(pointee_id)};
  757. }
  758. // Gets the value representation of a nested type, which should already be
  759. // complete.
  760. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  761. CARBON_CHECK(context_.types().IsComplete(nested_type_id))
  762. << "Nested type should already be complete";
  763. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  764. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown)
  765. << "Complete type should have a value representation";
  766. return value_rep;
  767. }
  768. auto BuildBuiltinValueRepr(SemIR::TypeId type_id,
  769. SemIR::Builtin builtin) const -> SemIR::ValueRepr {
  770. switch (builtin.builtin_kind) {
  771. case SemIR::BuiltinKind::TypeType:
  772. case SemIR::BuiltinKind::Error:
  773. case SemIR::BuiltinKind::Invalid:
  774. case SemIR::BuiltinKind::BoolType:
  775. case SemIR::BuiltinKind::IntType:
  776. case SemIR::BuiltinKind::FloatType:
  777. case SemIR::BuiltinKind::NamespaceType:
  778. case SemIR::BuiltinKind::BoundMethodType:
  779. case SemIR::BuiltinKind::WitnessType:
  780. return MakeCopyValueRepr(type_id);
  781. case SemIR::BuiltinKind::StringType:
  782. // TODO: Decide on string value semantics. This should probably be a
  783. // custom value representation carrying a pointer and size or
  784. // similar.
  785. return MakePointerValueRepr(type_id);
  786. }
  787. llvm_unreachable("All builtin kinds were handled above");
  788. }
  789. auto BuildStructOrTupleValueRepr(std::size_t num_elements,
  790. SemIR::TypeId elementwise_rep,
  791. bool same_as_object_rep) const
  792. -> SemIR::ValueRepr {
  793. SemIR::ValueRepr::AggregateKind aggregate_kind =
  794. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  795. : SemIR::ValueRepr::ValueAggregate;
  796. if (num_elements == 1) {
  797. // The value representation for a struct or tuple with a single element
  798. // is a struct or tuple containing the value representation of the
  799. // element.
  800. // TODO: Consider doing the same whenever `elementwise_rep` is
  801. // sufficiently small.
  802. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  803. }
  804. // For a struct or tuple with multiple fields, we use a pointer
  805. // to the elementwise value representation.
  806. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  807. }
  808. auto BuildStructTypeValueRepr(SemIR::TypeId type_id,
  809. SemIR::StructType struct_type) const
  810. -> SemIR::ValueRepr {
  811. // TODO: Share more code with tuples.
  812. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  813. if (fields.empty()) {
  814. return MakeEmptyValueRepr();
  815. }
  816. // Find the value representation for each field, and construct a struct
  817. // of value representations.
  818. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  819. value_rep_fields.reserve(fields.size());
  820. bool same_as_object_rep = true;
  821. for (auto field_id : fields) {
  822. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  823. auto field_value_rep = GetNestedValueRepr(field.field_type_id);
  824. if (field_value_rep.type_id != field.field_type_id) {
  825. same_as_object_rep = false;
  826. field.field_type_id = field_value_rep.type_id;
  827. field_id = context_.constant_values().GetInstId(
  828. TryEvalInst(context_, SemIR::InstId::Invalid, field));
  829. }
  830. value_rep_fields.push_back(field_id);
  831. }
  832. auto value_rep = same_as_object_rep
  833. ? type_id
  834. : context_.GetStructType(
  835. context_.inst_blocks().Add(value_rep_fields));
  836. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  837. same_as_object_rep);
  838. }
  839. auto BuildTupleTypeValueRepr(SemIR::TypeId type_id,
  840. SemIR::TupleType tuple_type) const
  841. -> SemIR::ValueRepr {
  842. // TODO: Share more code with structs.
  843. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  844. if (elements.empty()) {
  845. return MakeEmptyValueRepr();
  846. }
  847. // Find the value representation for each element, and construct a tuple
  848. // of value representations.
  849. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  850. value_rep_elements.reserve(elements.size());
  851. bool same_as_object_rep = true;
  852. for (auto element_type_id : elements) {
  853. auto element_value_rep = GetNestedValueRepr(element_type_id);
  854. if (element_value_rep.type_id != element_type_id) {
  855. same_as_object_rep = false;
  856. }
  857. value_rep_elements.push_back(element_value_rep.type_id);
  858. }
  859. auto value_rep = same_as_object_rep
  860. ? type_id
  861. : context_.GetTupleType(value_rep_elements);
  862. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  863. same_as_object_rep);
  864. }
  865. // Builds and returns the value representation for the given type. All nested
  866. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  867. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  868. -> SemIR::ValueRepr {
  869. CARBON_KIND_SWITCH(inst) {
  870. #define CARBON_SEM_IR_INST_KIND_TYPE_ALWAYS(...)
  871. #define CARBON_SEM_IR_INST_KIND_TYPE_MAYBE(...)
  872. #define CARBON_SEM_IR_INST_KIND(Name) case SemIR::Name::Kind:
  873. #include "toolchain/sem_ir/inst_kind.def"
  874. CARBON_FATAL() << "Type refers to non-type inst " << inst;
  875. case SemIR::ArrayType::Kind: {
  876. // For arrays, it's convenient to always use a pointer representation,
  877. // even when the array has zero or one element, in order to support
  878. // indexing.
  879. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  880. }
  881. case CARBON_KIND(SemIR::StructType struct_type): {
  882. return BuildStructTypeValueRepr(type_id, struct_type);
  883. }
  884. case CARBON_KIND(SemIR::TupleType tuple_type): {
  885. return BuildTupleTypeValueRepr(type_id, tuple_type);
  886. }
  887. case CARBON_KIND(SemIR::ClassType class_type): {
  888. auto& class_info = context_.classes().Get(class_type.class_id);
  889. // The value representation of an adapter is the value representation of
  890. // its adapted type.
  891. if (class_info.adapt_id.is_valid()) {
  892. return GetNestedValueRepr(class_info.object_repr_id);
  893. }
  894. // Otherwise, the value representation for a class is a pointer to the
  895. // object representation.
  896. // TODO: Support customized value representations for classes.
  897. // TODO: Pick a better value representation when possible.
  898. return MakePointerValueRepr(class_info.object_repr_id,
  899. SemIR::ValueRepr::ObjectAggregate);
  900. }
  901. case SemIR::AssociatedEntityType::Kind:
  902. case SemIR::FunctionType::Kind:
  903. case SemIR::GenericClassType::Kind:
  904. case SemIR::GenericInterfaceType::Kind:
  905. case SemIR::InterfaceType::Kind:
  906. case SemIR::UnboundElementType::Kind: {
  907. // These types have no runtime operations, so we use an empty value
  908. // representation.
  909. //
  910. // TODO: There is information we could model here:
  911. // - For an interface, we could use a witness.
  912. // - For an associated entity, we could use an index into the witness.
  913. // - For an unbound element, we could use an index or offset.
  914. return MakeEmptyValueRepr();
  915. }
  916. case CARBON_KIND(SemIR::Builtin builtin): {
  917. return BuildBuiltinValueRepr(type_id, builtin);
  918. }
  919. case SemIR::BindSymbolicName::Kind:
  920. case SemIR::InterfaceWitnessAccess::Kind:
  921. // For symbolic types, we arbitrarily pick a copy representation.
  922. return MakeCopyValueRepr(type_id);
  923. case SemIR::FloatType::Kind:
  924. case SemIR::IntType::Kind:
  925. case SemIR::PointerType::Kind:
  926. return MakeCopyValueRepr(type_id);
  927. case CARBON_KIND(SemIR::ConstType const_type): {
  928. // The value representation of `const T` is the same as that of `T`.
  929. // Objects are not modifiable through their value representations.
  930. return GetNestedValueRepr(const_type.inner_id);
  931. }
  932. }
  933. }
  934. enum class Phase : int8_t {
  935. // The next step is to add nested types to the list of types to complete.
  936. AddNestedIncompleteTypes,
  937. // The next step is to build the value representation for the type.
  938. BuildValueRepr,
  939. };
  940. struct WorkItem {
  941. SemIR::TypeId type_id;
  942. Phase phase;
  943. };
  944. Context& context_;
  945. llvm::SmallVector<WorkItem> work_list_;
  946. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  947. diagnoser_;
  948. };
  949. } // namespace
  950. auto Context::TryToCompleteType(
  951. SemIR::TypeId type_id,
  952. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  953. -> bool {
  954. return TypeCompleter(*this, diagnoser).Complete(type_id);
  955. }
  956. auto Context::TryToDefineType(
  957. SemIR::TypeId type_id,
  958. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  959. -> bool {
  960. if (!TryToCompleteType(type_id, diagnoser)) {
  961. return false;
  962. }
  963. if (auto interface = types().TryGetAs<SemIR::InterfaceType>(type_id)) {
  964. auto interface_id = interface->interface_id;
  965. if (!interfaces().Get(interface_id).is_defined()) {
  966. auto builder = (*diagnoser)();
  967. NoteUndefinedInterface(interface_id, builder);
  968. builder.Emit();
  969. return false;
  970. }
  971. // TODO: Trigger generic resolution here for a generic instance.
  972. }
  973. return true;
  974. }
  975. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  976. -> SemIR::TypeId {
  977. CARBON_CHECK(constant_id.is_constant())
  978. << "Canonicalizing non-constant type: " << constant_id;
  979. auto result = type_ids_for_type_constants_.Insert(
  980. constant_id, [&]() { return types().Add({.constant_id = constant_id}); });
  981. return result.value();
  982. }
  983. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  984. template <typename InstT, typename... EachArgT>
  985. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  986. -> SemIR::TypeId {
  987. // TODO: Remove inst_id parameter from TryEvalInst.
  988. InstT inst = {SemIR::TypeId::TypeType, each_arg...};
  989. return context.GetTypeIdForTypeConstant(
  990. TryEvalInst(context, SemIR::InstId::Invalid, inst));
  991. }
  992. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  993. // and completes the type. This should only be used when type completion cannot
  994. // fail.
  995. template <typename InstT, typename... EachArgT>
  996. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  997. -> SemIR::TypeId {
  998. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  999. bool complete = context.TryToCompleteType(type_id);
  1000. CARBON_CHECK(complete) << "Type completion should not fail";
  1001. return type_id;
  1002. }
  1003. auto Context::GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId {
  1004. return GetTypeImpl<SemIR::StructType>(*this, refs_id);
  1005. }
  1006. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  1007. -> SemIR::TypeId {
  1008. return GetTypeImpl<SemIR::TupleType>(*this,
  1009. type_blocks().AddCanonical(type_ids));
  1010. }
  1011. auto Context::GetAssociatedEntityType(SemIR::InterfaceId interface_id,
  1012. SemIR::TypeId entity_type_id)
  1013. -> SemIR::TypeId {
  1014. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_id,
  1015. entity_type_id);
  1016. }
  1017. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  1018. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  1019. auto type_id = GetTypeIdForTypeInst(SemIR::InstId::ForBuiltin(kind));
  1020. // To keep client code simpler, complete builtin types before returning them.
  1021. bool complete = TryToCompleteType(type_id);
  1022. CARBON_CHECK(complete) << "Failed to complete builtin type";
  1023. return type_id;
  1024. }
  1025. auto Context::GetFunctionType(SemIR::FunctionId fn_id) -> SemIR::TypeId {
  1026. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id);
  1027. }
  1028. auto Context::GetGenericClassType(SemIR::ClassId class_id) -> SemIR::TypeId {
  1029. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id);
  1030. }
  1031. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id)
  1032. -> SemIR::TypeId {
  1033. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(*this, interface_id);
  1034. }
  1035. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  1036. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  1037. }
  1038. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  1039. SemIR::TypeId element_type_id)
  1040. -> SemIR::TypeId {
  1041. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  1042. element_type_id);
  1043. }
  1044. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  1045. if (auto const_type = types().TryGetAs<SemIR::ConstType>(type_id)) {
  1046. return const_type->inner_id;
  1047. }
  1048. return type_id;
  1049. }
  1050. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  1051. node_stack_.PrintForStackDump(output);
  1052. inst_block_stack_.PrintForStackDump(output);
  1053. param_and_arg_refs_stack_.PrintForStackDump(output);
  1054. args_type_info_stack_.PrintForStackDump(output);
  1055. }
  1056. } // namespace Carbon::Check