context.cpp 41 KB

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