context.cpp 43 KB

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