semantics_context.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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/semantics/semantics_context.h"
  5. #include <utility>
  6. #include "common/check.h"
  7. #include "common/vlog.h"
  8. #include "toolchain/diagnostics/diagnostic_kind.h"
  9. #include "toolchain/lexer/tokenized_buffer.h"
  10. #include "toolchain/parser/parse_node_kind.h"
  11. #include "toolchain/semantics/semantics_declaration_name_stack.h"
  12. #include "toolchain/semantics/semantics_ir.h"
  13. #include "toolchain/semantics/semantics_node.h"
  14. #include "toolchain/semantics/semantics_node_block_stack.h"
  15. #include "toolchain/semantics/semantics_node_kind.h"
  16. namespace Carbon {
  17. SemanticsContext::SemanticsContext(const TokenizedBuffer& tokens,
  18. DiagnosticEmitter<ParseTree::Node>& emitter,
  19. const ParseTree& parse_tree,
  20. SemanticsIR& semantics_ir,
  21. llvm::raw_ostream* vlog_stream)
  22. : tokens_(&tokens),
  23. emitter_(&emitter),
  24. parse_tree_(&parse_tree),
  25. semantics_ir_(&semantics_ir),
  26. vlog_stream_(vlog_stream),
  27. node_stack_(parse_tree, vlog_stream),
  28. node_block_stack_("node_block_stack_", semantics_ir, vlog_stream),
  29. params_or_args_stack_("params_or_args_stack_", semantics_ir, vlog_stream),
  30. args_type_info_stack_("args_type_info_stack_", semantics_ir, vlog_stream),
  31. declaration_name_stack_(this) {
  32. // Inserts the "Error" and "Type" types as "used types" so that
  33. // canonicalization can skip them. We don't emit either for lowering.
  34. canonical_types_.insert(
  35. {SemanticsNodeId::BuiltinError, SemanticsTypeId::Error});
  36. canonical_types_.insert(
  37. {SemanticsNodeId::BuiltinTypeType, SemanticsTypeId::TypeType});
  38. }
  39. auto SemanticsContext::TODO(ParseTree::Node parse_node, std::string label)
  40. -> bool {
  41. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.",
  42. std::string);
  43. emitter_->Emit(parse_node, SemanticsTodo, std::move(label));
  44. return false;
  45. }
  46. auto SemanticsContext::VerifyOnFinish() -> void {
  47. // Information in all the various context objects should be cleaned up as
  48. // various pieces of context go out of scope. At this point, nothing should
  49. // remain.
  50. // node_stack_ will still contain top-level entities.
  51. CARBON_CHECK(name_lookup_.empty()) << name_lookup_.size();
  52. CARBON_CHECK(scope_stack_.empty()) << scope_stack_.size();
  53. CARBON_CHECK(node_block_stack_.empty()) << node_block_stack_.size();
  54. CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size();
  55. }
  56. auto SemanticsContext::AddNode(SemanticsNode node) -> SemanticsNodeId {
  57. return AddNodeToBlock(node_block_stack_.PeekForAdd(), node);
  58. }
  59. auto SemanticsContext::AddNodeToBlock(SemanticsNodeBlockId block,
  60. SemanticsNode node) -> SemanticsNodeId {
  61. CARBON_VLOG() << "AddNode " << block << ": " << node << "\n";
  62. return semantics_ir_->AddNode(block, node);
  63. }
  64. auto SemanticsContext::AddNodeAndPush(ParseTree::Node parse_node,
  65. SemanticsNode node) -> void {
  66. auto node_id = AddNode(node);
  67. node_stack_.Push(parse_node, node_id);
  68. }
  69. auto SemanticsContext::DiagnoseDuplicateName(ParseTree::Node parse_node,
  70. SemanticsNodeId prev_def_id)
  71. -> void {
  72. CARBON_DIAGNOSTIC(NameDeclarationDuplicate, Error,
  73. "Duplicate name being declared in the same scope.");
  74. CARBON_DIAGNOSTIC(NameDeclarationPrevious, Note,
  75. "Name is previously declared here.");
  76. auto prev_def = semantics_ir_->GetNode(prev_def_id);
  77. emitter_->Build(parse_node, NameDeclarationDuplicate)
  78. .Note(prev_def.parse_node(), NameDeclarationPrevious)
  79. .Emit();
  80. }
  81. auto SemanticsContext::DiagnoseNameNotFound(ParseTree::Node parse_node,
  82. SemanticsStringId name_id) -> void {
  83. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.",
  84. llvm::StringRef);
  85. emitter_->Emit(parse_node, NameNotFound, semantics_ir_->GetString(name_id));
  86. }
  87. auto SemanticsContext::AddNameToLookup(ParseTree::Node name_node,
  88. SemanticsStringId name_id,
  89. SemanticsNodeId 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 SemanticsContext::LookupName(ParseTree::Node parse_node,
  97. SemanticsStringId name_id,
  98. SemanticsNameScopeId scope_id,
  99. bool print_diagnostics) -> SemanticsNodeId {
  100. if (scope_id == SemanticsNameScopeId::Invalid) {
  101. auto it = name_lookup_.find(name_id);
  102. if (it == name_lookup_.end()) {
  103. if (print_diagnostics) {
  104. DiagnoseNameNotFound(parse_node, name_id);
  105. }
  106. return SemanticsNodeId::BuiltinError;
  107. }
  108. CARBON_CHECK(!it->second.empty())
  109. << "Should have been erased: " << semantics_ir_->GetString(name_id);
  110. // TODO: Check for ambiguous lookups.
  111. return it->second.back();
  112. } else {
  113. const auto& scope = semantics_ir_->GetNameScope(scope_id);
  114. auto it = scope.find(name_id);
  115. if (it == scope.end()) {
  116. if (print_diagnostics) {
  117. DiagnoseNameNotFound(parse_node, name_id);
  118. }
  119. return SemanticsNodeId::BuiltinError;
  120. }
  121. return it->second;
  122. }
  123. }
  124. auto SemanticsContext::PushScope() -> void { scope_stack_.push_back({}); }
  125. auto SemanticsContext::PopScope() -> void {
  126. auto scope = scope_stack_.pop_back_val();
  127. for (const auto& str_id : scope.names) {
  128. auto it = name_lookup_.find(str_id);
  129. if (it->second.size() == 1) {
  130. // Erase names that no longer resolve.
  131. name_lookup_.erase(it);
  132. } else {
  133. it->second.pop_back();
  134. }
  135. }
  136. }
  137. template <typename BranchNode, typename... Args>
  138. static auto AddDominatedBlockAndBranchImpl(SemanticsContext& context,
  139. ParseTree::Node parse_node,
  140. Args... args)
  141. -> SemanticsNodeBlockId {
  142. if (!context.node_block_stack().is_current_block_reachable()) {
  143. return SemanticsNodeBlockId::Unreachable;
  144. }
  145. auto block_id = context.semantics_ir().AddNodeBlock();
  146. context.AddNode(BranchNode::Make(parse_node, block_id, args...));
  147. return block_id;
  148. }
  149. auto SemanticsContext::AddDominatedBlockAndBranch(ParseTree::Node parse_node)
  150. -> SemanticsNodeBlockId {
  151. return AddDominatedBlockAndBranchImpl<SemanticsNode::Branch>(*this,
  152. parse_node);
  153. }
  154. auto SemanticsContext::AddDominatedBlockAndBranchWithArg(
  155. ParseTree::Node parse_node, SemanticsNodeId arg_id)
  156. -> SemanticsNodeBlockId {
  157. return AddDominatedBlockAndBranchImpl<SemanticsNode::BranchWithArg>(
  158. *this, parse_node, arg_id);
  159. }
  160. auto SemanticsContext::AddDominatedBlockAndBranchIf(ParseTree::Node parse_node,
  161. SemanticsNodeId cond_id)
  162. -> SemanticsNodeBlockId {
  163. return AddDominatedBlockAndBranchImpl<SemanticsNode::BranchIf>(
  164. *this, parse_node, cond_id);
  165. }
  166. auto SemanticsContext::AddConvergenceBlockAndPush(
  167. ParseTree::Node parse_node,
  168. std::initializer_list<SemanticsNodeBlockId> blocks) -> void {
  169. CARBON_CHECK(blocks.size() >= 2) << "no convergence";
  170. SemanticsNodeBlockId new_block_id = SemanticsNodeBlockId::Unreachable;
  171. for (SemanticsNodeBlockId block_id : blocks) {
  172. if (block_id != SemanticsNodeBlockId::Unreachable) {
  173. if (new_block_id == SemanticsNodeBlockId::Unreachable) {
  174. new_block_id = semantics_ir().AddNodeBlock();
  175. }
  176. AddNodeToBlock(block_id,
  177. SemanticsNode::Branch::Make(parse_node, new_block_id));
  178. }
  179. }
  180. node_block_stack().Push(new_block_id);
  181. }
  182. auto SemanticsContext::AddConvergenceBlockWithArgAndPush(
  183. ParseTree::Node parse_node,
  184. std::initializer_list<std::pair<SemanticsNodeBlockId, SemanticsNodeId>>
  185. blocks_and_args) -> SemanticsNodeId {
  186. CARBON_CHECK(blocks_and_args.size() >= 2) << "no convergence";
  187. SemanticsNodeBlockId new_block_id = SemanticsNodeBlockId::Unreachable;
  188. for (auto [block_id, arg_id] : blocks_and_args) {
  189. if (block_id != SemanticsNodeBlockId::Unreachable) {
  190. if (new_block_id == SemanticsNodeBlockId::Unreachable) {
  191. new_block_id = semantics_ir().AddNodeBlock();
  192. }
  193. AddNodeToBlock(block_id, SemanticsNode::BranchWithArg::Make(
  194. parse_node, new_block_id, arg_id));
  195. }
  196. }
  197. node_block_stack().Push(new_block_id);
  198. // Acquire the result value.
  199. SemanticsTypeId result_type_id =
  200. semantics_ir().GetNode(blocks_and_args.begin()->second).type_id();
  201. return AddNode(
  202. SemanticsNode::BlockArg::Make(parse_node, result_type_id, new_block_id));
  203. }
  204. // Add the current code block to the enclosing function.
  205. auto SemanticsContext::AddCurrentCodeBlockToFunction() -> void {
  206. CARBON_CHECK(!node_block_stack().empty()) << "no current code block";
  207. CARBON_CHECK(!return_scope_stack().empty()) << "no current function";
  208. if (!node_block_stack().is_current_block_reachable()) {
  209. // Don't include unreachable blocks in the function.
  210. return;
  211. }
  212. auto function_id = semantics_ir()
  213. .GetNode(return_scope_stack().back())
  214. .GetAsFunctionDeclaration();
  215. semantics_ir()
  216. .GetFunction(function_id)
  217. .body_block_ids.push_back(node_block_stack().PeekForAdd());
  218. }
  219. auto SemanticsContext::is_current_position_reachable() -> bool {
  220. switch (auto block_id = node_block_stack().Peek(); block_id.index) {
  221. case SemanticsNodeBlockId::Unreachable.index: {
  222. return false;
  223. }
  224. case SemanticsNodeBlockId::Invalid.index: {
  225. return true;
  226. }
  227. default: {
  228. // Our current position is at the end of a real block. That position is
  229. // reachable unless the previous instruction is a terminator instruction.
  230. const auto& block_contents = semantics_ir().GetNodeBlock(block_id);
  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. SemanticsTerminatorKind::Terminator;
  237. }
  238. }
  239. }
  240. auto SemanticsContext::ImplicitAsForArgs(
  241. SemanticsNodeBlockId arg_refs_id, ParseTree::Node param_parse_node,
  242. SemanticsNodeBlockId param_refs_id,
  243. DiagnosticEmitter<ParseTree::Node>::DiagnosticBuilder* diagnostic) -> bool {
  244. // If both arguments and parameters are empty, return quickly. Otherwise,
  245. // we'll fetch both so that errors are consistent.
  246. if (arg_refs_id == SemanticsNodeBlockId::Empty &&
  247. param_refs_id == SemanticsNodeBlockId::Empty) {
  248. return true;
  249. }
  250. auto arg_refs = semantics_ir_->GetNodeBlock(arg_refs_id);
  251. auto param_refs = semantics_ir_->GetNodeBlock(param_refs_id);
  252. // If sizes mismatch, fail early.
  253. if (arg_refs.size() != param_refs.size()) {
  254. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  255. CARBON_DIAGNOSTIC(CallArgCountMismatch, Note,
  256. "Function cannot be used: Received {0} argument(s), but "
  257. "require {1} argument(s).",
  258. int, int);
  259. diagnostic->Note(param_parse_node, CallArgCountMismatch, arg_refs.size(),
  260. param_refs.size());
  261. return false;
  262. }
  263. // Check type conversions per-element.
  264. // TODO: arg_ir_id is passed so that implicit conversions can be inserted.
  265. // It's currently not supported, but will be needed.
  266. for (size_t i = 0; i < arg_refs.size(); ++i) {
  267. auto value_id = arg_refs[i];
  268. auto as_type_id = semantics_ir_->GetNode(param_refs[i]).type_id();
  269. if (ImplicitAsImpl(value_id, as_type_id,
  270. diagnostic == nullptr ? &value_id : nullptr) ==
  271. ImplicitAsKind::Incompatible) {
  272. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  273. CARBON_DIAGNOSTIC(CallArgTypeMismatch, Note,
  274. "Function cannot be used: Cannot implicitly convert "
  275. "argument {0} from `{1}` to `{2}`.",
  276. size_t, std::string, std::string);
  277. diagnostic->Note(param_parse_node, CallArgTypeMismatch, i,
  278. semantics_ir_->StringifyType(
  279. semantics_ir_->GetNode(value_id).type_id()),
  280. semantics_ir_->StringifyType(as_type_id));
  281. return false;
  282. }
  283. }
  284. return true;
  285. }
  286. auto SemanticsContext::ImplicitAsRequired(ParseTree::Node parse_node,
  287. SemanticsNodeId value_id,
  288. SemanticsTypeId as_type_id)
  289. -> SemanticsNodeId {
  290. SemanticsNodeId output_value_id = value_id;
  291. if (ImplicitAsImpl(value_id, as_type_id, &output_value_id) ==
  292. ImplicitAsKind::Incompatible) {
  293. // Only error when the system is trying to use the result.
  294. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  295. "Cannot implicitly convert from `{0}` to `{1}`.",
  296. std::string, std::string);
  297. emitter_
  298. ->Build(parse_node, ImplicitAsConversionFailure,
  299. semantics_ir_->StringifyType(
  300. semantics_ir_->GetNode(value_id).type_id()),
  301. semantics_ir_->StringifyType(as_type_id))
  302. .Emit();
  303. }
  304. return output_value_id;
  305. }
  306. auto SemanticsContext::ImplicitAsBool(ParseTree::Node parse_node,
  307. SemanticsNodeId value_id)
  308. -> SemanticsNodeId {
  309. return ImplicitAsRequired(parse_node, value_id,
  310. CanonicalizeType(SemanticsNodeId::BuiltinBoolType));
  311. }
  312. auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id,
  313. SemanticsTypeId as_type_id,
  314. SemanticsNodeId* output_value_id)
  315. -> ImplicitAsKind {
  316. // Start by making sure both sides are valid. If any part is invalid, the
  317. // result is invalid and we shouldn't error.
  318. if (value_id == SemanticsNodeId::BuiltinError) {
  319. // If the value is invalid, we can't do much, but do "succeed".
  320. return ImplicitAsKind::Identical;
  321. }
  322. auto value = semantics_ir_->GetNode(value_id);
  323. auto value_type_id = value.type_id();
  324. if (value_type_id == SemanticsTypeId::Error) {
  325. // Although the source type is invalid, this still changes the value.
  326. if (output_value_id != nullptr) {
  327. *output_value_id = SemanticsNodeId::BuiltinError;
  328. }
  329. return ImplicitAsKind::Compatible;
  330. }
  331. if (as_type_id == SemanticsTypeId::Error) {
  332. // Although the target type is invalid, this still changes the value.
  333. if (output_value_id != nullptr) {
  334. *output_value_id = SemanticsNodeId::BuiltinError;
  335. }
  336. return ImplicitAsKind::Compatible;
  337. }
  338. if (value_type_id == as_type_id) {
  339. // Type doesn't need to change.
  340. return ImplicitAsKind::Identical;
  341. }
  342. auto as_type = semantics_ir_->GetTypeAllowBuiltinTypes(as_type_id);
  343. auto as_type_node = semantics_ir_->GetNode(as_type);
  344. if (as_type_node.kind() == SemanticsNodeKind::ArrayType) {
  345. auto [bound_node_id, element_type_id] = as_type_node.GetAsArrayType();
  346. // To resolve lambda issue.
  347. auto element_type = element_type_id;
  348. auto value_type_node = semantics_ir_->GetNode(
  349. semantics_ir_->GetTypeAllowBuiltinTypes(value_type_id));
  350. if (value_type_node.kind() == SemanticsNodeKind::TupleType) {
  351. auto tuple_type_block_id = value_type_node.GetAsTupleType();
  352. const auto& type_block = semantics_ir_->GetTypeBlock(tuple_type_block_id);
  353. if (type_block.size() ==
  354. semantics_ir_->GetArrayBoundValue(bound_node_id) &&
  355. std::all_of(type_block.begin(), type_block.end(),
  356. [&](auto type) { return type == element_type; })) {
  357. if (output_value_id != nullptr) {
  358. *output_value_id = AddNode(SemanticsNode::ArrayValue::Make(
  359. value.parse_node(), as_type_id, value_id));
  360. }
  361. return ImplicitAsKind::Compatible;
  362. }
  363. }
  364. }
  365. if (as_type_id == SemanticsTypeId::TypeType) {
  366. if (value.kind() == SemanticsNodeKind::TupleValue) {
  367. auto tuple_block_id = value.GetAsTupleValue();
  368. llvm::SmallVector<SemanticsTypeId> type_ids;
  369. // If it is empty tuple type, we don't fetch anything.
  370. if (tuple_block_id != SemanticsNodeBlockId::Empty) {
  371. const auto& tuple_block = semantics_ir_->GetNodeBlock(tuple_block_id);
  372. for (auto tuple_node_id : tuple_block) {
  373. // TODO: Eventually ExpressionAsType will insert implicit cast
  374. // instructions. When that happens, this will need to verify the full
  375. // tuple conversion will work before calling it.
  376. type_ids.push_back(
  377. ExpressionAsType(value.parse_node(), tuple_node_id));
  378. }
  379. }
  380. auto tuple_type_id =
  381. CanonicalizeTupleType(value.parse_node(), std::move(type_ids));
  382. if (output_value_id != nullptr) {
  383. *output_value_id =
  384. semantics_ir_->GetTypeAllowBuiltinTypes(tuple_type_id);
  385. }
  386. return ImplicitAsKind::Compatible;
  387. }
  388. // When converting `{}` to a type, the result is `{} as Type`.
  389. if (value.kind() == SemanticsNodeKind::StructValue &&
  390. value.GetAsStructValue() == SemanticsNodeBlockId::Empty) {
  391. if (output_value_id != nullptr) {
  392. *output_value_id = semantics_ir_->GetType(value_type_id);
  393. }
  394. return ImplicitAsKind::Compatible;
  395. }
  396. }
  397. // TODO: Handle ImplicitAs for compatible structs and tuples.
  398. if (output_value_id != nullptr) {
  399. *output_value_id = SemanticsNodeId::BuiltinError;
  400. }
  401. return ImplicitAsKind::Incompatible;
  402. }
  403. auto SemanticsContext::ParamOrArgStart() -> void {
  404. params_or_args_stack_.Push();
  405. }
  406. auto SemanticsContext::ParamOrArgComma(bool for_args) -> void {
  407. ParamOrArgSave(for_args);
  408. }
  409. auto SemanticsContext::ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  410. -> SemanticsNodeBlockId {
  411. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  412. ParamOrArgSave(for_args);
  413. }
  414. return params_or_args_stack_.Pop();
  415. }
  416. auto SemanticsContext::ParamOrArgSave(bool for_args) -> void {
  417. auto [entry_parse_node, entry_node_id] =
  418. node_stack_.PopExpressionWithParseNode();
  419. if (for_args) {
  420. // For an argument, we add a stub reference to the expression on the top of
  421. // the stack. There may not be anything on the IR prior to this.
  422. entry_node_id = AddNode(SemanticsNode::StubReference::Make(
  423. entry_parse_node, semantics_ir_->GetNode(entry_node_id).type_id(),
  424. entry_node_id));
  425. }
  426. // Save the param or arg ID.
  427. auto& params_or_args =
  428. semantics_ir_->GetNodeBlock(params_or_args_stack_.PeekForAdd());
  429. params_or_args.push_back(entry_node_id);
  430. }
  431. auto SemanticsContext::CanonicalizeTypeImpl(
  432. SemanticsNodeKind kind,
  433. llvm::function_ref<void(llvm::FoldingSetNodeID& canonical_id)> profile_type,
  434. llvm::function_ref<SemanticsNodeId()> make_node) -> SemanticsTypeId {
  435. llvm::FoldingSetNodeID canonical_id;
  436. kind.Profile(canonical_id);
  437. profile_type(canonical_id);
  438. void* insert_pos;
  439. auto* node =
  440. canonical_type_nodes_.FindNodeOrInsertPos(canonical_id, insert_pos);
  441. if (node != nullptr) {
  442. return node->type_id();
  443. }
  444. auto node_id = make_node();
  445. auto type_id = semantics_ir_->AddType(node_id);
  446. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  447. type_node_storage_.push_back(
  448. std::make_unique<TypeNode>(canonical_id, type_id));
  449. // In a debug build, check that our insertion position is still valid. It
  450. // could have been invalidated by a misbehaving `make_node`.
  451. CARBON_DCHECK([&] {
  452. void* check_insert_pos;
  453. auto* check_node = canonical_type_nodes_.FindNodeOrInsertPos(
  454. canonical_id, check_insert_pos);
  455. return !check_node && insert_pos == check_insert_pos;
  456. }()) << "Type was created recursively during canonicalization";
  457. canonical_type_nodes_.InsertNode(type_node_storage_.back().get(), insert_pos);
  458. return type_id;
  459. }
  460. // Compute a fingerprint for a tuple type, for use as a key in a folding set.
  461. static auto ProfileTupleType(const llvm::SmallVector<SemanticsTypeId>& type_ids,
  462. llvm::FoldingSetNodeID& canonical_id) -> void {
  463. for (const auto& type_id : type_ids) {
  464. canonical_id.AddInteger(type_id.index);
  465. }
  466. }
  467. // Compute a fingerprint for a type, for use as a key in a folding set.
  468. static auto ProfileType(SemanticsContext& semantics_context, SemanticsNode node,
  469. llvm::FoldingSetNodeID& canonical_id) -> void {
  470. switch (node.kind()) {
  471. case SemanticsNodeKind::ArrayType: {
  472. auto [bound_id, element_type_id] = node.GetAsArrayType();
  473. canonical_id.AddInteger(
  474. semantics_context.semantics_ir().GetArrayBoundValue(bound_id));
  475. canonical_id.AddInteger(element_type_id.index);
  476. break;
  477. }
  478. case SemanticsNodeKind::Builtin:
  479. canonical_id.AddInteger(node.GetAsBuiltin().AsInt());
  480. break;
  481. case SemanticsNodeKind::CrossReference: {
  482. // TODO: Cross-references should be canonicalized by looking at their
  483. // target rather than treating them as new unique types.
  484. auto [xref_id, node_id] = node.GetAsCrossReference();
  485. canonical_id.AddInteger(xref_id.index);
  486. canonical_id.AddInteger(node_id.index);
  487. break;
  488. }
  489. case SemanticsNodeKind::ConstType:
  490. canonical_id.AddInteger(
  491. semantics_context.GetUnqualifiedType(node.GetAsConstType()).index);
  492. break;
  493. case SemanticsNodeKind::PointerType:
  494. canonical_id.AddInteger(node.GetAsPointerType().index);
  495. break;
  496. case SemanticsNodeKind::StructType: {
  497. auto refs =
  498. semantics_context.semantics_ir().GetNodeBlock(node.GetAsStructType());
  499. for (const auto& ref_id : refs) {
  500. auto ref = semantics_context.semantics_ir().GetNode(ref_id);
  501. auto [name_id, type_id] = ref.GetAsStructTypeField();
  502. canonical_id.AddInteger(name_id.index);
  503. canonical_id.AddInteger(type_id.index);
  504. }
  505. break;
  506. }
  507. case SemanticsNodeKind::StubReference: {
  508. // We rely on stub references not referring to each other to ensure we
  509. // only recurse once here.
  510. auto inner =
  511. semantics_context.semantics_ir().GetNode(node.GetAsStubReference());
  512. CARBON_CHECK(inner.kind() != SemanticsNodeKind::StubReference)
  513. << "A stub reference should never refer to another stub reference.";
  514. ProfileType(semantics_context, inner, canonical_id);
  515. break;
  516. }
  517. case SemanticsNodeKind::TupleType:
  518. ProfileTupleType(
  519. semantics_context.semantics_ir().GetTypeBlock(node.GetAsTupleType()),
  520. canonical_id);
  521. break;
  522. default:
  523. CARBON_FATAL() << "Unexpected type node " << node;
  524. }
  525. }
  526. auto SemanticsContext::CanonicalizeTypeAndAddNodeIfNew(SemanticsNode node)
  527. -> SemanticsTypeId {
  528. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  529. ProfileType(*this, node, canonical_id);
  530. };
  531. auto make_node = [&] { return AddNode(node); };
  532. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  533. }
  534. auto SemanticsContext::CanonicalizeType(SemanticsNodeId node_id)
  535. -> SemanticsTypeId {
  536. auto it = canonical_types_.find(node_id);
  537. if (it != canonical_types_.end()) {
  538. return it->second;
  539. }
  540. auto node = semantics_ir_->GetNode(node_id);
  541. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  542. ProfileType(*this, node, canonical_id);
  543. };
  544. auto make_node = [&] { return node_id; };
  545. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  546. }
  547. auto SemanticsContext::CanonicalizeStructType(ParseTree::Node parse_node,
  548. SemanticsNodeBlockId refs_id)
  549. -> SemanticsTypeId {
  550. return CanonicalizeTypeAndAddNodeIfNew(SemanticsNode::StructType::Make(
  551. parse_node, SemanticsTypeId::TypeType, refs_id));
  552. }
  553. auto SemanticsContext::CanonicalizeTupleType(
  554. ParseTree::Node parse_node, llvm::SmallVector<SemanticsTypeId>&& type_ids)
  555. -> SemanticsTypeId {
  556. // Defer allocating a SemanticsTypeBlockId until we know this is a new type.
  557. auto profile_tuple = [&](llvm::FoldingSetNodeID& canonical_id) {
  558. ProfileTupleType(type_ids, canonical_id);
  559. };
  560. auto make_tuple_node = [&] {
  561. auto type_block_id = semantics_ir_->AddTypeBlock();
  562. auto& type_block = semantics_ir_->GetTypeBlock(type_block_id);
  563. type_block = std::move(type_ids);
  564. return AddNode(SemanticsNode::TupleType::Make(
  565. parse_node, SemanticsTypeId::TypeType, type_block_id));
  566. };
  567. return CanonicalizeTypeImpl(SemanticsNodeKind::TupleType, profile_tuple,
  568. make_tuple_node);
  569. }
  570. auto SemanticsContext::GetPointerType(ParseTree::Node parse_node,
  571. SemanticsTypeId pointee_type_id)
  572. -> SemanticsTypeId {
  573. return CanonicalizeTypeAndAddNodeIfNew(SemanticsNode::PointerType::Make(
  574. parse_node, SemanticsTypeId::TypeType, pointee_type_id));
  575. }
  576. auto SemanticsContext::GetUnqualifiedType(SemanticsTypeId type_id)
  577. -> SemanticsTypeId {
  578. SemanticsNode type_node =
  579. semantics_ir_->GetNode(semantics_ir_->GetTypeAllowBuiltinTypes(type_id));
  580. if (type_node.kind() == SemanticsNodeKind::ConstType) {
  581. return type_node.GetAsConstType();
  582. }
  583. return type_id;
  584. }
  585. auto SemanticsContext::PrintForStackDump(llvm::raw_ostream& output) const
  586. -> void {
  587. node_stack_.PrintForStackDump(output);
  588. node_block_stack_.PrintForStackDump(output);
  589. params_or_args_stack_.PrintForStackDump(output);
  590. args_type_info_stack_.PrintForStackDump(output);
  591. }
  592. } // namespace Carbon