context.cpp 42 KB

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