context.cpp 44 KB

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