context.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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. namespace {
  564. // Worklist-based type completion mechanism.
  565. //
  566. // When attempting to complete a type, we may find other types that also need to
  567. // be completed: types nested within that type, and the value representation of
  568. // the type. In order to complete a type without recursing arbitrarily deeply,
  569. // we use a worklist of tasks:
  570. //
  571. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  572. // nested within a type to the work list.
  573. // - A `BuildValueRepr` step computes the value representation for a
  574. // type, once all of its nested types are complete, and marks the type as
  575. // complete.
  576. class TypeCompleter {
  577. public:
  578. TypeCompleter(
  579. Context& context,
  580. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  581. diagnoser)
  582. : context_(context), diagnoser_(diagnoser) {}
  583. // Attempts to complete the given type. Returns true if it is now complete,
  584. // false if it could not be completed.
  585. auto Complete(SemIR::TypeId type_id) -> bool {
  586. Push(type_id);
  587. while (!work_list_.empty()) {
  588. if (!ProcessStep()) {
  589. return false;
  590. }
  591. }
  592. return true;
  593. }
  594. private:
  595. // Adds `type_id` to the work list, if it's not already complete.
  596. auto Push(SemIR::TypeId type_id) -> void {
  597. if (!context_.types().IsComplete(type_id)) {
  598. work_list_.push_back(
  599. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  600. }
  601. }
  602. // Runs the next step.
  603. auto ProcessStep() -> bool {
  604. auto [type_id, phase] = work_list_.back();
  605. // We might have enqueued the same type more than once. Just skip the
  606. // type if it's already complete.
  607. if (context_.types().IsComplete(type_id)) {
  608. work_list_.pop_back();
  609. return true;
  610. }
  611. auto inst_id = context_.types().GetInstId(type_id);
  612. auto inst = context_.insts().Get(inst_id);
  613. auto old_work_list_size = work_list_.size();
  614. switch (phase) {
  615. case Phase::AddNestedIncompleteTypes:
  616. if (!AddNestedIncompleteTypes(inst)) {
  617. return false;
  618. }
  619. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  620. << "AddNestedIncompleteTypes should not remove work items";
  621. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  622. break;
  623. case Phase::BuildValueRepr: {
  624. auto value_rep = BuildValueRepr(type_id, inst);
  625. context_.sem_ir().CompleteType(type_id, value_rep);
  626. CARBON_CHECK(old_work_list_size == work_list_.size())
  627. << "BuildValueRepr should not change work items";
  628. work_list_.pop_back();
  629. // Also complete the value representation type, if necessary. This
  630. // should never fail: the value representation shouldn't require any
  631. // additional nested types to be complete.
  632. if (!context_.types().IsComplete(value_rep.type_id)) {
  633. work_list_.push_back(
  634. {.type_id = value_rep.type_id, .phase = Phase::BuildValueRepr});
  635. }
  636. // For a pointer representation, the pointee also needs to be complete.
  637. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  638. if (value_rep.type_id == SemIR::TypeId::Error) {
  639. break;
  640. }
  641. auto pointee_type_id =
  642. context_.sem_ir().GetPointeeType(value_rep.type_id);
  643. if (!context_.types().IsComplete(pointee_type_id)) {
  644. work_list_.push_back(
  645. {.type_id = pointee_type_id, .phase = Phase::BuildValueRepr});
  646. }
  647. }
  648. break;
  649. }
  650. }
  651. return true;
  652. }
  653. // Adds any types nested within `type_inst` that need to be complete for
  654. // `type_inst` to be complete to our work list.
  655. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  656. CARBON_KIND_SWITCH(type_inst) {
  657. case CARBON_KIND(SemIR::ArrayType inst): {
  658. Push(inst.element_type_id);
  659. break;
  660. }
  661. case CARBON_KIND(SemIR::StructType inst): {
  662. for (auto field_id : context_.inst_blocks().Get(inst.fields_id)) {
  663. Push(context_.insts()
  664. .GetAs<SemIR::StructTypeField>(field_id)
  665. .field_type_id);
  666. }
  667. break;
  668. }
  669. case CARBON_KIND(SemIR::TupleType inst): {
  670. for (auto element_type_id :
  671. context_.type_blocks().Get(inst.elements_id)) {
  672. Push(element_type_id);
  673. }
  674. break;
  675. }
  676. case CARBON_KIND(SemIR::ClassType inst): {
  677. auto& class_info = context_.classes().Get(inst.class_id);
  678. if (!class_info.is_defined()) {
  679. if (diagnoser_) {
  680. auto builder = (*diagnoser_)();
  681. context_.NoteIncompleteClass(inst.class_id, builder);
  682. builder.Emit();
  683. }
  684. return false;
  685. }
  686. Push(class_info.object_repr_id);
  687. break;
  688. }
  689. case CARBON_KIND(SemIR::ConstType inst): {
  690. Push(inst.inner_id);
  691. break;
  692. }
  693. default:
  694. break;
  695. }
  696. return true;
  697. }
  698. // Makes an empty value representation, which is used for types that have no
  699. // state, such as empty structs and tuples.
  700. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  701. return {.kind = SemIR::ValueRepr::None,
  702. .type_id = context_.GetTupleType({})};
  703. }
  704. // Makes a value representation that uses pass-by-copy, copying the given
  705. // type.
  706. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  707. SemIR::ValueRepr::AggregateKind aggregate_kind =
  708. SemIR::ValueRepr::NotAggregate) const
  709. -> SemIR::ValueRepr {
  710. return {.kind = SemIR::ValueRepr::Copy,
  711. .aggregate_kind = aggregate_kind,
  712. .type_id = rep_id};
  713. }
  714. // Makes a value representation that uses pass-by-address with the given
  715. // pointee type.
  716. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  717. SemIR::ValueRepr::AggregateKind aggregate_kind =
  718. SemIR::ValueRepr::NotAggregate) const
  719. -> SemIR::ValueRepr {
  720. // TODO: Should we add `const` qualification to `pointee_id`?
  721. return {.kind = SemIR::ValueRepr::Pointer,
  722. .aggregate_kind = aggregate_kind,
  723. .type_id = context_.GetPointerType(pointee_id)};
  724. }
  725. // Gets the value representation of a nested type, which should already be
  726. // complete.
  727. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  728. CARBON_CHECK(context_.types().IsComplete(nested_type_id))
  729. << "Nested type should already be complete";
  730. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  731. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown)
  732. << "Complete type should have a value representation";
  733. return value_rep;
  734. }
  735. auto BuildBuiltinValueRepr(SemIR::TypeId type_id,
  736. SemIR::Builtin builtin) const -> SemIR::ValueRepr {
  737. switch (builtin.builtin_kind) {
  738. case SemIR::BuiltinKind::TypeType:
  739. case SemIR::BuiltinKind::Error:
  740. case SemIR::BuiltinKind::Invalid:
  741. case SemIR::BuiltinKind::BoolType:
  742. case SemIR::BuiltinKind::IntType:
  743. case SemIR::BuiltinKind::FloatType:
  744. case SemIR::BuiltinKind::NamespaceType:
  745. case SemIR::BuiltinKind::BoundMethodType:
  746. case SemIR::BuiltinKind::WitnessType:
  747. return MakeCopyValueRepr(type_id);
  748. case SemIR::BuiltinKind::StringType:
  749. // TODO: Decide on string value semantics. This should probably be a
  750. // custom value representation carrying a pointer and size or
  751. // similar.
  752. return MakePointerValueRepr(type_id);
  753. }
  754. llvm_unreachable("All builtin kinds were handled above");
  755. }
  756. auto BuildStructOrTupleValueRepr(std::size_t num_elements,
  757. SemIR::TypeId elementwise_rep,
  758. bool same_as_object_rep) const
  759. -> SemIR::ValueRepr {
  760. SemIR::ValueRepr::AggregateKind aggregate_kind =
  761. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  762. : SemIR::ValueRepr::ValueAggregate;
  763. if (num_elements == 1) {
  764. // The value representation for a struct or tuple with a single element
  765. // is a struct or tuple containing the value representation of the
  766. // element.
  767. // TODO: Consider doing the same whenever `elementwise_rep` is
  768. // sufficiently small.
  769. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  770. }
  771. // For a struct or tuple with multiple fields, we use a pointer
  772. // to the elementwise value representation.
  773. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  774. }
  775. auto BuildStructTypeValueRepr(SemIR::TypeId type_id,
  776. SemIR::StructType struct_type) const
  777. -> SemIR::ValueRepr {
  778. // TODO: Share more code with tuples.
  779. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  780. if (fields.empty()) {
  781. return MakeEmptyValueRepr();
  782. }
  783. // Find the value representation for each field, and construct a struct
  784. // of value representations.
  785. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  786. value_rep_fields.reserve(fields.size());
  787. bool same_as_object_rep = true;
  788. for (auto field_id : fields) {
  789. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  790. auto field_value_rep = GetNestedValueRepr(field.field_type_id);
  791. if (field_value_rep.type_id != field.field_type_id) {
  792. same_as_object_rep = false;
  793. field.field_type_id = field_value_rep.type_id;
  794. field_id = context_.constant_values().GetInstId(
  795. TryEvalInst(context_, SemIR::InstId::Invalid, field));
  796. }
  797. value_rep_fields.push_back(field_id);
  798. }
  799. auto value_rep = same_as_object_rep
  800. ? type_id
  801. : context_.GetStructType(
  802. context_.inst_blocks().Add(value_rep_fields));
  803. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  804. same_as_object_rep);
  805. }
  806. auto BuildTupleTypeValueRepr(SemIR::TypeId type_id,
  807. SemIR::TupleType tuple_type) const
  808. -> SemIR::ValueRepr {
  809. // TODO: Share more code with structs.
  810. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  811. if (elements.empty()) {
  812. return MakeEmptyValueRepr();
  813. }
  814. // Find the value representation for each element, and construct a tuple
  815. // of value representations.
  816. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  817. value_rep_elements.reserve(elements.size());
  818. bool same_as_object_rep = true;
  819. for (auto element_type_id : elements) {
  820. auto element_value_rep = GetNestedValueRepr(element_type_id);
  821. if (element_value_rep.type_id != element_type_id) {
  822. same_as_object_rep = false;
  823. }
  824. value_rep_elements.push_back(element_value_rep.type_id);
  825. }
  826. auto value_rep = same_as_object_rep
  827. ? type_id
  828. : context_.GetTupleType(value_rep_elements);
  829. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  830. same_as_object_rep);
  831. }
  832. // Builds and returns the value representation for the given type. All nested
  833. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  834. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  835. -> SemIR::ValueRepr {
  836. CARBON_KIND_SWITCH(inst) {
  837. #define CARBON_SEM_IR_INST_KIND_TYPE_ALWAYS(...)
  838. #define CARBON_SEM_IR_INST_KIND_TYPE_MAYBE(...)
  839. #define CARBON_SEM_IR_INST_KIND(Name) case SemIR::Name::Kind:
  840. #include "toolchain/sem_ir/inst_kind.def"
  841. CARBON_FATAL() << "Type refers to non-type inst " << inst;
  842. case SemIR::ArrayType::Kind: {
  843. // For arrays, it's convenient to always use a pointer representation,
  844. // even when the array has zero or one element, in order to support
  845. // indexing.
  846. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  847. }
  848. case CARBON_KIND(SemIR::StructType struct_type): {
  849. return BuildStructTypeValueRepr(type_id, struct_type);
  850. }
  851. case CARBON_KIND(SemIR::TupleType tuple_type): {
  852. return BuildTupleTypeValueRepr(type_id, tuple_type);
  853. }
  854. case CARBON_KIND(SemIR::ClassType class_type): {
  855. auto& class_info = context_.classes().Get(class_type.class_id);
  856. // The value representation of an adapter is the value representation of
  857. // its adapted type.
  858. if (class_info.adapt_id.is_valid()) {
  859. return GetNestedValueRepr(class_info.object_repr_id);
  860. }
  861. // Otherwise, the value representation for a class is a pointer to the
  862. // object representation.
  863. // TODO: Support customized value representations for classes.
  864. // TODO: Pick a better value representation when possible.
  865. return MakePointerValueRepr(class_info.object_repr_id,
  866. SemIR::ValueRepr::ObjectAggregate);
  867. }
  868. case SemIR::AssociatedEntityType::Kind:
  869. case SemIR::FunctionType::Kind:
  870. case SemIR::GenericClassType::Kind:
  871. case SemIR::GenericInterfaceType::Kind:
  872. case SemIR::InterfaceType::Kind:
  873. case SemIR::UnboundElementType::Kind: {
  874. // These types have no runtime operations, so we use an empty value
  875. // representation.
  876. //
  877. // TODO: There is information we could model here:
  878. // - For an interface, we could use a witness.
  879. // - For an associated entity, we could use an index into the witness.
  880. // - For an unbound element, we could use an index or offset.
  881. return MakeEmptyValueRepr();
  882. }
  883. case CARBON_KIND(SemIR::Builtin builtin): {
  884. return BuildBuiltinValueRepr(type_id, builtin);
  885. }
  886. case SemIR::BindSymbolicName::Kind:
  887. case SemIR::InterfaceWitnessAccess::Kind:
  888. // For symbolic types, we arbitrarily pick a copy representation.
  889. return MakeCopyValueRepr(type_id);
  890. case SemIR::FloatType::Kind:
  891. case SemIR::IntType::Kind:
  892. case SemIR::PointerType::Kind:
  893. return MakeCopyValueRepr(type_id);
  894. case CARBON_KIND(SemIR::ConstType const_type): {
  895. // The value representation of `const T` is the same as that of `T`.
  896. // Objects are not modifiable through their value representations.
  897. return GetNestedValueRepr(const_type.inner_id);
  898. }
  899. }
  900. }
  901. enum class Phase : int8_t {
  902. // The next step is to add nested types to the list of types to complete.
  903. AddNestedIncompleteTypes,
  904. // The next step is to build the value representation for the type.
  905. BuildValueRepr,
  906. };
  907. struct WorkItem {
  908. SemIR::TypeId type_id;
  909. Phase phase;
  910. };
  911. Context& context_;
  912. llvm::SmallVector<WorkItem> work_list_;
  913. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  914. diagnoser_;
  915. };
  916. } // namespace
  917. auto Context::TryToCompleteType(
  918. SemIR::TypeId type_id,
  919. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  920. -> bool {
  921. return TypeCompleter(*this, diagnoser).Complete(type_id);
  922. }
  923. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  924. -> SemIR::TypeId {
  925. CARBON_CHECK(constant_id.is_constant())
  926. << "Canonicalizing non-constant type: " << constant_id;
  927. auto result = type_ids_for_type_constants_.Insert(
  928. constant_id, [&]() { return types().Add({.constant_id = constant_id}); });
  929. return result.value();
  930. }
  931. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  932. template <typename InstT, typename... EachArgT>
  933. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  934. -> SemIR::TypeId {
  935. // TODO: Remove inst_id parameter from TryEvalInst.
  936. InstT inst = {SemIR::TypeId::TypeType, each_arg...};
  937. return context.GetTypeIdForTypeConstant(
  938. TryEvalInst(context, SemIR::InstId::Invalid, inst));
  939. }
  940. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  941. // and completes the type. This should only be used when type completion cannot
  942. // fail.
  943. template <typename InstT, typename... EachArgT>
  944. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  945. -> SemIR::TypeId {
  946. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  947. bool complete = context.TryToCompleteType(type_id);
  948. CARBON_CHECK(complete) << "Type completion should not fail";
  949. return type_id;
  950. }
  951. auto Context::GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId {
  952. return GetTypeImpl<SemIR::StructType>(*this, refs_id);
  953. }
  954. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  955. -> SemIR::TypeId {
  956. return GetTypeImpl<SemIR::TupleType>(*this,
  957. type_blocks().AddCanonical(type_ids));
  958. }
  959. auto Context::GetAssociatedEntityType(SemIR::InterfaceId interface_id,
  960. SemIR::TypeId entity_type_id)
  961. -> SemIR::TypeId {
  962. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_id,
  963. entity_type_id);
  964. }
  965. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  966. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  967. auto type_id = GetTypeIdForTypeInst(SemIR::InstId::ForBuiltin(kind));
  968. // To keep client code simpler, complete builtin types before returning them.
  969. bool complete = TryToCompleteType(type_id);
  970. CARBON_CHECK(complete) << "Failed to complete builtin type";
  971. return type_id;
  972. }
  973. auto Context::GetFunctionType(SemIR::FunctionId fn_id) -> SemIR::TypeId {
  974. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id);
  975. }
  976. auto Context::GetGenericClassType(SemIR::ClassId class_id) -> SemIR::TypeId {
  977. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id);
  978. }
  979. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id)
  980. -> SemIR::TypeId {
  981. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(*this, interface_id);
  982. }
  983. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  984. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  985. }
  986. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  987. SemIR::TypeId element_type_id)
  988. -> SemIR::TypeId {
  989. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  990. element_type_id);
  991. }
  992. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  993. if (auto const_type = types().TryGetAs<SemIR::ConstType>(type_id)) {
  994. return const_type->inner_id;
  995. }
  996. return type_id;
  997. }
  998. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  999. node_stack_.PrintForStackDump(output);
  1000. inst_block_stack_.PrintForStackDump(output);
  1001. param_and_arg_refs_stack_.PrintForStackDump(output);
  1002. args_type_info_stack_.PrintForStackDump(output);
  1003. }
  1004. } // namespace Carbon::Check