context.cpp 39 KB

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