context.cpp 41 KB

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