context.cpp 41 KB

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