context.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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) -> SemIR::InstId {
  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, name_scope_id] : llvm::reverse(non_lexical_scopes)) {
  247. if (auto non_lexical_result =
  248. LookupQualifiedName(node_id, name_id, name_scope_id,
  249. /*required=*/false);
  250. non_lexical_result.is_valid()) {
  251. return non_lexical_result;
  252. }
  253. }
  254. if (lexical_result.is_valid()) {
  255. return lexical_result;
  256. }
  257. // We didn't find anything at all.
  258. DiagnoseNameNotFound(node_id, name_id);
  259. return SemIR::InstId::BuiltinError;
  260. }
  261. // Handles lookup through the import_ir_scopes for LookupNameInExactScope.
  262. static auto LookupInImportIRScopes(Context& context, SemIRLoc loc,
  263. SemIR::NameId name_id,
  264. SemIR::NameScopeId scope_id,
  265. const SemIR::NameScope& scope)
  266. -> SemIR::InstId {
  267. auto identifier_id = name_id.AsIdentifierId();
  268. llvm::StringRef identifier;
  269. if (identifier_id.is_valid()) {
  270. identifier = context.identifiers().Get(identifier_id);
  271. }
  272. DiagnosticAnnotationScope annotate_diagnostics(
  273. &context.emitter(), [&](auto& builder) {
  274. CARBON_DIAGNOSTIC(InNameLookup, Note, "In name lookup for `{0}`.",
  275. SemIR::NameId);
  276. builder.Note(loc, InNameLookup, name_id);
  277. });
  278. auto result_id = SemIR::InstId::Invalid;
  279. std::optional<SemIR::ImportIRInst> canonical_result_inst;
  280. for (auto [import_ir_id, import_scope_id] : scope.import_ir_scopes) {
  281. auto& import_ir = context.import_irs().Get(import_ir_id);
  282. // Determine the NameId in the import IR.
  283. SemIR::NameId import_name_id = name_id;
  284. if (identifier_id.is_valid()) {
  285. auto import_identifier_id =
  286. import_ir.sem_ir->identifiers().Lookup(identifier);
  287. if (!import_identifier_id.is_valid()) {
  288. // Name doesn't exist in the import IR.
  289. continue;
  290. }
  291. import_name_id = SemIR::NameId::ForIdentifier(import_identifier_id);
  292. }
  293. // Look up the name in the import scope.
  294. const auto& import_scope =
  295. import_ir.sem_ir->name_scopes().Get(import_scope_id);
  296. auto lookup = import_scope.name_map.Lookup(import_name_id);
  297. if (!lookup) {
  298. // Name doesn't exist in the import scope.
  299. continue;
  300. }
  301. const auto& import_scope_entry = import_scope.names[lookup.value()];
  302. auto import_inst =
  303. import_ir.sem_ir->insts().Get(import_scope_entry.inst_id);
  304. if (import_inst.Is<SemIR::AnyImportRef>()) {
  305. // This entity was added to name lookup by using an import, and is not
  306. // exported.
  307. continue;
  308. }
  309. if (import_scope_entry.access_kind != SemIR::AccessKind::Public) {
  310. // Ignore cross-package non-public names.
  311. continue;
  312. }
  313. if (result_id.is_valid()) {
  314. // On a conflict, we verify the canonical instruction is the same.
  315. if (!canonical_result_inst) {
  316. canonical_result_inst =
  317. GetCanonicalImportIRInst(context, &context.sem_ir(), result_id);
  318. }
  319. VerifySameCanonicalImportIRInst(
  320. context, result_id, *canonical_result_inst, import_ir_id,
  321. import_ir.sem_ir, import_scope_entry.inst_id);
  322. } else {
  323. // Add the first result found.
  324. auto bind_name_id = context.bind_names().Add(
  325. {.name_id = name_id,
  326. .parent_scope_id = scope_id,
  327. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  328. result_id = AddImportRef(
  329. context,
  330. {.ir_id = import_ir_id, .inst_id = import_scope_entry.inst_id},
  331. bind_name_id);
  332. LoadImportRef(context, result_id);
  333. }
  334. }
  335. return result_id;
  336. }
  337. auto Context::LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  338. SemIR::NameScopeId scope_id,
  339. const SemIR::NameScope& scope)
  340. -> SemIR::InstId {
  341. if (auto lookup = scope.name_map.Lookup(name_id)) {
  342. auto inst_id = scope.names[lookup.value()].inst_id;
  343. LoadImportRef(*this, inst_id);
  344. return inst_id;
  345. }
  346. if (!scope.import_ir_scopes.empty()) {
  347. return LookupInImportIRScopes(*this, loc, name_id, scope_id, scope);
  348. }
  349. return SemIR::InstId::Invalid;
  350. }
  351. auto Context::LookupQualifiedName(Parse::NodeId node_id, SemIR::NameId name_id,
  352. SemIR::NameScopeId scope_id, bool required)
  353. -> SemIR::InstId {
  354. llvm::SmallVector<SemIR::NameScopeId> scope_ids = {scope_id};
  355. auto result_id = SemIR::InstId::Invalid;
  356. bool has_error = false;
  357. // Walk this scope and, if nothing is found here, the scopes it extends.
  358. while (!scope_ids.empty()) {
  359. auto scope_id = scope_ids.pop_back_val();
  360. const auto& scope = name_scopes().Get(scope_id);
  361. has_error |= scope.has_error;
  362. auto scope_result_id =
  363. LookupNameInExactScope(node_id, name_id, scope_id, scope);
  364. if (!scope_result_id.is_valid()) {
  365. // Nothing found in this scope: also look in its extended scopes.
  366. auto extended = llvm::reverse(scope.extended_scopes);
  367. scope_ids.append(extended.begin(), extended.end());
  368. continue;
  369. }
  370. // If this is our second lookup result, diagnose an ambiguity.
  371. if (result_id.is_valid()) {
  372. // TODO: This is currently not reachable because the only scope that can
  373. // extend is a class scope, and it can only extend a single base class.
  374. // Add test coverage once this is possible.
  375. CARBON_DIAGNOSTIC(
  376. NameAmbiguousDueToExtend, Error,
  377. "Ambiguous use of name `{0}` found in multiple extended scopes.",
  378. SemIR::NameId);
  379. emitter_->Emit(node_id, NameAmbiguousDueToExtend, name_id);
  380. // TODO: Add notes pointing to the scopes.
  381. return SemIR::InstId::BuiltinError;
  382. }
  383. result_id = scope_result_id;
  384. }
  385. if (required && !result_id.is_valid()) {
  386. if (!has_error) {
  387. DiagnoseNameNotFound(node_id, name_id);
  388. }
  389. return SemIR::InstId::BuiltinError;
  390. }
  391. return result_id;
  392. }
  393. // Returns the scope of the Core package, or Invalid if it's not found.
  394. //
  395. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  396. // name lookup to find it.
  397. static auto GetCorePackage(Context& context, SemIRLoc loc)
  398. -> SemIR::NameScopeId {
  399. auto core_ident_id = context.identifiers().Add("Core");
  400. auto packaging = context.parse_tree().packaging_decl();
  401. if (packaging && packaging->names.package_id == core_ident_id) {
  402. return SemIR::NameScopeId::Package;
  403. }
  404. auto core_name_id = SemIR::NameId::ForIdentifier(core_ident_id);
  405. // Look up `package.Core`.
  406. auto core_inst_id = context.LookupNameInExactScope(
  407. loc, core_name_id, SemIR::NameScopeId::Package,
  408. context.name_scopes().Get(SemIR::NameScopeId::Package));
  409. if (!core_inst_id.is_valid()) {
  410. context.DiagnoseNameNotFound(loc, core_name_id);
  411. return SemIR::NameScopeId::Invalid;
  412. }
  413. // We expect it to be a namespace.
  414. if (auto namespace_inst =
  415. context.insts().TryGetAs<SemIR::Namespace>(core_inst_id)) {
  416. return namespace_inst->name_scope_id;
  417. }
  418. // TODO: This should really diagnose the name issue.
  419. context.DiagnoseNameNotFound(loc, core_name_id);
  420. return SemIR::NameScopeId::Invalid;
  421. }
  422. auto Context::LookupNameInCore(SemIRLoc loc, llvm::StringRef name)
  423. -> SemIR::InstId {
  424. auto core_package_id = GetCorePackage(*this, loc);
  425. if (!core_package_id.is_valid()) {
  426. return SemIR::InstId::BuiltinError;
  427. }
  428. auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
  429. auto inst_id = LookupNameInExactScope(loc, name_id, core_package_id,
  430. name_scopes().Get(core_package_id));
  431. if (!inst_id.is_valid()) {
  432. DiagnoseNameNotFound(loc, name_id);
  433. return SemIR::InstId::BuiltinError;
  434. }
  435. // Look through import_refs and aliases.
  436. return constant_values().GetConstantInstId(inst_id);
  437. }
  438. template <typename BranchNode, typename... Args>
  439. static auto AddDominatedBlockAndBranchImpl(Context& context,
  440. Parse::NodeId node_id, Args... args)
  441. -> SemIR::InstBlockId {
  442. if (!context.inst_block_stack().is_current_block_reachable()) {
  443. return SemIR::InstBlockId::Unreachable;
  444. }
  445. auto block_id = context.inst_blocks().AddDefaultValue();
  446. context.AddInst<BranchNode>(node_id, {block_id, args...});
  447. return block_id;
  448. }
  449. auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
  450. -> SemIR::InstBlockId {
  451. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
  452. }
  453. auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  454. SemIR::InstId arg_id)
  455. -> SemIR::InstBlockId {
  456. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
  457. arg_id);
  458. }
  459. auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  460. SemIR::InstId cond_id)
  461. -> SemIR::InstBlockId {
  462. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
  463. cond_id);
  464. }
  465. auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  466. -> void {
  467. CARBON_CHECK(num_blocks >= 2) << "no convergence";
  468. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  469. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  470. if (inst_block_stack().is_current_block_reachable()) {
  471. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  472. new_block_id = inst_blocks().AddDefaultValue();
  473. }
  474. AddInst<SemIR::Branch>(node_id, {.target_id = new_block_id});
  475. }
  476. inst_block_stack().Pop();
  477. }
  478. inst_block_stack().Push(new_block_id);
  479. }
  480. auto Context::AddConvergenceBlockWithArgAndPush(
  481. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  482. -> SemIR::InstId {
  483. CARBON_CHECK(block_args.size() >= 2) << "no convergence";
  484. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  485. for (auto arg_id : block_args) {
  486. if (inst_block_stack().is_current_block_reachable()) {
  487. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  488. new_block_id = inst_blocks().AddDefaultValue();
  489. }
  490. AddInst<SemIR::BranchWithArg>(
  491. node_id, {.target_id = new_block_id, .arg_id = arg_id});
  492. }
  493. inst_block_stack().Pop();
  494. }
  495. inst_block_stack().Push(new_block_id);
  496. // Acquire the result value.
  497. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  498. return AddInst<SemIR::BlockArg>(
  499. node_id, {.type_id = result_type_id, .block_id = new_block_id});
  500. }
  501. auto Context::SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  502. SemIR::InstId cond_id,
  503. SemIR::InstId if_true,
  504. SemIR::InstId if_false)
  505. -> void {
  506. CARBON_CHECK(insts().Is<SemIR::BlockArg>(select_id));
  507. // Determine the constant result based on the condition value.
  508. SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
  509. auto cond_const_id = constant_values().Get(cond_id);
  510. if (!cond_const_id.is_template()) {
  511. // Symbolic or non-constant condition means a non-constant result.
  512. } else if (auto literal = insts().TryGetAs<SemIR::BoolLiteral>(
  513. constant_values().GetInstId(cond_const_id))) {
  514. const_id = constant_values().Get(literal.value().value.ToBool() ? if_true
  515. : if_false);
  516. } else {
  517. CARBON_CHECK(cond_const_id == SemIR::ConstantId::Error)
  518. << "Unexpected constant branch condition.";
  519. const_id = SemIR::ConstantId::Error;
  520. }
  521. if (const_id.is_constant()) {
  522. CARBON_VLOG() << "Constant: " << insts().Get(select_id) << " -> "
  523. << constant_values().GetInstId(const_id) << "\n";
  524. constant_values().Set(select_id, const_id);
  525. }
  526. }
  527. auto Context::AddCurrentCodeBlockToFunction(Parse::NodeId node_id) -> void {
  528. CARBON_CHECK(!inst_block_stack().empty()) << "no current code block";
  529. if (return_scope_stack().empty()) {
  530. CARBON_CHECK(node_id.is_valid())
  531. << "No current function, but node_id not provided";
  532. TODO(node_id,
  533. "Control flow expressions are currently only supported inside "
  534. "functions.");
  535. return;
  536. }
  537. if (!inst_block_stack().is_current_block_reachable()) {
  538. // Don't include unreachable blocks in the function.
  539. return;
  540. }
  541. auto function_id =
  542. insts()
  543. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  544. .function_id;
  545. functions()
  546. .Get(function_id)
  547. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  548. }
  549. auto Context::is_current_position_reachable() -> bool {
  550. if (!inst_block_stack().is_current_block_reachable()) {
  551. return false;
  552. }
  553. // Our current position is at the end of a reachable block. That position is
  554. // reachable unless the previous instruction is a terminator instruction.
  555. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  556. if (block_contents.empty()) {
  557. return true;
  558. }
  559. const auto& last_inst = insts().Get(block_contents.back());
  560. return last_inst.kind().terminator_kind() !=
  561. SemIR::TerminatorKind::Terminator;
  562. }
  563. auto Context::Finalize() -> void {
  564. // Pop information for the file-level scope.
  565. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  566. scope_stack().Pop();
  567. // Finalizes the list of exports on the IR.
  568. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  569. // Finalizes the ImportRef inst block.
  570. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  571. // Finalizes __global_init.
  572. global_init_.Finalize();
  573. }
  574. namespace {
  575. // Worklist-based type completion mechanism.
  576. //
  577. // When attempting to complete a type, we may find other types that also need to
  578. // be completed: types nested within that type, and the value representation of
  579. // the type. In order to complete a type without recursing arbitrarily deeply,
  580. // we use a worklist of tasks:
  581. //
  582. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  583. // nested within a type to the work list.
  584. // - A `BuildValueRepr` step computes the value representation for a
  585. // type, once all of its nested types are complete, and marks the type as
  586. // complete.
  587. class TypeCompleter {
  588. public:
  589. TypeCompleter(
  590. Context& context,
  591. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  592. diagnoser)
  593. : context_(context), diagnoser_(diagnoser) {}
  594. // Attempts to complete the given type. Returns true if it is now complete,
  595. // false if it could not be completed.
  596. auto Complete(SemIR::TypeId type_id) -> bool {
  597. Push(type_id);
  598. while (!work_list_.empty()) {
  599. if (!ProcessStep()) {
  600. return false;
  601. }
  602. }
  603. return true;
  604. }
  605. private:
  606. // Adds `type_id` to the work list, if it's not already complete.
  607. auto Push(SemIR::TypeId type_id) -> void {
  608. if (!context_.types().IsComplete(type_id)) {
  609. work_list_.push_back(
  610. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  611. }
  612. }
  613. // Runs the next step.
  614. auto ProcessStep() -> bool {
  615. auto [type_id, phase] = work_list_.back();
  616. // We might have enqueued the same type more than once. Just skip the
  617. // type if it's already complete.
  618. if (context_.types().IsComplete(type_id)) {
  619. work_list_.pop_back();
  620. return true;
  621. }
  622. auto inst_id = context_.types().GetInstId(type_id);
  623. auto inst = context_.insts().Get(inst_id);
  624. auto old_work_list_size = work_list_.size();
  625. switch (phase) {
  626. case Phase::AddNestedIncompleteTypes:
  627. if (!AddNestedIncompleteTypes(inst)) {
  628. return false;
  629. }
  630. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  631. << "AddNestedIncompleteTypes should not remove work items";
  632. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  633. break;
  634. case Phase::BuildValueRepr: {
  635. auto value_rep = BuildValueRepr(type_id, inst);
  636. context_.sem_ir().CompleteType(type_id, value_rep);
  637. CARBON_CHECK(old_work_list_size == work_list_.size())
  638. << "BuildValueRepr should not change work items";
  639. work_list_.pop_back();
  640. // Also complete the value representation type, if necessary. This
  641. // should never fail: the value representation shouldn't require any
  642. // additional nested types to be complete.
  643. if (!context_.types().IsComplete(value_rep.type_id)) {
  644. work_list_.push_back(
  645. {.type_id = value_rep.type_id, .phase = Phase::BuildValueRepr});
  646. }
  647. // For a pointer representation, the pointee also needs to be complete.
  648. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  649. if (value_rep.type_id == SemIR::TypeId::Error) {
  650. break;
  651. }
  652. auto pointee_type_id =
  653. context_.sem_ir().GetPointeeType(value_rep.type_id);
  654. if (!context_.types().IsComplete(pointee_type_id)) {
  655. work_list_.push_back(
  656. {.type_id = pointee_type_id, .phase = Phase::BuildValueRepr});
  657. }
  658. }
  659. break;
  660. }
  661. }
  662. return true;
  663. }
  664. // Adds any types nested within `type_inst` that need to be complete for
  665. // `type_inst` to be complete to our work list.
  666. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  667. CARBON_KIND_SWITCH(type_inst) {
  668. case CARBON_KIND(SemIR::ArrayType inst): {
  669. Push(inst.element_type_id);
  670. break;
  671. }
  672. case CARBON_KIND(SemIR::StructType inst): {
  673. for (auto field_id : context_.inst_blocks().Get(inst.fields_id)) {
  674. Push(context_.insts()
  675. .GetAs<SemIR::StructTypeField>(field_id)
  676. .field_type_id);
  677. }
  678. break;
  679. }
  680. case CARBON_KIND(SemIR::TupleType inst): {
  681. for (auto element_type_id :
  682. context_.type_blocks().Get(inst.elements_id)) {
  683. Push(element_type_id);
  684. }
  685. break;
  686. }
  687. case CARBON_KIND(SemIR::ClassType inst): {
  688. auto& class_info = context_.classes().Get(inst.class_id);
  689. if (!class_info.is_defined()) {
  690. if (diagnoser_) {
  691. auto builder = (*diagnoser_)();
  692. context_.NoteIncompleteClass(inst.class_id, builder);
  693. builder.Emit();
  694. }
  695. return false;
  696. }
  697. Push(class_info.object_repr_id);
  698. break;
  699. }
  700. case CARBON_KIND(SemIR::ConstType inst): {
  701. Push(inst.inner_id);
  702. break;
  703. }
  704. default:
  705. break;
  706. }
  707. return true;
  708. }
  709. // Makes an empty value representation, which is used for types that have no
  710. // state, such as empty structs and tuples.
  711. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  712. return {.kind = SemIR::ValueRepr::None,
  713. .type_id = context_.GetTupleType({})};
  714. }
  715. // Makes a value representation that uses pass-by-copy, copying the given
  716. // type.
  717. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  718. SemIR::ValueRepr::AggregateKind aggregate_kind =
  719. SemIR::ValueRepr::NotAggregate) const
  720. -> SemIR::ValueRepr {
  721. return {.kind = SemIR::ValueRepr::Copy,
  722. .aggregate_kind = aggregate_kind,
  723. .type_id = rep_id};
  724. }
  725. // Makes a value representation that uses pass-by-address with the given
  726. // pointee type.
  727. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  728. SemIR::ValueRepr::AggregateKind aggregate_kind =
  729. SemIR::ValueRepr::NotAggregate) const
  730. -> SemIR::ValueRepr {
  731. // TODO: Should we add `const` qualification to `pointee_id`?
  732. return {.kind = SemIR::ValueRepr::Pointer,
  733. .aggregate_kind = aggregate_kind,
  734. .type_id = context_.GetPointerType(pointee_id)};
  735. }
  736. // Gets the value representation of a nested type, which should already be
  737. // complete.
  738. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  739. CARBON_CHECK(context_.types().IsComplete(nested_type_id))
  740. << "Nested type should already be complete";
  741. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  742. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown)
  743. << "Complete type should have a value representation";
  744. return value_rep;
  745. }
  746. auto BuildBuiltinValueRepr(SemIR::TypeId type_id,
  747. SemIR::Builtin builtin) const -> SemIR::ValueRepr {
  748. switch (builtin.builtin_kind) {
  749. case SemIR::BuiltinKind::TypeType:
  750. case SemIR::BuiltinKind::Error:
  751. case SemIR::BuiltinKind::Invalid:
  752. case SemIR::BuiltinKind::BoolType:
  753. case SemIR::BuiltinKind::IntType:
  754. case SemIR::BuiltinKind::FloatType:
  755. case SemIR::BuiltinKind::NamespaceType:
  756. case SemIR::BuiltinKind::BoundMethodType:
  757. case SemIR::BuiltinKind::WitnessType:
  758. return MakeCopyValueRepr(type_id);
  759. case SemIR::BuiltinKind::StringType:
  760. // TODO: Decide on string value semantics. This should probably be a
  761. // custom value representation carrying a pointer and size or
  762. // similar.
  763. return MakePointerValueRepr(type_id);
  764. }
  765. llvm_unreachable("All builtin kinds were handled above");
  766. }
  767. auto BuildStructOrTupleValueRepr(std::size_t num_elements,
  768. SemIR::TypeId elementwise_rep,
  769. bool same_as_object_rep) const
  770. -> SemIR::ValueRepr {
  771. SemIR::ValueRepr::AggregateKind aggregate_kind =
  772. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  773. : SemIR::ValueRepr::ValueAggregate;
  774. if (num_elements == 1) {
  775. // The value representation for a struct or tuple with a single element
  776. // is a struct or tuple containing the value representation of the
  777. // element.
  778. // TODO: Consider doing the same whenever `elementwise_rep` is
  779. // sufficiently small.
  780. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  781. }
  782. // For a struct or tuple with multiple fields, we use a pointer
  783. // to the elementwise value representation.
  784. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  785. }
  786. auto BuildStructTypeValueRepr(SemIR::TypeId type_id,
  787. SemIR::StructType struct_type) const
  788. -> SemIR::ValueRepr {
  789. // TODO: Share more code with tuples.
  790. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  791. if (fields.empty()) {
  792. return MakeEmptyValueRepr();
  793. }
  794. // Find the value representation for each field, and construct a struct
  795. // of value representations.
  796. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  797. value_rep_fields.reserve(fields.size());
  798. bool same_as_object_rep = true;
  799. for (auto field_id : fields) {
  800. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  801. auto field_value_rep = GetNestedValueRepr(field.field_type_id);
  802. if (field_value_rep.type_id != field.field_type_id) {
  803. same_as_object_rep = false;
  804. field.field_type_id = field_value_rep.type_id;
  805. field_id = context_.constant_values().GetInstId(
  806. TryEvalInst(context_, SemIR::InstId::Invalid, field));
  807. }
  808. value_rep_fields.push_back(field_id);
  809. }
  810. auto value_rep = same_as_object_rep
  811. ? type_id
  812. : context_.GetStructType(
  813. context_.inst_blocks().Add(value_rep_fields));
  814. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  815. same_as_object_rep);
  816. }
  817. auto BuildTupleTypeValueRepr(SemIR::TypeId type_id,
  818. SemIR::TupleType tuple_type) const
  819. -> SemIR::ValueRepr {
  820. // TODO: Share more code with structs.
  821. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  822. if (elements.empty()) {
  823. return MakeEmptyValueRepr();
  824. }
  825. // Find the value representation for each element, and construct a tuple
  826. // of value representations.
  827. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  828. value_rep_elements.reserve(elements.size());
  829. bool same_as_object_rep = true;
  830. for (auto element_type_id : elements) {
  831. auto element_value_rep = GetNestedValueRepr(element_type_id);
  832. if (element_value_rep.type_id != element_type_id) {
  833. same_as_object_rep = false;
  834. }
  835. value_rep_elements.push_back(element_value_rep.type_id);
  836. }
  837. auto value_rep = same_as_object_rep
  838. ? type_id
  839. : context_.GetTupleType(value_rep_elements);
  840. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  841. same_as_object_rep);
  842. }
  843. // Builds and returns the value representation for the given type. All nested
  844. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  845. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  846. -> SemIR::ValueRepr {
  847. CARBON_KIND_SWITCH(inst) {
  848. #define CARBON_SEM_IR_INST_KIND_TYPE_ALWAYS(...)
  849. #define CARBON_SEM_IR_INST_KIND_TYPE_MAYBE(...)
  850. #define CARBON_SEM_IR_INST_KIND(Name) case SemIR::Name::Kind:
  851. #include "toolchain/sem_ir/inst_kind.def"
  852. CARBON_FATAL() << "Type refers to non-type inst " << inst;
  853. case SemIR::ArrayType::Kind: {
  854. // For arrays, it's convenient to always use a pointer representation,
  855. // even when the array has zero or one element, in order to support
  856. // indexing.
  857. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  858. }
  859. case CARBON_KIND(SemIR::StructType struct_type): {
  860. return BuildStructTypeValueRepr(type_id, struct_type);
  861. }
  862. case CARBON_KIND(SemIR::TupleType tuple_type): {
  863. return BuildTupleTypeValueRepr(type_id, tuple_type);
  864. }
  865. case CARBON_KIND(SemIR::ClassType class_type): {
  866. auto& class_info = context_.classes().Get(class_type.class_id);
  867. // The value representation of an adapter is the value representation of
  868. // its adapted type.
  869. if (class_info.adapt_id.is_valid()) {
  870. return GetNestedValueRepr(class_info.object_repr_id);
  871. }
  872. // Otherwise, the value representation for a class is a pointer to the
  873. // object representation.
  874. // TODO: Support customized value representations for classes.
  875. // TODO: Pick a better value representation when possible.
  876. return MakePointerValueRepr(class_info.object_repr_id,
  877. SemIR::ValueRepr::ObjectAggregate);
  878. }
  879. case SemIR::AssociatedEntityType::Kind:
  880. case SemIR::FunctionType::Kind:
  881. case SemIR::GenericClassType::Kind:
  882. case SemIR::GenericInterfaceType::Kind:
  883. case SemIR::InterfaceType::Kind:
  884. case SemIR::UnboundElementType::Kind: {
  885. // These types have no runtime operations, so we use an empty value
  886. // representation.
  887. //
  888. // TODO: There is information we could model here:
  889. // - For an interface, we could use a witness.
  890. // - For an associated entity, we could use an index into the witness.
  891. // - For an unbound element, we could use an index or offset.
  892. return MakeEmptyValueRepr();
  893. }
  894. case CARBON_KIND(SemIR::Builtin builtin): {
  895. return BuildBuiltinValueRepr(type_id, builtin);
  896. }
  897. case SemIR::BindSymbolicName::Kind:
  898. case SemIR::InterfaceWitnessAccess::Kind:
  899. // For symbolic types, we arbitrarily pick a copy representation.
  900. return MakeCopyValueRepr(type_id);
  901. case SemIR::FloatType::Kind:
  902. case SemIR::IntType::Kind:
  903. case SemIR::PointerType::Kind:
  904. return MakeCopyValueRepr(type_id);
  905. case CARBON_KIND(SemIR::ConstType const_type): {
  906. // The value representation of `const T` is the same as that of `T`.
  907. // Objects are not modifiable through their value representations.
  908. return GetNestedValueRepr(const_type.inner_id);
  909. }
  910. }
  911. }
  912. enum class Phase : int8_t {
  913. // The next step is to add nested types to the list of types to complete.
  914. AddNestedIncompleteTypes,
  915. // The next step is to build the value representation for the type.
  916. BuildValueRepr,
  917. };
  918. struct WorkItem {
  919. SemIR::TypeId type_id;
  920. Phase phase;
  921. };
  922. Context& context_;
  923. llvm::SmallVector<WorkItem> work_list_;
  924. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  925. diagnoser_;
  926. };
  927. } // namespace
  928. auto Context::TryToCompleteType(
  929. SemIR::TypeId type_id,
  930. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  931. -> bool {
  932. return TypeCompleter(*this, diagnoser).Complete(type_id);
  933. }
  934. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  935. -> SemIR::TypeId {
  936. CARBON_CHECK(constant_id.is_constant())
  937. << "Canonicalizing non-constant type: " << constant_id;
  938. auto result = type_ids_for_type_constants_.Insert(
  939. constant_id, [&]() { return types().Add({.constant_id = constant_id}); });
  940. return result.value();
  941. }
  942. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  943. template <typename InstT, typename... EachArgT>
  944. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  945. -> SemIR::TypeId {
  946. // TODO: Remove inst_id parameter from TryEvalInst.
  947. InstT inst = {SemIR::TypeId::TypeType, each_arg...};
  948. return context.GetTypeIdForTypeConstant(
  949. TryEvalInst(context, SemIR::InstId::Invalid, inst));
  950. }
  951. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  952. // and completes the type. This should only be used when type completion cannot
  953. // fail.
  954. template <typename InstT, typename... EachArgT>
  955. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  956. -> SemIR::TypeId {
  957. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  958. bool complete = context.TryToCompleteType(type_id);
  959. CARBON_CHECK(complete) << "Type completion should not fail";
  960. return type_id;
  961. }
  962. auto Context::GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId {
  963. return GetTypeImpl<SemIR::StructType>(*this, refs_id);
  964. }
  965. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  966. -> SemIR::TypeId {
  967. return GetTypeImpl<SemIR::TupleType>(*this,
  968. type_blocks().AddCanonical(type_ids));
  969. }
  970. auto Context::GetAssociatedEntityType(SemIR::InterfaceId interface_id,
  971. SemIR::TypeId entity_type_id)
  972. -> SemIR::TypeId {
  973. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_id,
  974. entity_type_id);
  975. }
  976. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  977. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  978. auto type_id = GetTypeIdForTypeInst(SemIR::InstId::ForBuiltin(kind));
  979. // To keep client code simpler, complete builtin types before returning them.
  980. bool complete = TryToCompleteType(type_id);
  981. CARBON_CHECK(complete) << "Failed to complete builtin type";
  982. return type_id;
  983. }
  984. auto Context::GetFunctionType(SemIR::FunctionId fn_id) -> SemIR::TypeId {
  985. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id);
  986. }
  987. auto Context::GetGenericClassType(SemIR::ClassId class_id) -> SemIR::TypeId {
  988. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id);
  989. }
  990. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id)
  991. -> SemIR::TypeId {
  992. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(*this, interface_id);
  993. }
  994. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  995. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  996. }
  997. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  998. SemIR::TypeId element_type_id)
  999. -> SemIR::TypeId {
  1000. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  1001. element_type_id);
  1002. }
  1003. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  1004. if (auto const_type = types().TryGetAs<SemIR::ConstType>(type_id)) {
  1005. return const_type->inner_id;
  1006. }
  1007. return type_id;
  1008. }
  1009. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  1010. node_stack_.PrintForStackDump(output);
  1011. inst_block_stack_.PrintForStackDump(output);
  1012. param_and_arg_refs_stack_.PrintForStackDump(output);
  1013. args_type_info_stack_.PrintForStackDump(output);
  1014. }
  1015. } // namespace Carbon::Check