context.cpp 43 KB

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