context.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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/declaration_name_stack.h"
  11. #include "toolchain/check/node_block_stack.h"
  12. #include "toolchain/lex/tokenized_buffer.h"
  13. #include "toolchain/parse/node_kind.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/node.h"
  16. #include "toolchain/sem_ir/node_kind.h"
  17. namespace Carbon::Check {
  18. Context::Context(const Lex::TokenizedBuffer& tokens, DiagnosticEmitter& emitter,
  19. const Parse::Tree& parse_tree, SemIR::File& semantics_ir,
  20. llvm::raw_ostream* vlog_stream)
  21. : tokens_(&tokens),
  22. emitter_(&emitter),
  23. parse_tree_(&parse_tree),
  24. semantics_ir_(&semantics_ir),
  25. vlog_stream_(vlog_stream),
  26. node_stack_(parse_tree, vlog_stream),
  27. node_block_stack_("node_block_stack_", semantics_ir, vlog_stream),
  28. params_or_args_stack_("params_or_args_stack_", semantics_ir, vlog_stream),
  29. args_type_info_stack_("args_type_info_stack_", semantics_ir, vlog_stream),
  30. declaration_name_stack_(this) {
  31. // Inserts the "Error" and "Type" types as "used types" so that
  32. // canonicalization can skip them. We don't emit either for lowering.
  33. canonical_types_.insert({SemIR::NodeId::BuiltinError, SemIR::TypeId::Error});
  34. canonical_types_.insert(
  35. {SemIR::NodeId::BuiltinTypeType, SemIR::TypeId::TypeType});
  36. }
  37. auto Context::TODO(Parse::Node parse_node, std::string label) -> bool {
  38. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.",
  39. std::string);
  40. emitter_->Emit(parse_node, SemanticsTodo, std::move(label));
  41. return false;
  42. }
  43. auto Context::VerifyOnFinish() -> void {
  44. // Information in all the various context objects should be cleaned up as
  45. // various pieces of context go out of scope. At this point, nothing should
  46. // remain.
  47. // node_stack_ will still contain top-level entities.
  48. CARBON_CHECK(name_lookup_.empty()) << name_lookup_.size();
  49. CARBON_CHECK(scope_stack_.empty()) << scope_stack_.size();
  50. CARBON_CHECK(node_block_stack_.empty()) << node_block_stack_.size();
  51. CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size();
  52. }
  53. auto Context::AddNode(SemIR::Node node) -> SemIR::NodeId {
  54. auto node_id = node_block_stack_.AddNode(node);
  55. CARBON_VLOG() << "AddNode: " << node << "\n";
  56. return node_id;
  57. }
  58. auto Context::AddNodeAndPush(Parse::Node parse_node, SemIR::Node node) -> void {
  59. auto node_id = AddNode(node);
  60. node_stack_.Push(parse_node, node_id);
  61. }
  62. auto Context::DiagnoseDuplicateName(Parse::Node parse_node,
  63. SemIR::NodeId prev_def_id) -> void {
  64. CARBON_DIAGNOSTIC(NameDeclarationDuplicate, Error,
  65. "Duplicate name being declared in the same scope.");
  66. CARBON_DIAGNOSTIC(NameDeclarationPrevious, Note,
  67. "Name is previously declared here.");
  68. auto prev_def = semantics_ir_->GetNode(prev_def_id);
  69. emitter_->Build(parse_node, NameDeclarationDuplicate)
  70. .Note(prev_def.parse_node(), NameDeclarationPrevious)
  71. .Emit();
  72. }
  73. auto Context::DiagnoseNameNotFound(Parse::Node parse_node, StringId name_id)
  74. -> void {
  75. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.",
  76. llvm::StringRef);
  77. emitter_->Emit(parse_node, NameNotFound,
  78. semantics_ir_->strings().Get(name_id));
  79. }
  80. auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
  81. DiagnosticBuilder& builder) -> void {
  82. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  83. "Class was forward declared here.");
  84. const auto& class_info = semantics_ir().classes().Get(class_id);
  85. builder.Note(semantics_ir().GetNode(class_info.declaration_id).parse_node(),
  86. ClassForwardDeclaredHere);
  87. }
  88. auto Context::AddNameToLookup(Parse::Node name_node, StringId name_id,
  89. SemIR::NodeId target_id) -> void {
  90. if (current_scope().names.insert(name_id).second) {
  91. name_lookup_[name_id].push_back(target_id);
  92. } else {
  93. DiagnoseDuplicateName(name_node, name_lookup_[name_id].back());
  94. }
  95. }
  96. auto Context::LookupName(Parse::Node parse_node, StringId name_id,
  97. SemIR::NameScopeId scope_id, bool print_diagnostics)
  98. -> SemIR::NodeId {
  99. if (scope_id == SemIR::NameScopeId::Invalid) {
  100. auto it = name_lookup_.find(name_id);
  101. if (it == name_lookup_.end()) {
  102. if (print_diagnostics) {
  103. DiagnoseNameNotFound(parse_node, name_id);
  104. }
  105. return SemIR::NodeId::BuiltinError;
  106. }
  107. CARBON_CHECK(!it->second.empty())
  108. << "Should have been erased: " << semantics_ir_->strings().Get(name_id);
  109. // TODO: Check for ambiguous lookups.
  110. return it->second.back();
  111. } else {
  112. const auto& scope = semantics_ir_->GetNameScope(scope_id);
  113. auto it = scope.find(name_id);
  114. if (it == scope.end()) {
  115. if (print_diagnostics) {
  116. DiagnoseNameNotFound(parse_node, name_id);
  117. }
  118. return SemIR::NodeId::BuiltinError;
  119. }
  120. return it->second;
  121. }
  122. }
  123. auto Context::PushScope(SemIR::NameScopeId scope_id) -> void {
  124. scope_stack_.push_back({.scope_id = scope_id});
  125. }
  126. auto Context::PopScope() -> void {
  127. auto scope = scope_stack_.pop_back_val();
  128. for (const auto& str_id : scope.names) {
  129. auto it = name_lookup_.find(str_id);
  130. if (it->second.size() == 1) {
  131. // Erase names that no longer resolve.
  132. name_lookup_.erase(it);
  133. } else {
  134. it->second.pop_back();
  135. }
  136. }
  137. }
  138. auto Context::FollowNameReferences(SemIR::NodeId node_id) -> SemIR::NodeId {
  139. while (auto name_ref =
  140. semantics_ir().GetNode(node_id).TryAs<SemIR::NameReference>()) {
  141. node_id = name_ref->value_id;
  142. }
  143. return node_id;
  144. }
  145. template <typename BranchNode, typename... Args>
  146. static auto AddDominatedBlockAndBranchImpl(Context& context,
  147. Parse::Node parse_node, Args... args)
  148. -> SemIR::NodeBlockId {
  149. if (!context.node_block_stack().is_current_block_reachable()) {
  150. return SemIR::NodeBlockId::Unreachable;
  151. }
  152. auto block_id = context.semantics_ir().AddNodeBlockId();
  153. context.AddNode(BranchNode{parse_node, block_id, args...});
  154. return block_id;
  155. }
  156. auto Context::AddDominatedBlockAndBranch(Parse::Node parse_node)
  157. -> SemIR::NodeBlockId {
  158. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, parse_node);
  159. }
  160. auto Context::AddDominatedBlockAndBranchWithArg(Parse::Node parse_node,
  161. SemIR::NodeId arg_id)
  162. -> SemIR::NodeBlockId {
  163. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, parse_node,
  164. arg_id);
  165. }
  166. auto Context::AddDominatedBlockAndBranchIf(Parse::Node parse_node,
  167. SemIR::NodeId cond_id)
  168. -> SemIR::NodeBlockId {
  169. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, parse_node,
  170. cond_id);
  171. }
  172. auto Context::AddConvergenceBlockAndPush(Parse::Node parse_node, int num_blocks)
  173. -> void {
  174. CARBON_CHECK(num_blocks >= 2) << "no convergence";
  175. SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable;
  176. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  177. if (node_block_stack().is_current_block_reachable()) {
  178. if (new_block_id == SemIR::NodeBlockId::Unreachable) {
  179. new_block_id = semantics_ir().AddNodeBlockId();
  180. }
  181. AddNode(SemIR::Branch{parse_node, new_block_id});
  182. }
  183. node_block_stack().Pop();
  184. }
  185. node_block_stack().Push(new_block_id);
  186. }
  187. auto Context::AddConvergenceBlockWithArgAndPush(
  188. Parse::Node parse_node, std::initializer_list<SemIR::NodeId> block_args)
  189. -> SemIR::NodeId {
  190. CARBON_CHECK(block_args.size() >= 2) << "no convergence";
  191. SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable;
  192. for (auto arg_id : block_args) {
  193. if (node_block_stack().is_current_block_reachable()) {
  194. if (new_block_id == SemIR::NodeBlockId::Unreachable) {
  195. new_block_id = semantics_ir().AddNodeBlockId();
  196. }
  197. AddNode(SemIR::BranchWithArg{parse_node, new_block_id, arg_id});
  198. }
  199. node_block_stack().Pop();
  200. }
  201. node_block_stack().Push(new_block_id);
  202. // Acquire the result value.
  203. SemIR::TypeId result_type_id =
  204. semantics_ir().GetNode(*block_args.begin()).type_id();
  205. return AddNode(SemIR::BlockArg{parse_node, result_type_id, new_block_id});
  206. }
  207. // Add the current code block to the enclosing function.
  208. auto Context::AddCurrentCodeBlockToFunction() -> void {
  209. CARBON_CHECK(!node_block_stack().empty()) << "no current code block";
  210. CARBON_CHECK(!return_scope_stack().empty()) << "no current function";
  211. if (!node_block_stack().is_current_block_reachable()) {
  212. // Don't include unreachable blocks in the function.
  213. return;
  214. }
  215. auto function_id =
  216. semantics_ir()
  217. .GetNodeAs<SemIR::FunctionDeclaration>(return_scope_stack().back())
  218. .function_id;
  219. semantics_ir()
  220. .functions()
  221. .Get(function_id)
  222. .body_block_ids.push_back(node_block_stack().PeekOrAdd());
  223. }
  224. auto Context::is_current_position_reachable() -> bool {
  225. if (!node_block_stack().is_current_block_reachable()) {
  226. return false;
  227. }
  228. // Our current position is at the end of a reachable block. That position is
  229. // reachable unless the previous instruction is a terminator instruction.
  230. auto block_contents = node_block_stack().PeekCurrentBlockContents();
  231. if (block_contents.empty()) {
  232. return true;
  233. }
  234. const auto& last_node = semantics_ir().GetNode(block_contents.back());
  235. return last_node.kind().terminator_kind() !=
  236. SemIR::TerminatorKind::Terminator;
  237. }
  238. auto Context::ParamOrArgStart() -> void { params_or_args_stack_.Push(); }
  239. auto Context::ParamOrArgComma() -> void {
  240. ParamOrArgSave(node_stack_.PopExpression());
  241. }
  242. auto Context::ParamOrArgEndNoPop(Parse::NodeKind start_kind) -> void {
  243. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  244. ParamOrArgSave(node_stack_.PopExpression());
  245. }
  246. }
  247. auto Context::ParamOrArgPop() -> SemIR::NodeBlockId {
  248. return params_or_args_stack_.Pop();
  249. }
  250. auto Context::ParamOrArgEnd(Parse::NodeKind start_kind) -> SemIR::NodeBlockId {
  251. ParamOrArgEndNoPop(start_kind);
  252. return ParamOrArgPop();
  253. }
  254. namespace {
  255. // Worklist-based type completion mechanism.
  256. //
  257. // When attempting to complete a type, we may find other types that also need to
  258. // be completed: types nested within that type, and the value representation of
  259. // the type. In order to complete a type without recursing arbitrarily deeply,
  260. // we use a worklist of tasks:
  261. //
  262. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  263. // nested within a type to the work list.
  264. // - A `BuildValueRepresentation` step computes the value representation for a
  265. // type, once all of its nested types are complete, and marks the type as
  266. // complete.
  267. class TypeCompleter {
  268. public:
  269. TypeCompleter(
  270. Context& context,
  271. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  272. diagnoser)
  273. : context_(context), diagnoser_(diagnoser) {}
  274. // Attempts to complete the given type. Returns true if it is now complete,
  275. // false if it could not be completed.
  276. auto Complete(SemIR::TypeId type_id) -> bool {
  277. Push(type_id);
  278. while (!work_list_.empty()) {
  279. if (!ProcessStep()) {
  280. return false;
  281. }
  282. }
  283. return true;
  284. }
  285. private:
  286. // Adds `type_id` to the work list, if it's not already complete.
  287. auto Push(SemIR::TypeId type_id) -> void {
  288. if (!context_.semantics_ir().IsTypeComplete(type_id)) {
  289. work_list_.push_back({type_id, Phase::AddNestedIncompleteTypes});
  290. }
  291. }
  292. // Runs the next step.
  293. auto ProcessStep() -> bool {
  294. auto [type_id, phase] = work_list_.back();
  295. // We might have enqueued the same type more than once. Just skip the
  296. // type if it's already complete.
  297. if (context_.semantics_ir().IsTypeComplete(type_id)) {
  298. work_list_.pop_back();
  299. return true;
  300. }
  301. auto node_id = context_.semantics_ir().GetTypeAllowBuiltinTypes(type_id);
  302. auto node = context_.semantics_ir().GetNode(node_id);
  303. auto old_work_list_size = work_list_.size();
  304. switch (phase) {
  305. case Phase::AddNestedIncompleteTypes:
  306. if (!AddNestedIncompleteTypes(node)) {
  307. return false;
  308. }
  309. CARBON_CHECK(work_list_.size() >= old_work_list_size)
  310. << "AddNestedIncompleteTypes should not remove work items";
  311. work_list_[old_work_list_size - 1].phase =
  312. Phase::BuildValueRepresentation;
  313. break;
  314. case Phase::BuildValueRepresentation: {
  315. auto value_rep = BuildValueRepresentation(type_id, node);
  316. context_.semantics_ir().CompleteType(type_id, value_rep);
  317. CARBON_CHECK(old_work_list_size == work_list_.size())
  318. << "BuildValueRepresentation should not change work items";
  319. work_list_.pop_back();
  320. // Also complete the value representation type, if necessary. This
  321. // should never fail: the value representation shouldn't require any
  322. // additional nested types to be complete.
  323. if (!context_.semantics_ir().IsTypeComplete(value_rep.type_id)) {
  324. work_list_.push_back(
  325. {value_rep.type_id, Phase::BuildValueRepresentation});
  326. }
  327. // For a pointer representation, the pointee also needs to be complete.
  328. if (value_rep.kind == SemIR::ValueRepresentation::Pointer) {
  329. auto pointee_type_id =
  330. context_.semantics_ir().GetPointeeType(value_rep.type_id);
  331. if (!context_.semantics_ir().IsTypeComplete(pointee_type_id)) {
  332. work_list_.push_back(
  333. {pointee_type_id, Phase::BuildValueRepresentation});
  334. }
  335. }
  336. break;
  337. }
  338. }
  339. return true;
  340. }
  341. // Adds any types nested within `type_node` that need to be complete for
  342. // `type_node` to be complete to our work list.
  343. auto AddNestedIncompleteTypes(SemIR::Node type_node) -> bool {
  344. switch (type_node.kind()) {
  345. case SemIR::ArrayType::Kind:
  346. Push(type_node.As<SemIR::ArrayType>().element_type_id);
  347. break;
  348. case SemIR::StructType::Kind:
  349. for (auto field_id : context_.semantics_ir().GetNodeBlock(
  350. type_node.As<SemIR::StructType>().fields_id)) {
  351. Push(context_.semantics_ir()
  352. .GetNodeAs<SemIR::StructTypeField>(field_id)
  353. .field_type_id);
  354. }
  355. break;
  356. case SemIR::TupleType::Kind:
  357. for (auto element_type_id : context_.semantics_ir().GetTypeBlock(
  358. type_node.As<SemIR::TupleType>().elements_id)) {
  359. Push(element_type_id);
  360. }
  361. break;
  362. case SemIR::ClassType::Kind:
  363. // TODO: Support class definitions and complete class types.
  364. if (diagnoser_) {
  365. auto builder = (*diagnoser_)();
  366. context_.NoteIncompleteClass(
  367. type_node.As<SemIR::ClassType>().class_id, builder);
  368. builder.Emit();
  369. }
  370. return false;
  371. case SemIR::ConstType::Kind:
  372. Push(type_node.As<SemIR::ConstType>().inner_id);
  373. break;
  374. default:
  375. break;
  376. }
  377. return true;
  378. }
  379. // Makes an empty value representation, which is used for types that have no
  380. // state, such as empty structs and tuples.
  381. auto MakeEmptyRepresentation(Parse::Node parse_node) const
  382. -> SemIR::ValueRepresentation {
  383. return {.kind = SemIR::ValueRepresentation::None,
  384. .type_id = context_.CanonicalizeTupleType(parse_node, {})};
  385. }
  386. // Makes a value representation that uses pass-by-copy, copying the given
  387. // type.
  388. auto MakeCopyRepresentation(SemIR::TypeId rep_id) const
  389. -> SemIR::ValueRepresentation {
  390. return {.kind = SemIR::ValueRepresentation::Copy, .type_id = rep_id};
  391. }
  392. // Makes a value representation that uses pass-by-address with the given
  393. // pointee type.
  394. auto MakePointerRepresentation(Parse::Node parse_node,
  395. SemIR::TypeId pointee_id) const
  396. -> SemIR::ValueRepresentation {
  397. // TODO: Should we add `const` qualification to `pointee_id`?
  398. return {.kind = SemIR::ValueRepresentation::Pointer,
  399. .type_id = context_.GetPointerType(parse_node, pointee_id)};
  400. }
  401. // Gets the value representation of a nested type, which should already be
  402. // complete.
  403. auto GetNestedValueRepresentation(SemIR::TypeId nested_type_id) const {
  404. CARBON_CHECK(context_.semantics_ir().IsTypeComplete(nested_type_id))
  405. << "Nested type should already be complete";
  406. auto value_rep =
  407. context_.semantics_ir().GetValueRepresentation(nested_type_id);
  408. CARBON_CHECK(value_rep.kind != SemIR::ValueRepresentation::Unknown)
  409. << "Complete type should have a value representation";
  410. return value_rep;
  411. };
  412. auto BuildCrossReferenceValueRepresentation(SemIR::TypeId type_id,
  413. SemIR::CrossReference xref) const
  414. -> SemIR::ValueRepresentation {
  415. auto xref_node = context_.semantics_ir()
  416. .GetCrossReferenceIR(xref.ir_id)
  417. .GetNode(xref.node_id);
  418. // The canonical description of a type should only have cross-references
  419. // for entities owned by another File, such as builtins, which are owned
  420. // by the prelude, and named entities like classes and interfaces, which
  421. // we don't support yet.
  422. CARBON_CHECK(xref_node.kind() == SemIR::Builtin::Kind)
  423. << "TODO: Handle other kinds of node cross-references";
  424. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  425. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  426. switch (xref_node.As<SemIR::Builtin>().builtin_kind) {
  427. case SemIR::BuiltinKind::TypeType:
  428. case SemIR::BuiltinKind::Error:
  429. case SemIR::BuiltinKind::Invalid:
  430. case SemIR::BuiltinKind::BoolType:
  431. case SemIR::BuiltinKind::IntegerType:
  432. case SemIR::BuiltinKind::FloatingPointType:
  433. case SemIR::BuiltinKind::NamespaceType:
  434. case SemIR::BuiltinKind::FunctionType:
  435. return MakeCopyRepresentation(type_id);
  436. case SemIR::BuiltinKind::StringType:
  437. // TODO: Decide on string value semantics. This should probably be a
  438. // custom value representation carrying a pointer and size or
  439. // similar.
  440. return MakePointerRepresentation(Parse::Node::Invalid, type_id);
  441. }
  442. llvm_unreachable("All builtin kinds were handled above");
  443. }
  444. auto BuildStructTypeValueRepresentation(SemIR::TypeId type_id,
  445. SemIR::StructType struct_type) const
  446. -> SemIR::ValueRepresentation {
  447. // TODO: Share code with tuples.
  448. auto fields = context_.semantics_ir().GetNodeBlock(struct_type.fields_id);
  449. if (fields.empty()) {
  450. return MakeEmptyRepresentation(struct_type.parse_node);
  451. }
  452. // Find the value representation for each field, and construct a struct
  453. // of value representations.
  454. llvm::SmallVector<SemIR::NodeId> value_rep_fields;
  455. value_rep_fields.reserve(fields.size());
  456. bool same_as_object_rep = true;
  457. for (auto field_id : fields) {
  458. auto field =
  459. context_.semantics_ir().GetNodeAs<SemIR::StructTypeField>(field_id);
  460. auto field_value_rep = GetNestedValueRepresentation(field.field_type_id);
  461. if (field_value_rep.type_id != field.field_type_id) {
  462. same_as_object_rep = false;
  463. field.field_type_id = field_value_rep.type_id;
  464. field_id = context_.AddNode(field);
  465. }
  466. value_rep_fields.push_back(field_id);
  467. }
  468. auto value_rep =
  469. same_as_object_rep
  470. ? type_id
  471. : context_.CanonicalizeStructType(
  472. struct_type.parse_node,
  473. context_.semantics_ir().AddNodeBlock(value_rep_fields));
  474. if (fields.size() == 1) {
  475. // The value representation for a struct with a single field is a
  476. // struct containing the value representation of the field.
  477. // TODO: Consider doing the same for structs with multiple small
  478. // fields.
  479. return MakeCopyRepresentation(value_rep);
  480. }
  481. // For a struct with multiple fields, we use a pointer representation.
  482. return MakePointerRepresentation(struct_type.parse_node, value_rep);
  483. }
  484. auto BuildTupleTypeValueRepresentation(SemIR::TypeId type_id,
  485. SemIR::TupleType tuple_type) const
  486. -> SemIR::ValueRepresentation {
  487. // TODO: Share code with structs.
  488. auto elements =
  489. context_.semantics_ir().GetTypeBlock(tuple_type.elements_id);
  490. if (elements.empty()) {
  491. return MakeEmptyRepresentation(tuple_type.parse_node);
  492. }
  493. // Find the value representation for each element, and construct a tuple
  494. // of value representations.
  495. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  496. value_rep_elements.reserve(elements.size());
  497. bool same_as_object_rep = true;
  498. for (auto element_type_id : elements) {
  499. auto element_value_rep = GetNestedValueRepresentation(element_type_id);
  500. if (element_value_rep.type_id != element_type_id) {
  501. same_as_object_rep = false;
  502. }
  503. value_rep_elements.push_back(element_value_rep.type_id);
  504. }
  505. auto value_rep = same_as_object_rep
  506. ? type_id
  507. : context_.CanonicalizeTupleType(tuple_type.parse_node,
  508. value_rep_elements);
  509. if (elements.size() == 1) {
  510. // The value representation for a tuple with a single element is a
  511. // tuple containing the value representation of that element.
  512. // TODO: Consider doing the same for tuples with multiple small
  513. // elements.
  514. return MakeCopyRepresentation(value_rep);
  515. }
  516. // For a tuple with multiple elements, we use a pointer representation.
  517. return MakePointerRepresentation(tuple_type.parse_node, value_rep);
  518. }
  519. // Builds and returns the value representation for the given type. All nested
  520. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  521. auto BuildValueRepresentation(SemIR::TypeId type_id, SemIR::Node node) const
  522. -> SemIR::ValueRepresentation {
  523. // TODO: This can emit new SemIR nodes. Consider emitting them into a
  524. // dedicated file-scope node block where possible, or somewhere else that
  525. // better reflects the definition of the type, rather than wherever the
  526. // type happens to first be required to be complete.
  527. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  528. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  529. switch (node.kind()) {
  530. case SemIR::AddressOf::Kind:
  531. case SemIR::ArrayIndex::Kind:
  532. case SemIR::ArrayInit::Kind:
  533. case SemIR::Assign::Kind:
  534. case SemIR::BinaryOperatorAdd::Kind:
  535. case SemIR::BindName::Kind:
  536. case SemIR::BindValue::Kind:
  537. case SemIR::BlockArg::Kind:
  538. case SemIR::BoolLiteral::Kind:
  539. case SemIR::Branch::Kind:
  540. case SemIR::BranchIf::Kind:
  541. case SemIR::BranchWithArg::Kind:
  542. case SemIR::Call::Kind:
  543. case SemIR::ClassDeclaration::Kind:
  544. case SemIR::Dereference::Kind:
  545. case SemIR::FunctionDeclaration::Kind:
  546. case SemIR::InitializeFrom::Kind:
  547. case SemIR::IntegerLiteral::Kind:
  548. case SemIR::NameReference::Kind:
  549. case SemIR::Namespace::Kind:
  550. case SemIR::NoOp::Kind:
  551. case SemIR::Parameter::Kind:
  552. case SemIR::RealLiteral::Kind:
  553. case SemIR::Return::Kind:
  554. case SemIR::ReturnExpression::Kind:
  555. case SemIR::SpliceBlock::Kind:
  556. case SemIR::StringLiteral::Kind:
  557. case SemIR::StructAccess::Kind:
  558. case SemIR::StructTypeField::Kind:
  559. case SemIR::StructLiteral::Kind:
  560. case SemIR::StructInit::Kind:
  561. case SemIR::StructValue::Kind:
  562. case SemIR::Temporary::Kind:
  563. case SemIR::TemporaryStorage::Kind:
  564. case SemIR::TupleAccess::Kind:
  565. case SemIR::TupleIndex::Kind:
  566. case SemIR::TupleLiteral::Kind:
  567. case SemIR::TupleInit::Kind:
  568. case SemIR::TupleValue::Kind:
  569. case SemIR::UnaryOperatorNot::Kind:
  570. case SemIR::ValueAsReference::Kind:
  571. case SemIR::VarStorage::Kind:
  572. CARBON_FATAL() << "Type refers to non-type node " << node;
  573. case SemIR::CrossReference::Kind:
  574. return BuildCrossReferenceValueRepresentation(
  575. type_id, node.As<SemIR::CrossReference>());
  576. case SemIR::ArrayType::Kind: {
  577. // For arrays, it's convenient to always use a pointer representation,
  578. // even when the array has zero or one element, in order to support
  579. // indexing.
  580. return MakePointerRepresentation(node.parse_node(), type_id);
  581. }
  582. case SemIR::StructType::Kind:
  583. return BuildStructTypeValueRepresentation(type_id,
  584. node.As<SemIR::StructType>());
  585. case SemIR::TupleType::Kind:
  586. return BuildTupleTypeValueRepresentation(type_id,
  587. node.As<SemIR::TupleType>());
  588. case SemIR::ClassType::Kind:
  589. // TODO: Support class definitions and complete class types.
  590. CARBON_FATAL() << "Class types are currently never complete";
  591. case SemIR::Builtin::Kind:
  592. CARBON_FATAL() << "Builtins should be named as cross-references";
  593. case SemIR::PointerType::Kind:
  594. return MakeCopyRepresentation(type_id);
  595. case SemIR::ConstType::Kind:
  596. // The value representation of `const T` is the same as that of `T`.
  597. // Objects are not modifiable through their value representations.
  598. return GetNestedValueRepresentation(
  599. node.As<SemIR::ConstType>().inner_id);
  600. }
  601. }
  602. enum class Phase : int8_t {
  603. // The next step is to add nested types to the list of types to complete.
  604. AddNestedIncompleteTypes,
  605. // The next step is to build the value representation for the type.
  606. BuildValueRepresentation,
  607. };
  608. struct WorkItem {
  609. SemIR::TypeId type_id;
  610. Phase phase;
  611. };
  612. Context& context_;
  613. llvm::SmallVector<WorkItem> work_list_;
  614. std::optional<llvm::function_ref<auto()->Context::DiagnosticBuilder>>
  615. diagnoser_;
  616. };
  617. } // namespace
  618. auto Context::TryToCompleteType(
  619. SemIR::TypeId type_id,
  620. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser)
  621. -> bool {
  622. return TypeCompleter(*this, diagnoser).Complete(type_id);
  623. }
  624. auto Context::CanonicalizeTypeImpl(
  625. SemIR::NodeKind kind,
  626. llvm::function_ref<void(llvm::FoldingSetNodeID& canonical_id)> profile_type,
  627. llvm::function_ref<SemIR::NodeId()> make_node) -> SemIR::TypeId {
  628. llvm::FoldingSetNodeID canonical_id;
  629. kind.Profile(canonical_id);
  630. profile_type(canonical_id);
  631. void* insert_pos;
  632. auto* node =
  633. canonical_type_nodes_.FindNodeOrInsertPos(canonical_id, insert_pos);
  634. if (node != nullptr) {
  635. return node->type_id();
  636. }
  637. auto node_id = make_node();
  638. auto type_id = semantics_ir_->types().Add({.node_id = node_id});
  639. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  640. type_node_storage_.push_back(
  641. std::make_unique<TypeNode>(canonical_id, type_id));
  642. // In a debug build, check that our insertion position is still valid. It
  643. // could have been invalidated by a misbehaving `make_node`.
  644. CARBON_DCHECK([&] {
  645. void* check_insert_pos;
  646. auto* check_node = canonical_type_nodes_.FindNodeOrInsertPos(
  647. canonical_id, check_insert_pos);
  648. return !check_node && insert_pos == check_insert_pos;
  649. }()) << "Type was created recursively during canonicalization";
  650. canonical_type_nodes_.InsertNode(type_node_storage_.back().get(), insert_pos);
  651. return type_id;
  652. }
  653. // Compute a fingerprint for a tuple type, for use as a key in a folding set.
  654. static auto ProfileTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids,
  655. llvm::FoldingSetNodeID& canonical_id) -> void {
  656. for (auto type_id : type_ids) {
  657. canonical_id.AddInteger(type_id.index);
  658. }
  659. }
  660. // Compute a fingerprint for a type, for use as a key in a folding set.
  661. static auto ProfileType(Context& semantics_context, SemIR::Node node,
  662. llvm::FoldingSetNodeID& canonical_id) -> void {
  663. switch (node.kind()) {
  664. case SemIR::ArrayType::Kind: {
  665. auto array_type = node.As<SemIR::ArrayType>();
  666. canonical_id.AddInteger(
  667. semantics_context.semantics_ir().GetArrayBoundValue(
  668. array_type.bound_id));
  669. canonical_id.AddInteger(array_type.element_type_id.index);
  670. break;
  671. }
  672. case SemIR::Builtin::Kind:
  673. canonical_id.AddInteger(node.As<SemIR::Builtin>().builtin_kind.AsInt());
  674. break;
  675. case SemIR::ClassType::Kind:
  676. canonical_id.AddInteger(node.As<SemIR::ClassType>().class_id.index);
  677. break;
  678. case SemIR::CrossReference::Kind: {
  679. // TODO: Cross-references should be canonicalized by looking at their
  680. // target rather than treating them as new unique types.
  681. auto xref = node.As<SemIR::CrossReference>();
  682. canonical_id.AddInteger(xref.ir_id.index);
  683. canonical_id.AddInteger(xref.node_id.index);
  684. break;
  685. }
  686. case SemIR::ConstType::Kind:
  687. canonical_id.AddInteger(
  688. semantics_context
  689. .GetUnqualifiedType(node.As<SemIR::ConstType>().inner_id)
  690. .index);
  691. break;
  692. case SemIR::PointerType::Kind:
  693. canonical_id.AddInteger(node.As<SemIR::PointerType>().pointee_id.index);
  694. break;
  695. case SemIR::StructType::Kind: {
  696. auto fields = semantics_context.semantics_ir().GetNodeBlock(
  697. node.As<SemIR::StructType>().fields_id);
  698. for (const auto& field_id : fields) {
  699. auto field =
  700. semantics_context.semantics_ir().GetNodeAs<SemIR::StructTypeField>(
  701. field_id);
  702. canonical_id.AddInteger(field.name_id.index);
  703. canonical_id.AddInteger(field.field_type_id.index);
  704. }
  705. break;
  706. }
  707. case SemIR::TupleType::Kind:
  708. ProfileTupleType(semantics_context.semantics_ir().GetTypeBlock(
  709. node.As<SemIR::TupleType>().elements_id),
  710. canonical_id);
  711. break;
  712. default:
  713. CARBON_FATAL() << "Unexpected type node " << node;
  714. }
  715. }
  716. auto Context::CanonicalizeTypeAndAddNodeIfNew(SemIR::Node node)
  717. -> SemIR::TypeId {
  718. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  719. ProfileType(*this, node, canonical_id);
  720. };
  721. auto make_node = [&] { return AddNode(node); };
  722. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  723. }
  724. auto Context::CanonicalizeType(SemIR::NodeId node_id) -> SemIR::TypeId {
  725. node_id = FollowNameReferences(node_id);
  726. auto it = canonical_types_.find(node_id);
  727. if (it != canonical_types_.end()) {
  728. return it->second;
  729. }
  730. auto node = semantics_ir_->GetNode(node_id);
  731. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  732. ProfileType(*this, node, canonical_id);
  733. };
  734. auto make_node = [&] { return node_id; };
  735. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  736. }
  737. auto Context::CanonicalizeStructType(Parse::Node parse_node,
  738. SemIR::NodeBlockId refs_id)
  739. -> SemIR::TypeId {
  740. return CanonicalizeTypeAndAddNodeIfNew(
  741. SemIR::StructType{parse_node, SemIR::TypeId::TypeType, refs_id});
  742. }
  743. auto Context::CanonicalizeTupleType(Parse::Node parse_node,
  744. llvm::ArrayRef<SemIR::TypeId> type_ids)
  745. -> SemIR::TypeId {
  746. // Defer allocating a SemIR::TypeBlockId until we know this is a new type.
  747. auto profile_tuple = [&](llvm::FoldingSetNodeID& canonical_id) {
  748. ProfileTupleType(type_ids, canonical_id);
  749. };
  750. auto make_tuple_node = [&] {
  751. return AddNode(SemIR::TupleType{parse_node, SemIR::TypeId::TypeType,
  752. semantics_ir_->AddTypeBlock(type_ids)});
  753. };
  754. return CanonicalizeTypeImpl(SemIR::TupleType::Kind, profile_tuple,
  755. make_tuple_node);
  756. }
  757. auto Context::GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId {
  758. CARBON_CHECK(kind != SemIR::BuiltinKind::Invalid);
  759. auto type_id = CanonicalizeType(SemIR::NodeId::ForBuiltin(kind));
  760. // To keep client code simpler, complete builtin types before returning them.
  761. bool complete = TryToCompleteType(type_id);
  762. CARBON_CHECK(complete) << "Failed to complete builtin type";
  763. return type_id;
  764. }
  765. auto Context::GetPointerType(Parse::Node parse_node,
  766. SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  767. return CanonicalizeTypeAndAddNodeIfNew(
  768. SemIR::PointerType{parse_node, SemIR::TypeId::TypeType, pointee_type_id});
  769. }
  770. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  771. SemIR::Node type_node =
  772. semantics_ir_->GetNode(semantics_ir_->GetTypeAllowBuiltinTypes(type_id));
  773. if (auto const_type = type_node.TryAs<SemIR::ConstType>()) {
  774. return const_type->inner_id;
  775. }
  776. return type_id;
  777. }
  778. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  779. node_stack_.PrintForStackDump(output);
  780. node_block_stack_.PrintForStackDump(output);
  781. params_or_args_stack_.PrintForStackDump(output);
  782. args_type_info_stack_.PrintForStackDump(output);
  783. }
  784. } // namespace Carbon::Check