context.cpp 43 KB

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