context.cpp 42 KB

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