context.cpp 39 KB

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