context.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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 =
  272. import_ir.sem_ir->identifiers().Lookup(identifier);
  273. if (!import_identifier_id.is_valid()) {
  274. // Name doesn't exist in the import IR.
  275. continue;
  276. }
  277. import_name_id = SemIR::NameId::ForIdentifier(import_identifier_id);
  278. }
  279. // Look up the name in the import scope.
  280. const auto& import_scope =
  281. import_ir.sem_ir->name_scopes().Get(import_scope_id);
  282. auto it = import_scope.names.find(import_name_id);
  283. if (it == import_scope.names.end()) {
  284. // Name doesn't exist in the import scope.
  285. continue;
  286. }
  287. auto import_inst_id = context.AddImportRef(import_ir_id, it->second);
  288. TryResolveImportRefUnused(context, import_inst_id);
  289. if (result_id.is_valid()) {
  290. // TODO: Add generalized merge functionality (merge_decls.h?).
  291. context.DiagnoseDuplicateName(import_inst_id, result_id);
  292. } else {
  293. result_id = import_inst_id;
  294. }
  295. }
  296. return result_id;
  297. }
  298. auto Context::LookupNameInExactScope(SemIRLocation loc, SemIR::NameId name_id,
  299. const SemIR::NameScope& scope)
  300. -> SemIR::InstId {
  301. if (auto it = scope.names.find(name_id); it != scope.names.end()) {
  302. TryResolveImportRefUnused(*this, it->second);
  303. return it->second;
  304. }
  305. if (!scope.import_ir_scopes.empty()) {
  306. return LookupInImportIRScopes(*this, loc, name_id, scope);
  307. }
  308. return SemIR::InstId::Invalid;
  309. }
  310. auto Context::LookupQualifiedName(Parse::NodeId node_id, SemIR::NameId name_id,
  311. SemIR::NameScopeId scope_id, bool required)
  312. -> SemIR::InstId {
  313. llvm::SmallVector<SemIR::NameScopeId> scope_ids = {scope_id};
  314. auto result_id = SemIR::InstId::Invalid;
  315. bool has_error = false;
  316. // Walk this scope and, if nothing is found here, the scopes it extends.
  317. while (!scope_ids.empty()) {
  318. const auto& scope = name_scopes().Get(scope_ids.pop_back_val());
  319. has_error |= scope.has_error;
  320. auto scope_result_id = LookupNameInExactScope(node_id, name_id, scope);
  321. if (!scope_result_id.is_valid()) {
  322. // Nothing found in this scope: also look in its extended scopes.
  323. auto extended = llvm::reverse(scope.extended_scopes);
  324. scope_ids.append(extended.begin(), extended.end());
  325. continue;
  326. }
  327. // If this is our second lookup result, diagnose an ambiguity.
  328. if (result_id.is_valid()) {
  329. // TODO: This is currently not reachable because the only scope that can
  330. // extend is a class scope, and it can only extend a single base class.
  331. // Add test coverage once this is possible.
  332. CARBON_DIAGNOSTIC(
  333. NameAmbiguousDueToExtend, Error,
  334. "Ambiguous use of name `{0}` found in multiple extended scopes.",
  335. SemIR::NameId);
  336. emitter_->Emit(node_id, NameAmbiguousDueToExtend, name_id);
  337. // TODO: Add notes pointing to the scopes.
  338. return SemIR::InstId::BuiltinError;
  339. }
  340. result_id = scope_result_id;
  341. }
  342. if (required && !result_id.is_valid()) {
  343. if (!has_error) {
  344. DiagnoseNameNotFound(node_id, name_id);
  345. }
  346. return SemIR::InstId::BuiltinError;
  347. }
  348. return result_id;
  349. }
  350. template <typename BranchNode, typename... Args>
  351. static auto AddDominatedBlockAndBranchImpl(Context& context,
  352. Parse::NodeId node_id, Args... args)
  353. -> SemIR::InstBlockId {
  354. if (!context.inst_block_stack().is_current_block_reachable()) {
  355. return SemIR::InstBlockId::Unreachable;
  356. }
  357. auto block_id = context.inst_blocks().AddDefaultValue();
  358. context.AddInst({node_id, BranchNode{block_id, args...}});
  359. return block_id;
  360. }
  361. auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
  362. -> SemIR::InstBlockId {
  363. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
  364. }
  365. auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  366. SemIR::InstId arg_id)
  367. -> SemIR::InstBlockId {
  368. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
  369. arg_id);
  370. }
  371. auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  372. SemIR::InstId cond_id)
  373. -> SemIR::InstBlockId {
  374. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
  375. cond_id);
  376. }
  377. auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  378. -> void {
  379. CARBON_CHECK(num_blocks >= 2) << "no convergence";
  380. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  381. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  382. if (inst_block_stack().is_current_block_reachable()) {
  383. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  384. new_block_id = inst_blocks().AddDefaultValue();
  385. }
  386. AddInst({node_id, SemIR::Branch{new_block_id}});
  387. }
  388. inst_block_stack().Pop();
  389. }
  390. inst_block_stack().Push(new_block_id);
  391. }
  392. auto Context::AddConvergenceBlockWithArgAndPush(
  393. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  394. -> SemIR::InstId {
  395. CARBON_CHECK(block_args.size() >= 2) << "no convergence";
  396. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  397. for (auto arg_id : block_args) {
  398. if (inst_block_stack().is_current_block_reachable()) {
  399. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  400. new_block_id = inst_blocks().AddDefaultValue();
  401. }
  402. AddInst({node_id, SemIR::BranchWithArg{new_block_id, arg_id}});
  403. }
  404. inst_block_stack().Pop();
  405. }
  406. inst_block_stack().Push(new_block_id);
  407. // Acquire the result value.
  408. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  409. return AddInst({node_id, SemIR::BlockArg{result_type_id, new_block_id}});
  410. }
  411. // Add the current code block to the enclosing function.
  412. auto Context::AddCurrentCodeBlockToFunction(Parse::NodeId node_id) -> void {
  413. CARBON_CHECK(!inst_block_stack().empty()) << "no current code block";
  414. if (return_scope_stack().empty()) {
  415. CARBON_CHECK(node_id.is_valid())
  416. << "No current function, but node_id not provided";
  417. TODO(node_id,
  418. "Control flow expressions are currently only supported inside "
  419. "functions.");
  420. return;
  421. }
  422. if (!inst_block_stack().is_current_block_reachable()) {
  423. // Don't include unreachable blocks in the function.
  424. return;
  425. }
  426. auto function_id =
  427. insts()
  428. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  429. .function_id;
  430. functions()
  431. .Get(function_id)
  432. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  433. }
  434. auto Context::is_current_position_reachable() -> bool {
  435. if (!inst_block_stack().is_current_block_reachable()) {
  436. return false;
  437. }
  438. // Our current position is at the end of a reachable block. That position is
  439. // reachable unless the previous instruction is a terminator instruction.
  440. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  441. if (block_contents.empty()) {
  442. return true;
  443. }
  444. const auto& last_inst = insts().Get(block_contents.back());
  445. return last_inst.kind().terminator_kind() !=
  446. SemIR::TerminatorKind::Terminator;
  447. }
  448. auto Context::FinalizeGlobalInit() -> void {
  449. inst_block_stack().PushGlobalInit();
  450. if (!inst_block_stack().PeekCurrentBlockContents().empty()) {
  451. AddInst({Parse::NodeId::Invalid, SemIR::Return{}});
  452. // Pop the GlobalInit block here to finalize it.
  453. inst_block_stack().Pop();
  454. // __global_init is only added if there are initialization instructions.
  455. auto name_id = sem_ir().identifiers().Add("__global_init");
  456. sem_ir().functions().Add(
  457. {.name_id = SemIR::NameId::ForIdentifier(name_id),
  458. .enclosing_scope_id = SemIR::NameScopeId::Package,
  459. .decl_id = SemIR::InstId::Invalid,
  460. .implicit_param_refs_id = SemIR::InstBlockId::Empty,
  461. .param_refs_id = SemIR::InstBlockId::Empty,
  462. .return_type_id = SemIR::TypeId::Invalid,
  463. .return_slot_id = SemIR::InstId::Invalid,
  464. .body_block_ids = {SemIR::InstBlockId::GlobalInit}});
  465. } else {
  466. inst_block_stack().PopGlobalInit();
  467. }
  468. }
  469. namespace {
  470. // Worklist-based type completion mechanism.
  471. //
  472. // When attempting to complete a type, we may find other types that also need to
  473. // be completed: types nested within that type, and the value representation of
  474. // the type. In order to complete a type without recursing arbitrarily deeply,
  475. // we use a worklist of tasks:
  476. //
  477. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  478. // nested within a type to the work list.
  479. // - A `BuildValueRepr` step computes the value representation for a
  480. // type, once all of its nested types are complete, and marks the type as
  481. // complete.
  482. class TypeCompleter {
  483. public:
  484. TypeCompleter(
  485. Context& context,
  486. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  487. diagnoser)
  488. : context_(context), diagnoser_(diagnoser) {}
  489. // Attempts to complete the given type. Returns true if it is now complete,
  490. // false if it could not be completed.
  491. auto Complete(SemIR::TypeId type_id) -> bool {
  492. Push(type_id);
  493. while (!work_list_.empty()) {
  494. if (!ProcessStep()) {
  495. return false;
  496. }
  497. }
  498. return true;
  499. }
  500. private:
  501. // Adds `type_id` to the work list, if it's not already complete.
  502. auto Push(SemIR::TypeId type_id) -> void {
  503. if (!context_.types().IsComplete(type_id)) {
  504. work_list_.push_back({type_id, Phase::AddNestedIncompleteTypes});
  505. }
  506. }
  507. // Runs the next step.
  508. auto ProcessStep() -> bool {
  509. auto [type_id, phase] = work_list_.back();
  510. // We might have enqueued the same type more than once. Just skip the
  511. // type if it's already complete.
  512. if (context_.types().IsComplete(type_id)) {
  513. work_list_.pop_back();
  514. return true;
  515. }
  516. auto inst_id = context_.types().GetInstId(type_id);
  517. auto inst = context_.insts().Get(inst_id);
  518. auto old_work_list_size = work_list_.size();
  519. switch (phase) {
  520. case Phase::AddNestedIncompleteTypes:
  521. if (!AddNestedIncompleteTypes(inst)) {
  522. return false;
  523. }
  524. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  525. << "AddNestedIncompleteTypes should not remove work items";
  526. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  527. break;
  528. case Phase::BuildValueRepr: {
  529. auto value_rep = BuildValueRepr(type_id, inst);
  530. context_.sem_ir().CompleteType(type_id, value_rep);
  531. CARBON_CHECK(old_work_list_size == work_list_.size())
  532. << "BuildValueRepr should not change work items";
  533. work_list_.pop_back();
  534. // Also complete the value representation type, if necessary. This
  535. // should never fail: the value representation shouldn't require any
  536. // additional nested types to be complete.
  537. if (!context_.types().IsComplete(value_rep.type_id)) {
  538. work_list_.push_back({value_rep.type_id, Phase::BuildValueRepr});
  539. }
  540. // For a pointer representation, the pointee also needs to be complete.
  541. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  542. if (value_rep.type_id == SemIR::TypeId::Error) {
  543. break;
  544. }
  545. auto pointee_type_id =
  546. context_.sem_ir().GetPointeeType(value_rep.type_id);
  547. if (!context_.types().IsComplete(pointee_type_id)) {
  548. work_list_.push_back({pointee_type_id, Phase::BuildValueRepr});
  549. }
  550. }
  551. break;
  552. }
  553. }
  554. return true;
  555. }
  556. // Adds any types nested within `type_inst` that need to be complete for
  557. // `type_inst` to be complete to our work list.
  558. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  559. switch (type_inst.kind()) {
  560. case SemIR::ArrayType::Kind:
  561. Push(type_inst.As<SemIR::ArrayType>().element_type_id);
  562. break;
  563. case SemIR::StructType::Kind:
  564. for (auto field_id : context_.inst_blocks().Get(
  565. type_inst.As<SemIR::StructType>().fields_id)) {
  566. Push(context_.insts()
  567. .GetAs<SemIR::StructTypeField>(field_id)
  568. .field_type_id);
  569. }
  570. break;
  571. case SemIR::TupleType::Kind:
  572. for (auto element_type_id : context_.type_blocks().Get(
  573. type_inst.As<SemIR::TupleType>().elements_id)) {
  574. Push(element_type_id);
  575. }
  576. break;
  577. case SemIR::ClassType::Kind: {
  578. auto class_type = type_inst.As<SemIR::ClassType>();
  579. auto& class_info = context_.classes().Get(class_type.class_id);
  580. if (!class_info.is_defined()) {
  581. if (diagnoser_) {
  582. auto builder = (*diagnoser_)();
  583. context_.NoteIncompleteClass(class_type.class_id, builder);
  584. builder.Emit();
  585. }
  586. return false;
  587. }
  588. Push(class_info.object_repr_id);
  589. break;
  590. }
  591. case SemIR::ConstType::Kind:
  592. Push(type_inst.As<SemIR::ConstType>().inner_id);
  593. break;
  594. default:
  595. break;
  596. }
  597. return true;
  598. }
  599. // Makes an empty value representation, which is used for types that have no
  600. // state, such as empty structs and tuples.
  601. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  602. return {.kind = SemIR::ValueRepr::None,
  603. .type_id = context_.GetTupleType({})};
  604. }
  605. // Makes a value representation that uses pass-by-copy, copying the given
  606. // type.
  607. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  608. SemIR::ValueRepr::AggregateKind aggregate_kind =
  609. SemIR::ValueRepr::NotAggregate) const
  610. -> SemIR::ValueRepr {
  611. return {.kind = SemIR::ValueRepr::Copy,
  612. .aggregate_kind = aggregate_kind,
  613. .type_id = rep_id};
  614. }
  615. // Makes a value representation that uses pass-by-address with the given
  616. // pointee type.
  617. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  618. SemIR::ValueRepr::AggregateKind aggregate_kind =
  619. SemIR::ValueRepr::NotAggregate) const
  620. -> SemIR::ValueRepr {
  621. // TODO: Should we add `const` qualification to `pointee_id`?
  622. return {.kind = SemIR::ValueRepr::Pointer,
  623. .aggregate_kind = aggregate_kind,
  624. .type_id = context_.GetPointerType(pointee_id)};
  625. }
  626. // Gets the value representation of a nested type, which should already be
  627. // complete.
  628. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  629. CARBON_CHECK(context_.types().IsComplete(nested_type_id))
  630. << "Nested type should already be complete";
  631. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  632. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown)
  633. << "Complete type should have a value representation";
  634. return value_rep;
  635. };
  636. auto BuildBuiltinValueRepr(SemIR::TypeId type_id,
  637. SemIR::Builtin builtin) const -> SemIR::ValueRepr {
  638. switch (builtin.builtin_kind) {
  639. case SemIR::BuiltinKind::TypeType:
  640. case SemIR::BuiltinKind::Error:
  641. case SemIR::BuiltinKind::Invalid:
  642. case SemIR::BuiltinKind::BoolType:
  643. case SemIR::BuiltinKind::IntType:
  644. case SemIR::BuiltinKind::FloatType:
  645. case SemIR::BuiltinKind::NamespaceType:
  646. case SemIR::BuiltinKind::FunctionType:
  647. case SemIR::BuiltinKind::BoundMethodType:
  648. case SemIR::BuiltinKind::WitnessType:
  649. return MakeCopyValueRepr(type_id);
  650. case SemIR::BuiltinKind::StringType:
  651. // TODO: Decide on string value semantics. This should probably be a
  652. // custom value representation carrying a pointer and size or
  653. // similar.
  654. return MakePointerValueRepr(type_id);
  655. }
  656. llvm_unreachable("All builtin kinds were handled above");
  657. }
  658. auto BuildImportRefUsedValueRepr(SemIR::TypeId type_id,
  659. SemIR::ImportRefUsed import_ref) const
  660. -> SemIR::ValueRepr {
  661. const auto& import_ir = context_.import_irs().Get(import_ref.ir_id).sem_ir;
  662. auto import_inst = import_ir->insts().Get(import_ref.inst_id);
  663. CARBON_CHECK(import_inst.kind() != SemIR::InstKind::ImportRefUsed)
  664. << "If ImportRefUsed can point at another, this would be recursive.";
  665. return BuildValueRepr(type_id, import_inst);
  666. }
  667. auto BuildStructOrTupleValueRepr(std::size_t num_elements,
  668. SemIR::TypeId elementwise_rep,
  669. bool same_as_object_rep) const
  670. -> SemIR::ValueRepr {
  671. SemIR::ValueRepr::AggregateKind aggregate_kind =
  672. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  673. : SemIR::ValueRepr::ValueAggregate;
  674. if (num_elements == 1) {
  675. // The value representation for a struct or tuple with a single element
  676. // is a struct or tuple containing the value representation of the
  677. // element.
  678. // TODO: Consider doing the same whenever `elementwise_rep` is
  679. // sufficiently small.
  680. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  681. }
  682. // For a struct or tuple with multiple fields, we use a pointer
  683. // to the elementwise value representation.
  684. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  685. }
  686. auto BuildStructTypeValueRepr(SemIR::TypeId type_id,
  687. SemIR::StructType struct_type) const
  688. -> SemIR::ValueRepr {
  689. // TODO: Share more code with tuples.
  690. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  691. if (fields.empty()) {
  692. return MakeEmptyValueRepr();
  693. }
  694. // Find the value representation for each field, and construct a struct
  695. // of value representations.
  696. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  697. value_rep_fields.reserve(fields.size());
  698. bool same_as_object_rep = true;
  699. for (auto field_id : fields) {
  700. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  701. auto field_value_rep = GetNestedValueRepr(field.field_type_id);
  702. if (field_value_rep.type_id != field.field_type_id) {
  703. same_as_object_rep = false;
  704. field.field_type_id = field_value_rep.type_id;
  705. // TODO: Use `TryEvalInst` to form this value.
  706. field_id = context_
  707. .AddConstant(field, context_.constant_values()
  708. .Get(context_.types().GetInstId(
  709. field.field_type_id))
  710. .is_symbolic())
  711. .inst_id();
  712. }
  713. value_rep_fields.push_back(field_id);
  714. }
  715. auto value_rep = same_as_object_rep
  716. ? type_id
  717. : context_.GetStructType(
  718. context_.inst_blocks().Add(value_rep_fields));
  719. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  720. same_as_object_rep);
  721. }
  722. auto BuildTupleTypeValueRepr(SemIR::TypeId type_id,
  723. SemIR::TupleType tuple_type) const
  724. -> SemIR::ValueRepr {
  725. // TODO: Share more code with structs.
  726. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  727. if (elements.empty()) {
  728. return MakeEmptyValueRepr();
  729. }
  730. // Find the value representation for each element, and construct a tuple
  731. // of value representations.
  732. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  733. value_rep_elements.reserve(elements.size());
  734. bool same_as_object_rep = true;
  735. for (auto element_type_id : elements) {
  736. auto element_value_rep = GetNestedValueRepr(element_type_id);
  737. if (element_value_rep.type_id != element_type_id) {
  738. same_as_object_rep = false;
  739. }
  740. value_rep_elements.push_back(element_value_rep.type_id);
  741. }
  742. auto value_rep = same_as_object_rep
  743. ? type_id
  744. : context_.GetTupleType(value_rep_elements);
  745. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  746. same_as_object_rep);
  747. }
  748. // Builds and returns the value representation for the given type. All nested
  749. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  750. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  751. -> SemIR::ValueRepr {
  752. switch (inst.kind()) {
  753. case SemIR::AddrOf::Kind:
  754. case SemIR::AddrPattern::Kind:
  755. case SemIR::ArrayIndex::Kind:
  756. case SemIR::ArrayInit::Kind:
  757. case SemIR::Assign::Kind:
  758. case SemIR::AssociatedConstantDecl::Kind:
  759. case SemIR::AssociatedEntity::Kind:
  760. case SemIR::BaseDecl::Kind:
  761. case SemIR::BindAlias::Kind:
  762. case SemIR::BindName::Kind:
  763. case SemIR::BindValue::Kind:
  764. case SemIR::BlockArg::Kind:
  765. case SemIR::BoolLiteral::Kind:
  766. case SemIR::BoundMethod::Kind:
  767. case SemIR::Branch::Kind:
  768. case SemIR::BranchIf::Kind:
  769. case SemIR::BranchWithArg::Kind:
  770. case SemIR::Call::Kind:
  771. case SemIR::ClassDecl::Kind:
  772. case SemIR::ClassElementAccess::Kind:
  773. case SemIR::ClassInit::Kind:
  774. case SemIR::Converted::Kind:
  775. case SemIR::Deref::Kind:
  776. case SemIR::FacetTypeAccess::Kind:
  777. case SemIR::FieldDecl::Kind:
  778. case SemIR::FunctionDecl::Kind:
  779. case SemIR::ImplDecl::Kind:
  780. case SemIR::ImportRefUnused::Kind:
  781. case SemIR::InitializeFrom::Kind:
  782. case SemIR::InterfaceDecl::Kind:
  783. case SemIR::InterfaceWitness::Kind:
  784. case SemIR::InterfaceWitnessAccess::Kind:
  785. case SemIR::IntLiteral::Kind:
  786. case SemIR::NameRef::Kind:
  787. case SemIR::Namespace::Kind:
  788. case SemIR::Param::Kind:
  789. case SemIR::RealLiteral::Kind:
  790. case SemIR::Return::Kind:
  791. case SemIR::ReturnExpr::Kind:
  792. case SemIR::SpliceBlock::Kind:
  793. case SemIR::StringLiteral::Kind:
  794. case SemIR::StructAccess::Kind:
  795. case SemIR::StructTypeField::Kind:
  796. case SemIR::StructLiteral::Kind:
  797. case SemIR::StructInit::Kind:
  798. case SemIR::StructValue::Kind:
  799. case SemIR::Temporary::Kind:
  800. case SemIR::TemporaryStorage::Kind:
  801. case SemIR::TupleAccess::Kind:
  802. case SemIR::TupleIndex::Kind:
  803. case SemIR::TupleLiteral::Kind:
  804. case SemIR::TupleInit::Kind:
  805. case SemIR::TupleValue::Kind:
  806. case SemIR::UnaryOperatorNot::Kind:
  807. case SemIR::ValueAsRef::Kind:
  808. case SemIR::ValueOfInitializer::Kind:
  809. case SemIR::VarStorage::Kind:
  810. CARBON_FATAL() << "Type refers to non-type inst " << inst;
  811. case SemIR::ArrayType::Kind: {
  812. // For arrays, it's convenient to always use a pointer representation,
  813. // even when the array has zero or one element, in order to support
  814. // indexing.
  815. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  816. }
  817. case SemIR::ImportRefUsed::Kind:
  818. return BuildImportRefUsedValueRepr(type_id,
  819. inst.As<SemIR::ImportRefUsed>());
  820. case SemIR::StructType::Kind:
  821. return BuildStructTypeValueRepr(type_id, inst.As<SemIR::StructType>());
  822. case SemIR::TupleType::Kind:
  823. return BuildTupleTypeValueRepr(type_id, inst.As<SemIR::TupleType>());
  824. case SemIR::ClassType::Kind:
  825. // The value representation for a class is a pointer to the object
  826. // representation.
  827. // TODO: Support customized value representations for classes.
  828. // TODO: Pick a better value representation when possible.
  829. return MakePointerValueRepr(
  830. context_.classes()
  831. .Get(inst.As<SemIR::ClassType>().class_id)
  832. .object_repr_id,
  833. SemIR::ValueRepr::ObjectAggregate);
  834. case SemIR::InterfaceType::Kind:
  835. // TODO: Should we model the value representation as a witness?
  836. return MakeEmptyValueRepr();
  837. case SemIR::Builtin::Kind:
  838. return BuildBuiltinValueRepr(type_id, inst.As<SemIR::Builtin>());
  839. case SemIR::AssociatedEntityType::Kind:
  840. case SemIR::BindSymbolicName::Kind:
  841. case SemIR::PointerType::Kind:
  842. case SemIR::UnboundElementType::Kind:
  843. return MakeCopyValueRepr(type_id);
  844. case SemIR::ConstType::Kind:
  845. // The value representation of `const T` is the same as that of `T`.
  846. // Objects are not modifiable through their value representations.
  847. return GetNestedValueRepr(inst.As<SemIR::ConstType>().inner_id);
  848. }
  849. }
  850. enum class Phase : int8_t {
  851. // The next step is to add nested types to the list of types to complete.
  852. AddNestedIncompleteTypes,
  853. // The next step is to build the value representation for the type.
  854. BuildValueRepr,
  855. };
  856. struct WorkItem {
  857. SemIR::TypeId type_id;
  858. Phase phase;
  859. };
  860. Context& context_;
  861. llvm::SmallVector<WorkItem> work_list_;
  862. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  863. diagnoser_;
  864. };
  865. } // namespace
  866. auto Context::TryToCompleteType(
  867. SemIR::TypeId type_id,
  868. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  869. -> bool {
  870. return TypeCompleter(*this, diagnoser).Complete(type_id);
  871. }
  872. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  873. -> SemIR::TypeId {
  874. CARBON_CHECK(constant_id.is_constant())
  875. << "Canonicalizing non-constant type: " << constant_id;
  876. auto [it, added] = type_ids_for_type_constants_.insert(
  877. {constant_id, SemIR::TypeId::Invalid});
  878. if (added) {
  879. it->second = types().Add({.constant_id = constant_id});
  880. }
  881. return it->second;
  882. }
  883. template <typename InstT, typename... EachArgT>
  884. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  885. -> SemIR::TypeId {
  886. // TODO: Remove inst_id parameter from TryEvalInst.
  887. return context.GetTypeIdForTypeConstant(
  888. TryEvalInst(context, SemIR::InstId::Invalid,
  889. InstT{SemIR::TypeId::TypeType, each_arg...}));
  890. }
  891. auto Context::GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId {
  892. return GetTypeImpl<SemIR::StructType>(*this, refs_id);
  893. }
  894. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  895. -> SemIR::TypeId {
  896. // TODO: Deduplicate the type block here. Currently requesting the same tuple
  897. // type more than once will create multiple type blocks, all but one of which
  898. // is unused.
  899. return GetTypeImpl<SemIR::TupleType>(*this, type_blocks().Add(type_ids));
  900. }
  901. auto Context::GetAssociatedEntityType(SemIR::InterfaceId interface_id,
  902. SemIR::TypeId entity_type_id)
  903. -> SemIR::TypeId {
  904. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_id,
  905. entity_type_id);
  906. }
  907. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  908. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  909. auto type_id = GetTypeIdForTypeInst(SemIR::InstId::ForBuiltin(kind));
  910. // To keep client code simpler, complete builtin types before returning them.
  911. bool complete = TryToCompleteType(type_id);
  912. CARBON_CHECK(complete) << "Failed to complete builtin type";
  913. return type_id;
  914. }
  915. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  916. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  917. }
  918. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  919. SemIR::TypeId element_type_id)
  920. -> SemIR::TypeId {
  921. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  922. element_type_id);
  923. }
  924. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  925. if (auto const_type = types().TryGetAs<SemIR::ConstType>(type_id)) {
  926. return const_type->inner_id;
  927. }
  928. return type_id;
  929. }
  930. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  931. node_stack_.PrintForStackDump(output);
  932. inst_block_stack_.PrintForStackDump(output);
  933. param_and_arg_refs_stack_.PrintForStackDump(output);
  934. args_type_info_stack_.PrintForStackDump(output);
  935. }
  936. } // namespace Carbon::Check