context.cpp 42 KB

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