context.cpp 42 KB

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