context.cpp 38 KB

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