context.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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/check/decl_name_stack.h"
  11. #include "toolchain/check/inst_block_stack.h"
  12. #include "toolchain/lex/tokenized_buffer.h"
  13. #include "toolchain/parse/node_kind.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/inst_kind.h"
  17. namespace Carbon::Check {
  18. Context::Context(const Lex::TokenizedBuffer& tokens, DiagnosticEmitter& emitter,
  19. const Parse::Tree& parse_tree, SemIR::File& sem_ir,
  20. llvm::raw_ostream* vlog_stream)
  21. : tokens_(&tokens),
  22. emitter_(&emitter),
  23. parse_tree_(&parse_tree),
  24. sem_ir_(&sem_ir),
  25. vlog_stream_(vlog_stream),
  26. node_stack_(parse_tree, vlog_stream),
  27. inst_block_stack_("inst_block_stack_", sem_ir, vlog_stream),
  28. params_or_args_stack_("params_or_args_stack_", sem_ir, vlog_stream),
  29. args_type_info_stack_("args_type_info_stack_", sem_ir, vlog_stream),
  30. decl_name_stack_(this) {
  31. // Inserts the "Error" and "Type" types as "used types" so that
  32. // canonicalization can skip them. We don't emit either for lowering.
  33. canonical_types_.insert({SemIR::InstId::BuiltinError, SemIR::TypeId::Error});
  34. canonical_types_.insert(
  35. {SemIR::InstId::BuiltinTypeType, SemIR::TypeId::TypeType});
  36. }
  37. auto Context::TODO(Parse::Node parse_node, std::string label) -> bool {
  38. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.",
  39. std::string);
  40. emitter_->Emit(parse_node, SemanticsTodo, std::move(label));
  41. return false;
  42. }
  43. auto Context::VerifyOnFinish() -> void {
  44. // Information in all the various context objects should be cleaned up as
  45. // various pieces of context go out of scope. At this point, nothing should
  46. // remain.
  47. // node_stack_ will still contain top-level entities.
  48. CARBON_CHECK(name_lookup_.empty()) << name_lookup_.size();
  49. CARBON_CHECK(scope_stack_.empty()) << scope_stack_.size();
  50. CARBON_CHECK(inst_block_stack_.empty()) << inst_block_stack_.size();
  51. CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size();
  52. }
  53. auto Context::AddInst(SemIR::Inst inst) -> SemIR::InstId {
  54. auto inst_id = inst_block_stack_.AddInst(inst);
  55. CARBON_VLOG() << "AddInst: " << inst << "\n";
  56. return inst_id;
  57. }
  58. auto Context::AddConstantInst(SemIR::Inst inst) -> SemIR::InstId {
  59. auto inst_id = insts().AddInNoBlock(inst);
  60. constants().Add(inst_id);
  61. CARBON_VLOG() << "AddConstantInst: " << inst << "\n";
  62. return inst_id;
  63. }
  64. auto Context::AddInstAndPush(Parse::Node parse_node, SemIR::Inst inst) -> void {
  65. auto inst_id = AddInst(inst);
  66. node_stack_.Push(parse_node, inst_id);
  67. }
  68. auto Context::DiagnoseDuplicateName(Parse::Node parse_node,
  69. SemIR::InstId prev_def_id) -> void {
  70. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  71. "Duplicate name being declared in the same scope.");
  72. CARBON_DIAGNOSTIC(NameDeclPrevious, Note,
  73. "Name is previously declared here.");
  74. auto prev_def = insts().Get(prev_def_id);
  75. emitter_->Build(parse_node, NameDeclDuplicate)
  76. .Note(prev_def.parse_node(), NameDeclPrevious)
  77. .Emit();
  78. }
  79. auto Context::DiagnoseNameNotFound(Parse::Node parse_node,
  80. SemIR::NameId name_id) -> void {
  81. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.",
  82. llvm::StringRef);
  83. emitter_->Emit(parse_node, NameNotFound, names().GetFormatted(name_id));
  84. }
  85. auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
  86. DiagnosticBuilder& builder) -> void {
  87. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  88. "Class was forward declared here.");
  89. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  90. "Class is incomplete within its definition.");
  91. const auto& class_info = classes().Get(class_id);
  92. CARBON_CHECK(!class_info.is_defined()) << "Class is not incomplete";
  93. if (class_info.definition_id.is_valid()) {
  94. builder.Note(insts().Get(class_info.definition_id).parse_node(),
  95. ClassIncompleteWithinDefinition);
  96. } else {
  97. builder.Note(insts().Get(class_info.decl_id).parse_node(),
  98. ClassForwardDeclaredHere);
  99. }
  100. }
  101. auto Context::AddNameToLookup(Parse::Node name_node, SemIR::NameId name_id,
  102. SemIR::InstId target_id) -> void {
  103. if (current_scope().names.insert(name_id).second) {
  104. // TODO: Reject if we previously performed a failed lookup for this name in
  105. // this scope or a scope nested within it.
  106. auto& lexical_results = name_lookup_[name_id];
  107. CARBON_CHECK(lexical_results.empty() ||
  108. lexical_results.back().scope_index < current_scope_index())
  109. << "Failed to clean up after scope nested within the current scope";
  110. lexical_results.push_back(
  111. {.node_id = target_id, .scope_index = current_scope_index()});
  112. } else {
  113. DiagnoseDuplicateName(name_node, name_lookup_[name_id].back().node_id);
  114. }
  115. }
  116. auto Context::LookupNameInDecl(Parse::Node parse_node, SemIR::NameId name_id,
  117. SemIR::NameScopeId scope_id) -> SemIR::InstId {
  118. if (scope_id == SemIR::NameScopeId::Invalid) {
  119. // Look for a name in the current scope only. There are two cases where the
  120. // name would be in an outer scope:
  121. //
  122. // - The name is the sole component of the declared name:
  123. //
  124. // class A;
  125. // fn F() {
  126. // class A;
  127. // }
  128. //
  129. // In this case, the inner A is not the same class as the outer A, so
  130. // lookup should not find the outer A.
  131. //
  132. // - The name is a qualifier of some larger declared name:
  133. //
  134. // class A { class B; }
  135. // fn F() {
  136. // class A.B {}
  137. // }
  138. //
  139. // In this case, we're not in the correct scope to define a member of
  140. // class A, so we should reject, and we achieve this by not finding the
  141. // name A from the outer scope.
  142. if (auto name_it = name_lookup_.find(name_id);
  143. name_it != name_lookup_.end()) {
  144. CARBON_CHECK(!name_it->second.empty())
  145. << "Should have been erased: " << names().GetFormatted(name_id);
  146. auto result = name_it->second.back();
  147. if (result.scope_index == current_scope_index()) {
  148. return result.node_id;
  149. }
  150. }
  151. return SemIR::InstId::Invalid;
  152. } else {
  153. // TODO: Once we support `extend`, do not look into `extend`ed scopes here,
  154. // following the same logic as above.
  155. return LookupQualifiedName(parse_node, name_id, scope_id,
  156. /*required=*/false);
  157. }
  158. }
  159. auto Context::LookupUnqualifiedName(Parse::Node parse_node,
  160. SemIR::NameId name_id) -> SemIR::InstId {
  161. // TODO: Check for shadowed lookup results.
  162. // Find the results from enclosing lexical scopes. These will be combined with
  163. // results from non-lexical scopes such as namespaces and classes.
  164. llvm::ArrayRef<LexicalLookupResult> lexical_results;
  165. if (auto name_it = name_lookup_.find(name_id);
  166. name_it != name_lookup_.end()) {
  167. lexical_results = name_it->second;
  168. CARBON_CHECK(!lexical_results.empty())
  169. << "Should have been erased: " << names().GetFormatted(name_id);
  170. }
  171. // Walk the non-lexical scopes and perform lookups into each of them.
  172. for (auto [index, name_scope_id] : llvm::reverse(non_lexical_scope_stack_)) {
  173. // If the innermost lexical result is within this non-lexical scope, then
  174. // it shadows all further non-lexical results and we're done.
  175. if (!lexical_results.empty() &&
  176. lexical_results.back().scope_index > index) {
  177. return lexical_results.back().node_id;
  178. }
  179. auto non_lexical_result =
  180. LookupQualifiedName(parse_node, name_id, name_scope_id,
  181. /*required=*/false);
  182. if (non_lexical_result.is_valid()) {
  183. return non_lexical_result;
  184. }
  185. }
  186. if (!lexical_results.empty()) {
  187. return lexical_results.back().node_id;
  188. }
  189. // We didn't find anything at all.
  190. DiagnoseNameNotFound(parse_node, name_id);
  191. return SemIR::InstId::BuiltinError;
  192. }
  193. auto Context::LookupQualifiedName(Parse::Node parse_node, SemIR::NameId name_id,
  194. SemIR::NameScopeId scope_id, bool required)
  195. -> SemIR::InstId {
  196. CARBON_CHECK(scope_id.is_valid()) << "No scope to perform lookup into";
  197. const auto& scope = name_scopes().Get(scope_id);
  198. auto it = scope.find(name_id);
  199. if (it == scope.end()) {
  200. // TODO: Also perform lookups into `extend`ed scopes.
  201. if (required) {
  202. DiagnoseNameNotFound(parse_node, name_id);
  203. return SemIR::InstId::BuiltinError;
  204. }
  205. return SemIR::InstId::Invalid;
  206. }
  207. return it->second;
  208. }
  209. auto Context::PushScope(SemIR::InstId scope_inst_id,
  210. SemIR::NameScopeId scope_id) -> void {
  211. scope_stack_.push_back({.index = next_scope_index_,
  212. .scope_inst_id = scope_inst_id,
  213. .scope_id = scope_id});
  214. if (scope_id.is_valid()) {
  215. non_lexical_scope_stack_.push_back({next_scope_index_, scope_id});
  216. }
  217. // TODO: Handle this case more gracefully.
  218. CARBON_CHECK(next_scope_index_.index != std::numeric_limits<int32_t>::max())
  219. << "Ran out of scopes";
  220. ++next_scope_index_.index;
  221. }
  222. auto Context::PopScope() -> void {
  223. auto scope = scope_stack_.pop_back_val();
  224. for (const auto& str_id : scope.names) {
  225. auto it = name_lookup_.find(str_id);
  226. CARBON_CHECK(it->second.back().scope_index == scope.index)
  227. << "Inconsistent scope index for name " << names().GetFormatted(str_id);
  228. if (it->second.size() == 1) {
  229. // Erase names that no longer resolve.
  230. name_lookup_.erase(it);
  231. } else {
  232. it->second.pop_back();
  233. }
  234. }
  235. if (scope.scope_id.is_valid()) {
  236. CARBON_CHECK(non_lexical_scope_stack_.back().first == scope.index);
  237. non_lexical_scope_stack_.pop_back();
  238. }
  239. if (scope.has_returned_var) {
  240. CARBON_CHECK(!return_scope_stack_.empty());
  241. CARBON_CHECK(return_scope_stack_.back().returned_var.is_valid());
  242. return_scope_stack_.back().returned_var = SemIR::InstId::Invalid;
  243. }
  244. }
  245. auto Context::PopToScope(ScopeIndex index) -> void {
  246. while (current_scope_index() > index) {
  247. PopScope();
  248. }
  249. CARBON_CHECK(current_scope_index() == index)
  250. << "Scope index " << index << " does not enclose the current scope "
  251. << current_scope_index();
  252. }
  253. auto Context::SetReturnedVarOrGetExisting(SemIR::InstId inst_id)
  254. -> SemIR::InstId {
  255. CARBON_CHECK(!return_scope_stack_.empty()) << "`returned var` in no function";
  256. auto& returned_var = return_scope_stack_.back().returned_var;
  257. if (returned_var.is_valid()) {
  258. return returned_var;
  259. }
  260. returned_var = inst_id;
  261. CARBON_CHECK(!current_scope().has_returned_var)
  262. << "Scope has returned var but none is set";
  263. if (inst_id.is_valid()) {
  264. current_scope().has_returned_var = true;
  265. }
  266. return SemIR::InstId::Invalid;
  267. }
  268. auto Context::FollowNameReferences(SemIR::InstId inst_id) -> SemIR::InstId {
  269. while (auto name_ref = insts().Get(inst_id).TryAs<SemIR::NameReference>()) {
  270. inst_id = name_ref->value_id;
  271. }
  272. return inst_id;
  273. }
  274. auto Context::GetConstantValue(SemIR::InstId inst_id) -> SemIR::InstId {
  275. // TODO: The constant value of an instruction should be computed as we build
  276. // the instruction, or at least cached once computed.
  277. while (true) {
  278. auto inst = insts().Get(inst_id);
  279. switch (inst.kind()) {
  280. case SemIR::NameReference::Kind:
  281. inst_id = inst.As<SemIR::NameReference>().value_id;
  282. break;
  283. case SemIR::BindName::Kind:
  284. inst_id = inst.As<SemIR::BindName>().value_id;
  285. break;
  286. case SemIR::Field::Kind:
  287. case SemIR::FunctionDecl::Kind:
  288. return inst_id;
  289. default:
  290. // TODO: Handle the remaining cases.
  291. return SemIR::InstId::Invalid;
  292. }
  293. }
  294. }
  295. template <typename BranchNode, typename... Args>
  296. static auto AddDominatedBlockAndBranchImpl(Context& context,
  297. Parse::Node parse_node, Args... args)
  298. -> SemIR::InstBlockId {
  299. if (!context.inst_block_stack().is_current_block_reachable()) {
  300. return SemIR::InstBlockId::Unreachable;
  301. }
  302. auto block_id = context.inst_blocks().AddDefaultValue();
  303. context.AddInst(BranchNode{parse_node, block_id, args...});
  304. return block_id;
  305. }
  306. auto Context::AddDominatedBlockAndBranch(Parse::Node parse_node)
  307. -> SemIR::InstBlockId {
  308. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, parse_node);
  309. }
  310. auto Context::AddDominatedBlockAndBranchWithArg(Parse::Node parse_node,
  311. SemIR::InstId arg_id)
  312. -> SemIR::InstBlockId {
  313. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, parse_node,
  314. arg_id);
  315. }
  316. auto Context::AddDominatedBlockAndBranchIf(Parse::Node parse_node,
  317. SemIR::InstId cond_id)
  318. -> SemIR::InstBlockId {
  319. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, parse_node,
  320. cond_id);
  321. }
  322. auto Context::AddConvergenceBlockAndPush(Parse::Node parse_node, int num_blocks)
  323. -> void {
  324. CARBON_CHECK(num_blocks >= 2) << "no convergence";
  325. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  326. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  327. if (inst_block_stack().is_current_block_reachable()) {
  328. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  329. new_block_id = inst_blocks().AddDefaultValue();
  330. }
  331. AddInst(SemIR::Branch{parse_node, new_block_id});
  332. }
  333. inst_block_stack().Pop();
  334. }
  335. inst_block_stack().Push(new_block_id);
  336. }
  337. auto Context::AddConvergenceBlockWithArgAndPush(
  338. Parse::Node parse_node, std::initializer_list<SemIR::InstId> block_args)
  339. -> SemIR::InstId {
  340. CARBON_CHECK(block_args.size() >= 2) << "no convergence";
  341. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  342. for (auto arg_id : block_args) {
  343. if (inst_block_stack().is_current_block_reachable()) {
  344. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  345. new_block_id = inst_blocks().AddDefaultValue();
  346. }
  347. AddInst(SemIR::BranchWithArg{parse_node, new_block_id, arg_id});
  348. }
  349. inst_block_stack().Pop();
  350. }
  351. inst_block_stack().Push(new_block_id);
  352. // Acquire the result value.
  353. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  354. return AddInst(SemIR::BlockArg{parse_node, result_type_id, new_block_id});
  355. }
  356. // Add the current code block to the enclosing function.
  357. auto Context::AddCurrentCodeBlockToFunction(Parse::Node parse_node) -> void {
  358. CARBON_CHECK(!inst_block_stack().empty()) << "no current code block";
  359. if (return_scope_stack().empty()) {
  360. CARBON_CHECK(parse_node.is_valid())
  361. << "No current function, but parse_node not provided";
  362. TODO(parse_node,
  363. "Control flow expressions are currently only supported inside "
  364. "functions.");
  365. return;
  366. }
  367. if (!inst_block_stack().is_current_block_reachable()) {
  368. // Don't include unreachable blocks in the function.
  369. return;
  370. }
  371. auto function_id =
  372. insts()
  373. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  374. .function_id;
  375. functions()
  376. .Get(function_id)
  377. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  378. }
  379. auto Context::is_current_position_reachable() -> bool {
  380. if (!inst_block_stack().is_current_block_reachable()) {
  381. return false;
  382. }
  383. // Our current position is at the end of a reachable block. That position is
  384. // reachable unless the previous instruction is a terminator instruction.
  385. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  386. if (block_contents.empty()) {
  387. return true;
  388. }
  389. const auto& last_inst = insts().Get(block_contents.back());
  390. return last_inst.kind().terminator_kind() !=
  391. SemIR::TerminatorKind::Terminator;
  392. }
  393. auto Context::ParamOrArgStart() -> void { params_or_args_stack_.Push(); }
  394. auto Context::ParamOrArgComma() -> void {
  395. ParamOrArgSave(node_stack_.PopExpr());
  396. }
  397. auto Context::ParamOrArgEndNoPop(Parse::NodeKind start_kind) -> void {
  398. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  399. ParamOrArgSave(node_stack_.PopExpr());
  400. }
  401. }
  402. auto Context::ParamOrArgPop() -> SemIR::InstBlockId {
  403. return params_or_args_stack_.Pop();
  404. }
  405. auto Context::ParamOrArgEnd(Parse::NodeKind start_kind) -> SemIR::InstBlockId {
  406. ParamOrArgEndNoPop(start_kind);
  407. return ParamOrArgPop();
  408. }
  409. namespace {
  410. // Worklist-based type completion mechanism.
  411. //
  412. // When attempting to complete a type, we may find other types that also need to
  413. // be completed: types nested within that type, and the value representation of
  414. // the type. In order to complete a type without recursing arbitrarily deeply,
  415. // we use a worklist of tasks:
  416. //
  417. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  418. // nested within a type to the work list.
  419. // - A `BuildValueRepresentation` step computes the value representation for a
  420. // type, once all of its nested types are complete, and marks the type as
  421. // complete.
  422. class TypeCompleter {
  423. public:
  424. TypeCompleter(
  425. Context& context,
  426. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  427. diagnoser)
  428. : context_(context), diagnoser_(diagnoser) {}
  429. // Attempts to complete the given type. Returns true if it is now complete,
  430. // false if it could not be completed.
  431. auto Complete(SemIR::TypeId type_id) -> bool {
  432. Push(type_id);
  433. while (!work_list_.empty()) {
  434. if (!ProcessStep()) {
  435. return false;
  436. }
  437. }
  438. return true;
  439. }
  440. private:
  441. // Adds `type_id` to the work list, if it's not already complete.
  442. auto Push(SemIR::TypeId type_id) -> void {
  443. if (!context_.sem_ir().IsTypeComplete(type_id)) {
  444. work_list_.push_back({type_id, Phase::AddNestedIncompleteTypes});
  445. }
  446. }
  447. // Runs the next step.
  448. auto ProcessStep() -> bool {
  449. auto [type_id, phase] = work_list_.back();
  450. // We might have enqueued the same type more than once. Just skip the
  451. // type if it's already complete.
  452. if (context_.sem_ir().IsTypeComplete(type_id)) {
  453. work_list_.pop_back();
  454. return true;
  455. }
  456. auto inst_id = context_.sem_ir().GetTypeAllowBuiltinTypes(type_id);
  457. auto inst = context_.insts().Get(inst_id);
  458. auto old_work_list_size = work_list_.size();
  459. switch (phase) {
  460. case Phase::AddNestedIncompleteTypes:
  461. if (!AddNestedIncompleteTypes(inst)) {
  462. return false;
  463. }
  464. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  465. << "AddNestedIncompleteTypes should not remove work items";
  466. work_list_[old_work_list_size - 1].phase =
  467. Phase::BuildValueRepresentation;
  468. break;
  469. case Phase::BuildValueRepresentation: {
  470. auto value_rep = BuildValueRepresentation(type_id, inst);
  471. context_.sem_ir().CompleteType(type_id, value_rep);
  472. CARBON_CHECK(old_work_list_size == work_list_.size())
  473. << "BuildValueRepresentation should not change work items";
  474. work_list_.pop_back();
  475. // Also complete the value representation type, if necessary. This
  476. // should never fail: the value representation shouldn't require any
  477. // additional nested types to be complete.
  478. if (!context_.sem_ir().IsTypeComplete(value_rep.type_id)) {
  479. work_list_.push_back(
  480. {value_rep.type_id, Phase::BuildValueRepresentation});
  481. }
  482. // For a pointer representation, the pointee also needs to be complete.
  483. if (value_rep.kind == SemIR::ValueRepresentation::Pointer) {
  484. auto pointee_type_id =
  485. context_.sem_ir().GetPointeeType(value_rep.type_id);
  486. if (!context_.sem_ir().IsTypeComplete(pointee_type_id)) {
  487. work_list_.push_back(
  488. {pointee_type_id, Phase::BuildValueRepresentation});
  489. }
  490. }
  491. break;
  492. }
  493. }
  494. return true;
  495. }
  496. // Adds any types nested within `type_inst` that need to be complete for
  497. // `type_inst` to be complete to our work list.
  498. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  499. switch (type_inst.kind()) {
  500. case SemIR::ArrayType::Kind:
  501. Push(type_inst.As<SemIR::ArrayType>().element_type_id);
  502. break;
  503. case SemIR::StructType::Kind:
  504. for (auto field_id : context_.inst_blocks().Get(
  505. type_inst.As<SemIR::StructType>().fields_id)) {
  506. Push(context_.insts()
  507. .GetAs<SemIR::StructTypeField>(field_id)
  508. .field_type_id);
  509. }
  510. break;
  511. case SemIR::TupleType::Kind:
  512. for (auto element_type_id : context_.type_blocks().Get(
  513. type_inst.As<SemIR::TupleType>().elements_id)) {
  514. Push(element_type_id);
  515. }
  516. break;
  517. case SemIR::ClassType::Kind: {
  518. auto class_type = type_inst.As<SemIR::ClassType>();
  519. auto& class_info = context_.classes().Get(class_type.class_id);
  520. if (!class_info.is_defined()) {
  521. if (diagnoser_) {
  522. auto builder = (*diagnoser_)();
  523. context_.NoteIncompleteClass(class_type.class_id, builder);
  524. builder.Emit();
  525. }
  526. return false;
  527. }
  528. Push(class_info.object_representation_id);
  529. break;
  530. }
  531. case SemIR::ConstType::Kind:
  532. Push(type_inst.As<SemIR::ConstType>().inner_id);
  533. break;
  534. default:
  535. break;
  536. }
  537. return true;
  538. }
  539. // Makes an empty value representation, which is used for types that have no
  540. // state, such as empty structs and tuples.
  541. auto MakeEmptyRepresentation(Parse::Node parse_node) const
  542. -> SemIR::ValueRepresentation {
  543. return {.kind = SemIR::ValueRepresentation::None,
  544. .type_id = context_.CanonicalizeTupleType(parse_node, {})};
  545. }
  546. // Makes a value representation that uses pass-by-copy, copying the given
  547. // type.
  548. auto MakeCopyRepresentation(
  549. SemIR::TypeId rep_id,
  550. SemIR::ValueRepresentation::AggregateKind aggregate_kind =
  551. SemIR::ValueRepresentation::NotAggregate) const
  552. -> SemIR::ValueRepresentation {
  553. return {.kind = SemIR::ValueRepresentation::Copy,
  554. .aggregate_kind = aggregate_kind,
  555. .type_id = rep_id};
  556. }
  557. // Makes a value representation that uses pass-by-address with the given
  558. // pointee type.
  559. auto MakePointerRepresentation(
  560. Parse::Node parse_node, SemIR::TypeId pointee_id,
  561. SemIR::ValueRepresentation::AggregateKind aggregate_kind =
  562. SemIR::ValueRepresentation::NotAggregate) const
  563. -> SemIR::ValueRepresentation {
  564. // TODO: Should we add `const` qualification to `pointee_id`?
  565. return {.kind = SemIR::ValueRepresentation::Pointer,
  566. .aggregate_kind = aggregate_kind,
  567. .type_id = context_.GetPointerType(parse_node, pointee_id)};
  568. }
  569. // Gets the value representation of a nested type, which should already be
  570. // complete.
  571. auto GetNestedValueRepresentation(SemIR::TypeId nested_type_id) const {
  572. CARBON_CHECK(context_.sem_ir().IsTypeComplete(nested_type_id))
  573. << "Nested type should already be complete";
  574. auto value_rep = context_.sem_ir().GetValueRepresentation(nested_type_id);
  575. CARBON_CHECK(value_rep.kind != SemIR::ValueRepresentation::Unknown)
  576. << "Complete type should have a value representation";
  577. return value_rep;
  578. };
  579. auto BuildCrossReferenceValueRepresentation(SemIR::TypeId type_id,
  580. SemIR::CrossReference xref) const
  581. -> SemIR::ValueRepresentation {
  582. auto xref_inst = context_.sem_ir()
  583. .GetCrossReferenceIR(xref.ir_id)
  584. .insts()
  585. .Get(xref.inst_id);
  586. // The canonical description of a type should only have cross-references
  587. // for entities owned by another File, such as builtins, which are owned
  588. // by the prelude, and named entities like classes and interfaces, which
  589. // we don't support yet.
  590. CARBON_CHECK(xref_inst.kind() == SemIR::Builtin::Kind)
  591. << "TODO: Handle other kinds of inst cross-references";
  592. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  593. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  594. switch (xref_inst.As<SemIR::Builtin>().builtin_kind) {
  595. case SemIR::BuiltinKind::TypeType:
  596. case SemIR::BuiltinKind::Error:
  597. case SemIR::BuiltinKind::Invalid:
  598. case SemIR::BuiltinKind::BoolType:
  599. case SemIR::BuiltinKind::IntegerType:
  600. case SemIR::BuiltinKind::FloatingPointType:
  601. case SemIR::BuiltinKind::NamespaceType:
  602. case SemIR::BuiltinKind::FunctionType:
  603. case SemIR::BuiltinKind::BoundMethodType:
  604. return MakeCopyRepresentation(type_id);
  605. case SemIR::BuiltinKind::StringType:
  606. // TODO: Decide on string value semantics. This should probably be a
  607. // custom value representation carrying a pointer and size or
  608. // similar.
  609. return MakePointerRepresentation(Parse::Node::Invalid, type_id);
  610. }
  611. llvm_unreachable("All builtin kinds were handled above");
  612. }
  613. auto BuildStructOrTupleValueRepresentation(Parse::Node parse_node,
  614. std::size_t num_elements,
  615. SemIR::TypeId elementwise_rep,
  616. bool same_as_object_rep) const
  617. -> SemIR::ValueRepresentation {
  618. SemIR::ValueRepresentation::AggregateKind aggregate_kind =
  619. same_as_object_rep ? SemIR::ValueRepresentation::ValueAndObjectAggregate
  620. : SemIR::ValueRepresentation::ValueAggregate;
  621. if (num_elements == 1) {
  622. // The value representation for a struct or tuple with a single element
  623. // is a struct or tuple containing the value representation of the
  624. // element.
  625. // TODO: Consider doing the same whenever `elementwise_rep` is
  626. // sufficiently small.
  627. return MakeCopyRepresentation(elementwise_rep, aggregate_kind);
  628. }
  629. // For a struct or tuple with multiple fields, we use a pointer
  630. // to the elementwise value representation.
  631. return MakePointerRepresentation(parse_node, elementwise_rep,
  632. aggregate_kind);
  633. }
  634. auto BuildStructTypeValueRepresentation(SemIR::TypeId type_id,
  635. SemIR::StructType struct_type) const
  636. -> SemIR::ValueRepresentation {
  637. // TODO: Share more code with tuples.
  638. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  639. if (fields.empty()) {
  640. return MakeEmptyRepresentation(struct_type.parse_node);
  641. }
  642. // Find the value representation for each field, and construct a struct
  643. // of value representations.
  644. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  645. value_rep_fields.reserve(fields.size());
  646. bool same_as_object_rep = true;
  647. for (auto field_id : fields) {
  648. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  649. auto field_value_rep = GetNestedValueRepresentation(field.field_type_id);
  650. if (field_value_rep.type_id != field.field_type_id) {
  651. same_as_object_rep = false;
  652. field.field_type_id = field_value_rep.type_id;
  653. field_id = context_.AddConstantInst(field);
  654. }
  655. value_rep_fields.push_back(field_id);
  656. }
  657. auto value_rep = same_as_object_rep
  658. ? type_id
  659. : context_.CanonicalizeStructType(
  660. struct_type.parse_node,
  661. context_.inst_blocks().Add(value_rep_fields));
  662. return BuildStructOrTupleValueRepresentation(
  663. struct_type.parse_node, fields.size(), value_rep, same_as_object_rep);
  664. }
  665. auto BuildTupleTypeValueRepresentation(SemIR::TypeId type_id,
  666. SemIR::TupleType tuple_type) const
  667. -> SemIR::ValueRepresentation {
  668. // TODO: Share more code with structs.
  669. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  670. if (elements.empty()) {
  671. return MakeEmptyRepresentation(tuple_type.parse_node);
  672. }
  673. // Find the value representation for each element, and construct a tuple
  674. // of value representations.
  675. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  676. value_rep_elements.reserve(elements.size());
  677. bool same_as_object_rep = true;
  678. for (auto element_type_id : elements) {
  679. auto element_value_rep = GetNestedValueRepresentation(element_type_id);
  680. if (element_value_rep.type_id != element_type_id) {
  681. same_as_object_rep = false;
  682. }
  683. value_rep_elements.push_back(element_value_rep.type_id);
  684. }
  685. auto value_rep = same_as_object_rep
  686. ? type_id
  687. : context_.CanonicalizeTupleType(tuple_type.parse_node,
  688. value_rep_elements);
  689. return BuildStructOrTupleValueRepresentation(
  690. tuple_type.parse_node, elements.size(), value_rep, same_as_object_rep);
  691. }
  692. // Builds and returns the value representation for the given type. All nested
  693. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  694. auto BuildValueRepresentation(SemIR::TypeId type_id, SemIR::Inst inst) const
  695. -> SemIR::ValueRepresentation {
  696. // TODO: This can emit new SemIR instructions. Consider emitting them into a
  697. // dedicated file-scope instruction block where possible, or somewhere else
  698. // that better reflects the definition of the type, rather than wherever the
  699. // type happens to first be required to be complete.
  700. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  701. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  702. switch (inst.kind()) {
  703. case SemIR::AddressOf::Kind:
  704. case SemIR::ArrayIndex::Kind:
  705. case SemIR::ArrayInit::Kind:
  706. case SemIR::Assign::Kind:
  707. case SemIR::BinaryOperatorAdd::Kind:
  708. case SemIR::BindName::Kind:
  709. case SemIR::BindValue::Kind:
  710. case SemIR::BlockArg::Kind:
  711. case SemIR::BoolLiteral::Kind:
  712. case SemIR::BoundMethod::Kind:
  713. case SemIR::Branch::Kind:
  714. case SemIR::BranchIf::Kind:
  715. case SemIR::BranchWithArg::Kind:
  716. case SemIR::Call::Kind:
  717. case SemIR::ClassDecl::Kind:
  718. case SemIR::ClassFieldAccess::Kind:
  719. case SemIR::ClassInit::Kind:
  720. case SemIR::Converted::Kind:
  721. case SemIR::Dereference::Kind:
  722. case SemIR::Field::Kind:
  723. case SemIR::FunctionDecl::Kind:
  724. case SemIR::InitializeFrom::Kind:
  725. case SemIR::IntegerLiteral::Kind:
  726. case SemIR::NameReference::Kind:
  727. case SemIR::Namespace::Kind:
  728. case SemIR::NoOp::Kind:
  729. case SemIR::Parameter::Kind:
  730. case SemIR::RealLiteral::Kind:
  731. case SemIR::Return::Kind:
  732. case SemIR::ReturnExpr::Kind:
  733. case SemIR::SelfParameter::Kind:
  734. case SemIR::SpliceBlock::Kind:
  735. case SemIR::StringLiteral::Kind:
  736. case SemIR::StructAccess::Kind:
  737. case SemIR::StructTypeField::Kind:
  738. case SemIR::StructLiteral::Kind:
  739. case SemIR::StructInit::Kind:
  740. case SemIR::StructValue::Kind:
  741. case SemIR::Temporary::Kind:
  742. case SemIR::TemporaryStorage::Kind:
  743. case SemIR::TupleAccess::Kind:
  744. case SemIR::TupleIndex::Kind:
  745. case SemIR::TupleLiteral::Kind:
  746. case SemIR::TupleInit::Kind:
  747. case SemIR::TupleValue::Kind:
  748. case SemIR::UnaryOperatorNot::Kind:
  749. case SemIR::ValueAsReference::Kind:
  750. case SemIR::ValueOfInitializer::Kind:
  751. case SemIR::VarStorage::Kind:
  752. CARBON_FATAL() << "Type refers to non-type inst " << inst;
  753. case SemIR::CrossReference::Kind:
  754. return BuildCrossReferenceValueRepresentation(
  755. type_id, inst.As<SemIR::CrossReference>());
  756. case SemIR::ArrayType::Kind: {
  757. // For arrays, it's convenient to always use a pointer representation,
  758. // even when the array has zero or one element, in order to support
  759. // indexing.
  760. return MakePointerRepresentation(
  761. inst.parse_node(), type_id,
  762. SemIR::ValueRepresentation::ObjectAggregate);
  763. }
  764. case SemIR::StructType::Kind:
  765. return BuildStructTypeValueRepresentation(type_id,
  766. inst.As<SemIR::StructType>());
  767. case SemIR::TupleType::Kind:
  768. return BuildTupleTypeValueRepresentation(type_id,
  769. inst.As<SemIR::TupleType>());
  770. case SemIR::ClassType::Kind:
  771. // The value representation for a class is a pointer to the object
  772. // representation.
  773. // TODO: Support customized value representations for classes.
  774. // TODO: Pick a better value representation when possible.
  775. return MakePointerRepresentation(
  776. inst.parse_node(),
  777. context_.classes()
  778. .Get(inst.As<SemIR::ClassType>().class_id)
  779. .object_representation_id,
  780. SemIR::ValueRepresentation::ObjectAggregate);
  781. case SemIR::Builtin::Kind:
  782. CARBON_FATAL() << "Builtins should be named as cross-references";
  783. case SemIR::PointerType::Kind:
  784. case SemIR::UnboundFieldType::Kind:
  785. return MakeCopyRepresentation(type_id);
  786. case SemIR::ConstType::Kind:
  787. // The value representation of `const T` is the same as that of `T`.
  788. // Objects are not modifiable through their value representations.
  789. return GetNestedValueRepresentation(
  790. inst.As<SemIR::ConstType>().inner_id);
  791. }
  792. }
  793. enum class Phase : int8_t {
  794. // The next step is to add nested types to the list of types to complete.
  795. AddNestedIncompleteTypes,
  796. // The next step is to build the value representation for the type.
  797. BuildValueRepresentation,
  798. };
  799. struct WorkItem {
  800. SemIR::TypeId type_id;
  801. Phase phase;
  802. };
  803. Context& context_;
  804. llvm::SmallVector<WorkItem> work_list_;
  805. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  806. diagnoser_;
  807. };
  808. } // namespace
  809. auto Context::TryToCompleteType(
  810. SemIR::TypeId type_id,
  811. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  812. -> bool {
  813. return TypeCompleter(*this, diagnoser).Complete(type_id);
  814. }
  815. auto Context::CanonicalizeTypeImpl(
  816. SemIR::InstKind kind,
  817. llvm::function_ref<bool(llvm::FoldingSetNodeID& canonical_id)> profile_type,
  818. llvm::function_ref<SemIR::InstId()> make_inst) -> SemIR::TypeId {
  819. llvm::FoldingSetNodeID canonical_id;
  820. kind.Profile(canonical_id);
  821. if (!profile_type(canonical_id)) {
  822. return SemIR::TypeId::Error;
  823. }
  824. void* insert_pos;
  825. auto* node =
  826. canonical_type_nodes_.FindNodeOrInsertPos(canonical_id, insert_pos);
  827. if (node != nullptr) {
  828. return node->type_id();
  829. }
  830. auto inst_id = make_inst();
  831. auto type_id = types().Add({.inst_id = inst_id});
  832. CARBON_CHECK(canonical_types_.insert({inst_id, type_id}).second);
  833. type_node_storage_.push_back(
  834. std::make_unique<TypeNode>(canonical_id, type_id));
  835. // In a debug build, check that our insertion position is still valid. It
  836. // could have been invalidated by a misbehaving `make_inst`.
  837. CARBON_DCHECK([&] {
  838. void* check_insert_pos;
  839. auto* check_node = canonical_type_nodes_.FindNodeOrInsertPos(
  840. canonical_id, check_insert_pos);
  841. return !check_node && insert_pos == check_insert_pos;
  842. }()) << "Type was created recursively during canonicalization";
  843. canonical_type_nodes_.InsertNode(type_node_storage_.back().get(), insert_pos);
  844. return type_id;
  845. }
  846. // Compute a fingerprint for a tuple type, for use as a key in a folding set.
  847. static auto ProfileTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids,
  848. llvm::FoldingSetNodeID& canonical_id) -> void {
  849. for (auto type_id : type_ids) {
  850. canonical_id.AddInteger(type_id.index);
  851. }
  852. }
  853. // Compute a fingerprint for a type, for use as a key in a folding set. Returns
  854. // false if not supported, which is presently the case for compile-time
  855. // expressions.
  856. // TODO: Once support is more complete, in particular ensuring that various
  857. // valid compile-time expressions are supported, it may be desirable to switch
  858. // the default to a CARBON_FATAL error.
  859. static auto ProfileType(Context& semantics_context, SemIR::Inst inst,
  860. llvm::FoldingSetNodeID& canonical_id) -> bool {
  861. switch (inst.kind()) {
  862. case SemIR::ArrayType::Kind: {
  863. auto array_type = inst.As<SemIR::ArrayType>();
  864. canonical_id.AddInteger(
  865. semantics_context.sem_ir().GetArrayBoundValue(array_type.bound_id));
  866. canonical_id.AddInteger(array_type.element_type_id.index);
  867. break;
  868. }
  869. case SemIR::Builtin::Kind:
  870. canonical_id.AddInteger(inst.As<SemIR::Builtin>().builtin_kind.AsInt());
  871. break;
  872. case SemIR::ClassType::Kind:
  873. canonical_id.AddInteger(inst.As<SemIR::ClassType>().class_id.index);
  874. break;
  875. case SemIR::CrossReference::Kind: {
  876. // TODO: Cross-references should be canonicalized by looking at their
  877. // target rather than treating them as new unique types.
  878. auto xref = inst.As<SemIR::CrossReference>();
  879. canonical_id.AddInteger(xref.ir_id.index);
  880. canonical_id.AddInteger(xref.inst_id.index);
  881. break;
  882. }
  883. case SemIR::ConstType::Kind:
  884. canonical_id.AddInteger(
  885. semantics_context
  886. .GetUnqualifiedType(inst.As<SemIR::ConstType>().inner_id)
  887. .index);
  888. break;
  889. case SemIR::PointerType::Kind:
  890. canonical_id.AddInteger(inst.As<SemIR::PointerType>().pointee_id.index);
  891. break;
  892. case SemIR::StructType::Kind: {
  893. auto fields = semantics_context.inst_blocks().Get(
  894. inst.As<SemIR::StructType>().fields_id);
  895. for (const auto& field_id : fields) {
  896. auto field =
  897. semantics_context.insts().GetAs<SemIR::StructTypeField>(field_id);
  898. canonical_id.AddInteger(field.name_id.index);
  899. canonical_id.AddInteger(field.field_type_id.index);
  900. }
  901. break;
  902. }
  903. case SemIR::TupleType::Kind:
  904. ProfileTupleType(semantics_context.type_blocks().Get(
  905. inst.As<SemIR::TupleType>().elements_id),
  906. canonical_id);
  907. break;
  908. case SemIR::UnboundFieldType::Kind: {
  909. auto unbound_field_type = inst.As<SemIR::UnboundFieldType>();
  910. canonical_id.AddInteger(unbound_field_type.class_type_id.index);
  911. canonical_id.AddInteger(unbound_field_type.field_type_id.index);
  912. break;
  913. }
  914. default: {
  915. // Right now, this is only expected to occur in calls from
  916. // ExprAsType. Diagnostics are issued there.
  917. return false;
  918. }
  919. }
  920. return true;
  921. }
  922. auto Context::CanonicalizeTypeAndAddInstIfNew(SemIR::Inst inst)
  923. -> SemIR::TypeId {
  924. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  925. return ProfileType(*this, inst, canonical_id);
  926. };
  927. auto make_inst = [&] { return AddConstantInst(inst); };
  928. return CanonicalizeTypeImpl(inst.kind(), profile_node, make_inst);
  929. }
  930. auto Context::CanonicalizeType(SemIR::InstId inst_id) -> SemIR::TypeId {
  931. while (auto converted = insts().Get(inst_id).TryAs<SemIR::Converted>()) {
  932. inst_id = converted->result_id;
  933. }
  934. inst_id = FollowNameReferences(inst_id);
  935. auto it = canonical_types_.find(inst_id);
  936. if (it != canonical_types_.end()) {
  937. return it->second;
  938. }
  939. auto inst = insts().Get(inst_id);
  940. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  941. return ProfileType(*this, inst, canonical_id);
  942. };
  943. auto make_inst = [&] { return inst_id; };
  944. return CanonicalizeTypeImpl(inst.kind(), profile_node, make_inst);
  945. }
  946. auto Context::CanonicalizeStructType(Parse::Node parse_node,
  947. SemIR::InstBlockId refs_id)
  948. -> SemIR::TypeId {
  949. return CanonicalizeTypeAndAddInstIfNew(
  950. SemIR::StructType{parse_node, SemIR::TypeId::TypeType, refs_id});
  951. }
  952. auto Context::CanonicalizeTupleType(Parse::Node parse_node,
  953. llvm::ArrayRef<SemIR::TypeId> type_ids)
  954. -> SemIR::TypeId {
  955. // Defer allocating a SemIR::TypeBlockId until we know this is a new type.
  956. auto profile_tuple = [&](llvm::FoldingSetNodeID& canonical_id) {
  957. ProfileTupleType(type_ids, canonical_id);
  958. return true;
  959. };
  960. auto make_tuple_inst = [&] {
  961. return AddConstantInst(SemIR::TupleType{parse_node, SemIR::TypeId::TypeType,
  962. type_blocks().Add(type_ids)});
  963. };
  964. return CanonicalizeTypeImpl(SemIR::TupleType::Kind, profile_tuple,
  965. make_tuple_inst);
  966. }
  967. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  968. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  969. auto type_id = CanonicalizeType(SemIR::InstId::ForBuiltin(kind));
  970. // To keep client code simpler, complete builtin types before returning them.
  971. bool complete = TryToCompleteType(type_id);
  972. CARBON_CHECK(complete) << "Failed to complete builtin type";
  973. return type_id;
  974. }
  975. auto Context::GetPointerType(Parse::Node parse_node,
  976. SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  977. return CanonicalizeTypeAndAddInstIfNew(
  978. SemIR::PointerType{parse_node, SemIR::TypeId::TypeType, pointee_type_id});
  979. }
  980. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  981. SemIR::Inst type_inst =
  982. insts().Get(sem_ir_->GetTypeAllowBuiltinTypes(type_id));
  983. if (auto const_type = type_inst.TryAs<SemIR::ConstType>()) {
  984. return const_type->inner_id;
  985. }
  986. return type_id;
  987. }
  988. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  989. node_stack_.PrintForStackDump(output);
  990. inst_block_stack_.PrintForStackDump(output);
  991. params_or_args_stack_.PrintForStackDump(output);
  992. args_type_info_stack_.PrintForStackDump(output);
  993. }
  994. } // namespace Carbon::Check