context.cpp 43 KB

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