context.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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 <utility>
  6. #include "common/check.h"
  7. #include "common/vlog.h"
  8. #include "llvm/ADT/STLExtras.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/diagnostics/diagnostic_kind.h"
  13. #include "toolchain/lex/tokenized_buffer.h"
  14. #include "toolchain/parse/node_kind.h"
  15. #include "toolchain/sem_ir/file.h"
  16. #include "toolchain/sem_ir/node.h"
  17. #include "toolchain/sem_ir/node_kind.h"
  18. namespace Carbon::Check {
  19. Context::Context(const Lex::TokenizedBuffer& tokens,
  20. DiagnosticEmitter<Parse::Node>& emitter,
  21. const Parse::Tree& parse_tree, SemIR::File& semantics_ir,
  22. llvm::raw_ostream* vlog_stream)
  23. : tokens_(&tokens),
  24. emitter_(&emitter),
  25. parse_tree_(&parse_tree),
  26. semantics_ir_(&semantics_ir),
  27. vlog_stream_(vlog_stream),
  28. node_stack_(parse_tree, vlog_stream),
  29. node_block_stack_("node_block_stack_", semantics_ir, vlog_stream),
  30. params_or_args_stack_("params_or_args_stack_", semantics_ir, vlog_stream),
  31. args_type_info_stack_("args_type_info_stack_", semantics_ir, vlog_stream),
  32. declaration_name_stack_(this) {
  33. // Inserts the "Error" and "Type" types as "used types" so that
  34. // canonicalization can skip them. We don't emit either for lowering.
  35. canonical_types_.insert({SemIR::NodeId::BuiltinError, SemIR::TypeId::Error});
  36. canonical_types_.insert(
  37. {SemIR::NodeId::BuiltinTypeType, SemIR::TypeId::TypeType});
  38. }
  39. auto Context::TODO(Parse::Node parse_node, std::string label) -> bool {
  40. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.",
  41. std::string);
  42. emitter_->Emit(parse_node, SemanticsTodo, std::move(label));
  43. return false;
  44. }
  45. auto Context::VerifyOnFinish() -> void {
  46. // Information in all the various context objects should be cleaned up as
  47. // various pieces of context go out of scope. At this point, nothing should
  48. // remain.
  49. // node_stack_ will still contain top-level entities.
  50. CARBON_CHECK(name_lookup_.empty()) << name_lookup_.size();
  51. CARBON_CHECK(scope_stack_.empty()) << scope_stack_.size();
  52. CARBON_CHECK(node_block_stack_.empty()) << node_block_stack_.size();
  53. CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size();
  54. }
  55. auto Context::AddNode(SemIR::Node node) -> SemIR::NodeId {
  56. auto node_id = node_block_stack_.AddNode(node);
  57. CARBON_VLOG() << "AddNode: " << node << "\n";
  58. return node_id;
  59. }
  60. auto Context::AddNodeAndPush(Parse::Node parse_node, SemIR::Node node) -> void {
  61. auto node_id = AddNode(node);
  62. node_stack_.Push(parse_node, node_id);
  63. }
  64. auto Context::DiagnoseDuplicateName(Parse::Node parse_node,
  65. SemIR::NodeId prev_def_id) -> void {
  66. CARBON_DIAGNOSTIC(NameDeclarationDuplicate, Error,
  67. "Duplicate name being declared in the same scope.");
  68. CARBON_DIAGNOSTIC(NameDeclarationPrevious, Note,
  69. "Name is previously declared here.");
  70. auto prev_def = semantics_ir_->GetNode(prev_def_id);
  71. emitter_->Build(parse_node, NameDeclarationDuplicate)
  72. .Note(prev_def.parse_node(), NameDeclarationPrevious)
  73. .Emit();
  74. }
  75. auto Context::DiagnoseNameNotFound(Parse::Node parse_node,
  76. SemIR::StringId name_id) -> void {
  77. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.",
  78. llvm::StringRef);
  79. emitter_->Emit(parse_node, NameNotFound, semantics_ir_->GetString(name_id));
  80. }
  81. auto Context::AddNameToLookup(Parse::Node name_node, SemIR::StringId name_id,
  82. SemIR::NodeId target_id) -> void {
  83. if (current_scope().names.insert(name_id).second) {
  84. name_lookup_[name_id].push_back(target_id);
  85. } else {
  86. DiagnoseDuplicateName(name_node, name_lookup_[name_id].back());
  87. }
  88. }
  89. auto Context::LookupName(Parse::Node parse_node, SemIR::StringId name_id,
  90. SemIR::NameScopeId scope_id, bool print_diagnostics)
  91. -> SemIR::NodeId {
  92. if (scope_id == SemIR::NameScopeId::Invalid) {
  93. auto it = name_lookup_.find(name_id);
  94. if (it == name_lookup_.end()) {
  95. if (print_diagnostics) {
  96. DiagnoseNameNotFound(parse_node, name_id);
  97. }
  98. return SemIR::NodeId::BuiltinError;
  99. }
  100. CARBON_CHECK(!it->second.empty())
  101. << "Should have been erased: " << semantics_ir_->GetString(name_id);
  102. // TODO: Check for ambiguous lookups.
  103. return it->second.back();
  104. } else {
  105. const auto& scope = semantics_ir_->GetNameScope(scope_id);
  106. auto it = scope.find(name_id);
  107. if (it == scope.end()) {
  108. if (print_diagnostics) {
  109. DiagnoseNameNotFound(parse_node, name_id);
  110. }
  111. return SemIR::NodeId::BuiltinError;
  112. }
  113. return it->second;
  114. }
  115. }
  116. auto Context::PushScope() -> void { scope_stack_.push_back({}); }
  117. auto Context::PopScope() -> void {
  118. auto scope = scope_stack_.pop_back_val();
  119. for (const auto& str_id : scope.names) {
  120. auto it = name_lookup_.find(str_id);
  121. if (it->second.size() == 1) {
  122. // Erase names that no longer resolve.
  123. name_lookup_.erase(it);
  124. } else {
  125. it->second.pop_back();
  126. }
  127. }
  128. }
  129. template <typename BranchNode, typename... Args>
  130. static auto AddDominatedBlockAndBranchImpl(Context& context,
  131. Parse::Node parse_node, Args... args)
  132. -> SemIR::NodeBlockId {
  133. if (!context.node_block_stack().is_current_block_reachable()) {
  134. return SemIR::NodeBlockId::Unreachable;
  135. }
  136. auto block_id = context.semantics_ir().AddNodeBlockId();
  137. context.AddNode(BranchNode::Make(parse_node, block_id, args...));
  138. return block_id;
  139. }
  140. auto Context::AddDominatedBlockAndBranch(Parse::Node parse_node)
  141. -> SemIR::NodeBlockId {
  142. return AddDominatedBlockAndBranchImpl<SemIR::Node::Branch>(*this, parse_node);
  143. }
  144. auto Context::AddDominatedBlockAndBranchWithArg(Parse::Node parse_node,
  145. SemIR::NodeId arg_id)
  146. -> SemIR::NodeBlockId {
  147. return AddDominatedBlockAndBranchImpl<SemIR::Node::BranchWithArg>(
  148. *this, parse_node, arg_id);
  149. }
  150. auto Context::AddDominatedBlockAndBranchIf(Parse::Node parse_node,
  151. SemIR::NodeId cond_id)
  152. -> SemIR::NodeBlockId {
  153. return AddDominatedBlockAndBranchImpl<SemIR::Node::BranchIf>(
  154. *this, parse_node, cond_id);
  155. }
  156. auto Context::AddConvergenceBlockAndPush(Parse::Node parse_node, int num_blocks)
  157. -> void {
  158. CARBON_CHECK(num_blocks >= 2) << "no convergence";
  159. SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable;
  160. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  161. if (node_block_stack().is_current_block_reachable()) {
  162. if (new_block_id == SemIR::NodeBlockId::Unreachable) {
  163. new_block_id = semantics_ir().AddNodeBlockId();
  164. }
  165. AddNode(SemIR::Node::Branch::Make(parse_node, new_block_id));
  166. }
  167. node_block_stack().Pop();
  168. }
  169. node_block_stack().Push(new_block_id);
  170. }
  171. auto Context::AddConvergenceBlockWithArgAndPush(
  172. Parse::Node parse_node, std::initializer_list<SemIR::NodeId> block_args)
  173. -> SemIR::NodeId {
  174. CARBON_CHECK(block_args.size() >= 2) << "no convergence";
  175. SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable;
  176. for (auto arg_id : block_args) {
  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(
  182. SemIR::Node::BranchWithArg::Make(parse_node, new_block_id, arg_id));
  183. }
  184. node_block_stack().Pop();
  185. }
  186. node_block_stack().Push(new_block_id);
  187. // Acquire the result value.
  188. SemIR::TypeId result_type_id =
  189. semantics_ir().GetNode(*block_args.begin()).type_id();
  190. return AddNode(
  191. SemIR::Node::BlockArg::Make(parse_node, result_type_id, new_block_id));
  192. }
  193. // Add the current code block to the enclosing function.
  194. auto Context::AddCurrentCodeBlockToFunction() -> void {
  195. CARBON_CHECK(!node_block_stack().empty()) << "no current code block";
  196. CARBON_CHECK(!return_scope_stack().empty()) << "no current function";
  197. if (!node_block_stack().is_current_block_reachable()) {
  198. // Don't include unreachable blocks in the function.
  199. return;
  200. }
  201. auto function_id = semantics_ir()
  202. .GetNode(return_scope_stack().back())
  203. .GetAsFunctionDeclaration();
  204. semantics_ir()
  205. .GetFunction(function_id)
  206. .body_block_ids.push_back(node_block_stack().PeekOrAdd());
  207. }
  208. auto Context::is_current_position_reachable() -> bool {
  209. if (!node_block_stack().is_current_block_reachable()) {
  210. return false;
  211. }
  212. // Our current position is at the end of a reachable block. That position is
  213. // reachable unless the previous instruction is a terminator instruction.
  214. auto block_contents = node_block_stack().PeekCurrentBlockContents();
  215. if (block_contents.empty()) {
  216. return true;
  217. }
  218. const auto& last_node = semantics_ir().GetNode(block_contents.back());
  219. return last_node.kind().terminator_kind() !=
  220. SemIR::TerminatorKind::Terminator;
  221. }
  222. auto Context::Initialize(Parse::Node parse_node, SemIR::NodeId target_id,
  223. SemIR::NodeId value_id) -> SemIR::NodeId {
  224. // Implicitly convert the value to the type of the target.
  225. auto type_id = semantics_ir().GetNode(target_id).type_id();
  226. auto expr_id = ImplicitAs(parse_node, value_id, type_id);
  227. SemIR::Node expr = semantics_ir().GetNode(expr_id);
  228. // Perform initialization now that we have an expression of the right type.
  229. switch (SemIR::GetExpressionCategory(semantics_ir(), expr_id)) {
  230. case SemIR::ExpressionCategory::NotExpression:
  231. CARBON_FATAL() << "Converting non-expression node " << expr
  232. << " to initializing expression";
  233. case SemIR::ExpressionCategory::DurableReference:
  234. case SemIR::ExpressionCategory::EphemeralReference:
  235. // The design uses a custom "copy initialization" process here. We model
  236. // that as value binding followed by direct initialization.
  237. //
  238. // TODO: Determine whether this is observably different from the design,
  239. // and change either the toolchain or the design so they match.
  240. return AddNode(SemIR::Node::BindValue::Make(expr.parse_node(),
  241. expr.type_id(), expr_id));
  242. case SemIR::ExpressionCategory::Value:
  243. // TODO: For class types, use an interface to determine how to perform
  244. // this operation.
  245. return expr_id;
  246. case SemIR::ExpressionCategory::Initializing:
  247. MarkInitializerFor(expr_id, target_id);
  248. return expr_id;
  249. }
  250. }
  251. auto Context::InitializeAndFinalize(Parse::Node parse_node,
  252. SemIR::NodeId target_id,
  253. SemIR::NodeId value_id) -> SemIR::NodeId {
  254. auto init_id = Initialize(parse_node, target_id, value_id);
  255. if (init_id == SemIR::NodeId::BuiltinError) {
  256. return init_id;
  257. }
  258. auto target_type_id = semantics_ir().GetNode(target_id).type_id();
  259. if (auto init_rep =
  260. SemIR::GetInitializingRepresentation(semantics_ir(), target_type_id);
  261. init_rep.kind == SemIR::InitializingRepresentation::ByCopy) {
  262. init_id = AddNode(SemIR::Node::InitializeFrom::Make(
  263. parse_node, target_type_id, init_id, target_id));
  264. }
  265. return init_id;
  266. }
  267. auto Context::ConvertToValueExpression(SemIR::NodeId expr_id) -> SemIR::NodeId {
  268. if (expr_id == SemIR::NodeId::BuiltinError) {
  269. return expr_id;
  270. }
  271. switch (SemIR::GetExpressionCategory(semantics_ir(), expr_id)) {
  272. case SemIR::ExpressionCategory::NotExpression:
  273. CARBON_FATAL() << "Converting non-expression node "
  274. << semantics_ir().GetNode(expr_id)
  275. << " to value expression";
  276. case SemIR::ExpressionCategory::Initializing:
  277. // Commit to using a temporary for this initializing expression.
  278. // TODO: Don't create a temporary if the initializing representation is
  279. // already a value representation.
  280. expr_id = FinalizeTemporary(expr_id, /*discarded=*/false);
  281. [[fallthrough]];
  282. case SemIR::ExpressionCategory::DurableReference:
  283. case SemIR::ExpressionCategory::EphemeralReference: {
  284. // TODO: Support types with custom value representations.
  285. SemIR::Node expr = semantics_ir().GetNode(expr_id);
  286. return AddNode(SemIR::Node::BindValue::Make(expr.parse_node(),
  287. expr.type_id(), expr_id));
  288. }
  289. case SemIR::ExpressionCategory::Value:
  290. return expr_id;
  291. }
  292. }
  293. auto Context::FinalizeTemporary(SemIR::NodeId init_id, bool discarded)
  294. -> SemIR::NodeId {
  295. // TODO: See if we can refactor this with MarkInitializerFor once recursion
  296. // through struct and tuple values is properly handled.
  297. auto orig_init_id = init_id;
  298. while (true) {
  299. SemIR::Node init = semantics_ir().GetNode(init_id);
  300. CARBON_CHECK(SemIR::GetExpressionCategory(semantics_ir(), init_id) ==
  301. SemIR::ExpressionCategory::Initializing)
  302. << "Can only materialize initializing expressions, found " << init;
  303. switch (init.kind()) {
  304. default:
  305. CARBON_FATAL() << "Initialization from unexpected node " << init;
  306. case SemIR::NodeKind::StructLiteral:
  307. case SemIR::NodeKind::TupleLiteral:
  308. CARBON_FATAL() << init << " is not modeled as initializing yet";
  309. case SemIR::NodeKind::StubReference: {
  310. init_id = init.GetAsStubReference();
  311. continue;
  312. }
  313. case SemIR::NodeKind::Call: {
  314. auto [refs_id, callee_id] = init.GetAsCall();
  315. if (semantics_ir().GetFunction(callee_id).return_slot_id.is_valid()) {
  316. // The return slot should have a materialized temporary in it.
  317. auto temporary_id = semantics_ir().GetNodeBlock(refs_id).back();
  318. CARBON_CHECK(semantics_ir().GetNode(temporary_id).kind() ==
  319. SemIR::NodeKind::TemporaryStorage)
  320. << "Return slot for function call does not contain a temporary; "
  321. << "initialized multiple times? Have "
  322. << semantics_ir().GetNode(temporary_id);
  323. return AddNode(SemIR::Node::Temporary::Make(
  324. init.parse_node(), init.type_id(), temporary_id, orig_init_id));
  325. }
  326. if (discarded) {
  327. // Don't invent a temporary that we're going to discard.
  328. return SemIR::NodeId::Invalid;
  329. }
  330. // The function has no return slot, but we want to produce a temporary
  331. // object. Materialize one now.
  332. // TODO: Consider using an invalid ID to mean that we immediately
  333. // materialize and initialize a temporary, rather than two separate
  334. // nodes.
  335. auto temporary_id = AddNode(SemIR::Node::TemporaryStorage::Make(
  336. init.parse_node(), init.type_id()));
  337. return AddNode(SemIR::Node::Temporary::Make(
  338. init.parse_node(), init.type_id(), temporary_id, init_id));
  339. }
  340. case SemIR::NodeKind::ArrayInit: {
  341. auto [src_id, refs_id] = init.GetAsArrayInit();
  342. // The return slot should have a materialized temporary in it.
  343. auto temporary_id = semantics_ir().GetNodeBlock(refs_id).back();
  344. CARBON_CHECK(semantics_ir().GetNode(temporary_id).kind() ==
  345. SemIR::NodeKind::TemporaryStorage)
  346. << "Return slot for array init does not contain a temporary; "
  347. << "initialized multiple times? Have "
  348. << semantics_ir().GetNode(temporary_id);
  349. return AddNode(SemIR::Node::Temporary::Make(
  350. init.parse_node(), init.type_id(), temporary_id, orig_init_id));
  351. }
  352. }
  353. }
  354. }
  355. auto Context::MarkInitializerFor(SemIR::NodeId init_id, SemIR::NodeId target_id)
  356. -> void {
  357. while (true) {
  358. SemIR::Node init = semantics_ir().GetNode(init_id);
  359. CARBON_CHECK(SemIR::GetExpressionCategory(semantics_ir(), init_id) ==
  360. SemIR::ExpressionCategory::Initializing)
  361. << "initialization from non-initializing node " << init;
  362. switch (init.kind()) {
  363. default:
  364. CARBON_FATAL() << "Initialization from unexpected node " << init;
  365. case SemIR::NodeKind::StructLiteral:
  366. case SemIR::NodeKind::TupleLiteral:
  367. CARBON_FATAL() << init << " is not modeled as initializing yet";
  368. case SemIR::NodeKind::StubReference:
  369. init_id = init.GetAsStubReference();
  370. continue;
  371. case SemIR::NodeKind::Call: {
  372. // If the callee has a return slot, point it at our target.
  373. auto [refs_id, callee_id] = init.GetAsCall();
  374. if (semantics_ir().GetFunction(callee_id).return_slot_id.is_valid()) {
  375. // Replace the return slot with our given target, and remove the
  376. // tentatively-created temporary.
  377. auto temporary_id = std::exchange(
  378. semantics_ir().GetNodeBlock(refs_id).back(), target_id);
  379. auto temporary = semantics_ir().GetNode(temporary_id);
  380. CARBON_CHECK(temporary.kind() == SemIR::NodeKind::TemporaryStorage)
  381. << "Return slot for function call does not contain a temporary; "
  382. << "initialized multiple times? Have " << temporary;
  383. semantics_ir().ReplaceNode(
  384. temporary_id, SemIR::Node::NoOp::Make(temporary.parse_node()));
  385. }
  386. return;
  387. }
  388. case SemIR::NodeKind::ArrayInit: {
  389. // Rewrite the return slot as a reference to our target. We can't just
  390. // update the index in `refs_id`, like we do for a Call, because there
  391. // will be other references to the return slot for the individual array
  392. // element initializers.
  393. auto [src_id, refs_id] = init.GetAsArrayInit();
  394. auto temporary_id = semantics_ir().GetNodeBlock(refs_id).back();
  395. CARBON_CHECK(semantics_ir().GetNode(temporary_id).kind() ==
  396. SemIR::NodeKind::TemporaryStorage)
  397. << "Return slot for array init does not contain a temporary; "
  398. << "initialized multiple times? Have "
  399. << semantics_ir().GetNode(temporary_id);
  400. semantics_ir().ReplaceNode(
  401. temporary_id,
  402. SemIR::Node::StubReference::Make(
  403. init.parse_node(), semantics_ir().GetNode(target_id).type_id(),
  404. target_id));
  405. return;
  406. }
  407. }
  408. }
  409. }
  410. auto Context::HandleDiscardedExpression(SemIR::NodeId expr_id) -> void {
  411. // If we discard an initializing expression, materialize it first.
  412. if (SemIR::GetExpressionCategory(semantics_ir(), expr_id) ==
  413. SemIR::ExpressionCategory::Initializing) {
  414. FinalizeTemporary(expr_id, /*discarded=*/true);
  415. }
  416. // TODO: This will eventually need to do some "do not discard" analysis.
  417. (void)expr_id;
  418. }
  419. auto Context::ImplicitAsForArgs(Parse::Node call_parse_node,
  420. SemIR::NodeBlockId arg_refs_id,
  421. Parse::Node param_parse_node,
  422. SemIR::NodeBlockId param_refs_id,
  423. bool has_return_slot) -> bool {
  424. // If both arguments and parameters are empty, return quickly. Otherwise,
  425. // we'll fetch both so that errors are consistent.
  426. if (arg_refs_id == SemIR::NodeBlockId::Empty &&
  427. param_refs_id == SemIR::NodeBlockId::Empty) {
  428. return true;
  429. }
  430. auto arg_refs = semantics_ir_->GetNodeBlock(arg_refs_id);
  431. auto param_refs = semantics_ir_->GetNodeBlock(param_refs_id);
  432. if (has_return_slot) {
  433. // There's no entry in the parameter block for the return slot, so ignore
  434. // the corresponding entry in the argument block.
  435. // TODO: Consider adding the return slot to the parameter list.
  436. CARBON_CHECK(!arg_refs.empty()) << "missing return slot";
  437. arg_refs = arg_refs.drop_back();
  438. }
  439. // If sizes mismatch, fail early.
  440. if (arg_refs.size() != param_refs.size()) {
  441. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  442. "{0} argument(s) passed to function expecting "
  443. "{1} argument(s).",
  444. int, int);
  445. CARBON_DIAGNOSTIC(InCallToFunction, Note,
  446. "Calling function declared here.");
  447. emitter_
  448. ->Build(call_parse_node, CallArgCountMismatch, arg_refs.size(),
  449. param_refs.size())
  450. .Note(param_parse_node, InCallToFunction)
  451. .Emit();
  452. return false;
  453. }
  454. if (param_refs.empty()) {
  455. return true;
  456. }
  457. int diag_param_index;
  458. DiagnosticAnnotationScope annotate_diagnostics(emitter_, [&](auto& builder) {
  459. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  460. "Initializing parameter {0} of function declared here.",
  461. int);
  462. builder.Note(param_parse_node, InCallToFunctionParam, diag_param_index + 1);
  463. });
  464. // Check type conversions per-element.
  465. for (auto [i, value_id, param_ref] : llvm::enumerate(arg_refs, param_refs)) {
  466. diag_param_index = i;
  467. auto as_type_id = semantics_ir_->GetNode(param_ref).type_id();
  468. // TODO: Convert to the proper expression category. For now, we assume
  469. // parameters are all `let` bindings.
  470. value_id = ConvertToValueOfType(call_parse_node, value_id, as_type_id);
  471. if (value_id == SemIR::NodeId::BuiltinError) {
  472. return false;
  473. }
  474. arg_refs[i] = value_id;
  475. }
  476. return true;
  477. }
  478. // Performs a conversion from a tuple to an array type.
  479. static auto ConvertTupleToArray(Context& context, SemIR::Node tuple_type,
  480. SemIR::Node array_type,
  481. SemIR::TypeId array_type_id,
  482. SemIR::NodeId value_id) -> SemIR::NodeId {
  483. auto [array_bound_id, element_type_id] = array_type.GetAsArrayType();
  484. auto tuple_elem_types_id = tuple_type.GetAsTupleType();
  485. const auto& tuple_elem_types =
  486. context.semantics_ir().GetTypeBlock(tuple_elem_types_id);
  487. // Skip back over StubReferences to find if we're being initialized from a
  488. // tuple literal.
  489. auto value = context.semantics_ir().GetNode(value_id);
  490. while (value.kind() == SemIR::NodeKind::StubReference) {
  491. value_id = value.GetAsStubReference();
  492. value = context.semantics_ir().GetNode(value_id);
  493. }
  494. llvm::ArrayRef<SemIR::NodeId> literal_elems;
  495. if (value.kind() == SemIR::NodeKind::TupleLiteral) {
  496. literal_elems =
  497. context.semantics_ir().GetNodeBlock(value.GetAsTupleLiteral());
  498. }
  499. // Check that the tuple is the right size.
  500. uint64_t array_bound =
  501. context.semantics_ir().GetArrayBoundValue(array_bound_id);
  502. if (tuple_elem_types.size() != array_bound) {
  503. CARBON_DIAGNOSTIC(
  504. ArrayInitFromLiteralArgCountMismatch, Error,
  505. "Cannot initialize array of {0} element(s) from {1} initializer(s).",
  506. uint64_t, size_t);
  507. CARBON_DIAGNOSTIC(ArrayInitFromExpressionArgCountMismatch, Error,
  508. "Cannot initialize array of {0} element(s) from tuple "
  509. "with {1} element(s).",
  510. uint64_t, size_t);
  511. context.emitter().Emit(
  512. context.semantics_ir().GetNode(value_id).parse_node(),
  513. literal_elems.empty() ? ArrayInitFromExpressionArgCountMismatch
  514. : ArrayInitFromLiteralArgCountMismatch,
  515. array_bound, tuple_elem_types.size());
  516. return SemIR::NodeId::BuiltinError;
  517. }
  518. // If we're initializing from a tuple literal, we will use its elements
  519. // directly. Otherwise, materialize a temporary if needed and index into the
  520. // result.
  521. if (literal_elems.empty()) {
  522. value_id = context.MaterializeIfInitializing(value_id);
  523. }
  524. // Arrays are always initialized in-place. Tentatively allocate a temporary
  525. // as the destination for the array initialization.
  526. auto return_slot_id = context.AddNode(
  527. SemIR::Node::TemporaryStorage::Make(value.parse_node(), array_type_id));
  528. // Initialize each element of the array from the corresponding element of the
  529. // tuple.
  530. llvm::SmallVector<SemIR::NodeId> inits;
  531. inits.reserve(array_bound + 1);
  532. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  533. // TODO: Add a new node kind for indexing an array at a constant index
  534. // so that we don't need an integer literal node here.
  535. auto index_id = context.AddNode(SemIR::Node::IntegerLiteral::Make(
  536. value.parse_node(),
  537. context.CanonicalizeType(SemIR::NodeId::BuiltinIntegerType),
  538. context.semantics_ir().AddIntegerLiteral(llvm::APInt(32, i))));
  539. auto target_id = context.AddNode(SemIR::Node::ArrayIndex::Make(
  540. value.parse_node(), element_type_id, return_slot_id, index_id));
  541. auto src_id =
  542. !literal_elems.empty()
  543. ? literal_elems[i]
  544. : context.AddNode(SemIR::Node::TupleIndex::Make(
  545. value.parse_node(), src_type_id, value_id, index_id));
  546. auto init_id =
  547. context.InitializeAndFinalize(value.parse_node(), target_id, src_id);
  548. if (init_id == SemIR::NodeId::BuiltinError) {
  549. return SemIR::NodeId::BuiltinError;
  550. }
  551. inits.push_back(init_id);
  552. }
  553. // The last element of the refs block contains the return slot for the array
  554. // initialization.
  555. inits.push_back(return_slot_id);
  556. return context.AddNode(
  557. SemIR::Node::ArrayInit::Make(value.parse_node(), array_type_id, value_id,
  558. context.semantics_ir().AddNodeBlock(inits)));
  559. }
  560. auto Context::ImplicitAs(Parse::Node parse_node, SemIR::NodeId value_id,
  561. SemIR::TypeId as_type_id) -> SemIR::NodeId {
  562. // Start by making sure both sides are valid. If any part is invalid, the
  563. // result is invalid and we shouldn't error.
  564. if (value_id == SemIR::NodeId::BuiltinError) {
  565. // If the value is invalid, we can't do much, but do "succeed".
  566. return value_id;
  567. }
  568. auto value = semantics_ir_->GetNode(value_id);
  569. auto value_type_id = value.type_id();
  570. if (value_type_id == SemIR::TypeId::Error ||
  571. as_type_id == SemIR::TypeId::Error) {
  572. return SemIR::NodeId::BuiltinError;
  573. }
  574. if (value_type_id == as_type_id) {
  575. return value_id;
  576. }
  577. auto as_type = semantics_ir_->GetTypeAllowBuiltinTypes(as_type_id);
  578. auto as_type_node = semantics_ir_->GetNode(as_type);
  579. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  580. if (as_type_node.kind() == SemIR::NodeKind::ArrayType) {
  581. auto value_type_node = semantics_ir_->GetNode(
  582. semantics_ir_->GetTypeAllowBuiltinTypes(value_type_id));
  583. if (value_type_node.kind() == SemIR::NodeKind::TupleType) {
  584. // The conversion from tuple to array is `final`, so we don't need a
  585. // fallback path here.
  586. return ConvertTupleToArray(*this, value_type_node, as_type_node,
  587. as_type_id, value_id);
  588. }
  589. }
  590. if (as_type_id == SemIR::TypeId::TypeType) {
  591. // A tuple of types converts to type `type`.
  592. // TODO: This should apply even for non-literal tuples.
  593. if (value.kind() == SemIR::NodeKind::TupleLiteral) {
  594. auto tuple_block_id = value.GetAsTupleLiteral();
  595. llvm::SmallVector<SemIR::TypeId> type_ids;
  596. // If it is empty tuple type, we don't fetch anything.
  597. if (tuple_block_id != SemIR::NodeBlockId::Empty) {
  598. const auto& tuple_block = semantics_ir_->GetNodeBlock(tuple_block_id);
  599. for (auto tuple_node_id : tuple_block) {
  600. // TODO: Eventually ExpressionAsType will insert implicit cast
  601. // instructions. When that happens, this will need to verify the full
  602. // tuple conversion will work before calling it.
  603. type_ids.push_back(
  604. ExpressionAsType(value.parse_node(), tuple_node_id));
  605. }
  606. }
  607. auto tuple_type_id =
  608. CanonicalizeTupleType(value.parse_node(), std::move(type_ids));
  609. return semantics_ir_->GetTypeAllowBuiltinTypes(tuple_type_id);
  610. }
  611. // When converting `{}` to a type, the result is `{} as type`.
  612. if (value.kind() == SemIR::NodeKind::StructLiteral &&
  613. value.GetAsStructLiteral() == SemIR::NodeBlockId::Empty) {
  614. return semantics_ir_->GetType(value_type_id);
  615. }
  616. }
  617. // TODO: Handle ImplicitAs for compatible structs and tuples.
  618. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  619. "Cannot implicitly convert from `{0}` to `{1}`.",
  620. std::string, std::string);
  621. emitter_
  622. ->Build(parse_node, ImplicitAsConversionFailure,
  623. semantics_ir_->StringifyType(
  624. semantics_ir_->GetNode(value_id).type_id()),
  625. semantics_ir_->StringifyType(as_type_id))
  626. .Emit();
  627. return SemIR::NodeId::BuiltinError;
  628. }
  629. auto Context::ParamOrArgStart() -> void { params_or_args_stack_.Push(); }
  630. auto Context::ParamOrArgComma(bool for_args) -> void {
  631. ParamOrArgSave(for_args);
  632. }
  633. auto Context::ParamOrArgEndNoPop(bool for_args, Parse::NodeKind start_kind)
  634. -> void {
  635. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  636. ParamOrArgSave(for_args);
  637. }
  638. }
  639. auto Context::ParamOrArgPop() -> SemIR::NodeBlockId {
  640. return params_or_args_stack_.Pop();
  641. }
  642. auto Context::ParamOrArgEnd(bool for_args, Parse::NodeKind start_kind)
  643. -> SemIR::NodeBlockId {
  644. ParamOrArgEndNoPop(for_args, start_kind);
  645. return ParamOrArgPop();
  646. }
  647. auto Context::ParamOrArgSave(bool for_args) -> void {
  648. auto [entry_parse_node, entry_node_id] =
  649. node_stack_.PopExpressionWithParseNode();
  650. if (for_args) {
  651. // For an argument, we add a stub reference to the expression on the top of
  652. // the stack. There may not be anything on the IR prior to this.
  653. entry_node_id = AddNode(SemIR::Node::StubReference::Make(
  654. entry_parse_node, semantics_ir_->GetNode(entry_node_id).type_id(),
  655. entry_node_id));
  656. }
  657. // Save the param or arg ID.
  658. params_or_args_stack_.AddNodeId(entry_node_id);
  659. }
  660. auto Context::CanonicalizeTypeImpl(
  661. SemIR::NodeKind kind,
  662. llvm::function_ref<void(llvm::FoldingSetNodeID& canonical_id)> profile_type,
  663. llvm::function_ref<SemIR::NodeId()> make_node) -> SemIR::TypeId {
  664. llvm::FoldingSetNodeID canonical_id;
  665. kind.Profile(canonical_id);
  666. profile_type(canonical_id);
  667. void* insert_pos;
  668. auto* node =
  669. canonical_type_nodes_.FindNodeOrInsertPos(canonical_id, insert_pos);
  670. if (node != nullptr) {
  671. return node->type_id();
  672. }
  673. auto node_id = make_node();
  674. auto type_id = semantics_ir_->AddType(node_id);
  675. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  676. type_node_storage_.push_back(
  677. std::make_unique<TypeNode>(canonical_id, type_id));
  678. // In a debug build, check that our insertion position is still valid. It
  679. // could have been invalidated by a misbehaving `make_node`.
  680. CARBON_DCHECK([&] {
  681. void* check_insert_pos;
  682. auto* check_node = canonical_type_nodes_.FindNodeOrInsertPos(
  683. canonical_id, check_insert_pos);
  684. return !check_node && insert_pos == check_insert_pos;
  685. }()) << "Type was created recursively during canonicalization";
  686. canonical_type_nodes_.InsertNode(type_node_storage_.back().get(), insert_pos);
  687. return type_id;
  688. }
  689. // Compute a fingerprint for a tuple type, for use as a key in a folding set.
  690. static auto ProfileTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids,
  691. llvm::FoldingSetNodeID& canonical_id) -> void {
  692. for (auto type_id : type_ids) {
  693. canonical_id.AddInteger(type_id.index);
  694. }
  695. }
  696. // Compute a fingerprint for a type, for use as a key in a folding set.
  697. static auto ProfileType(Context& semantics_context, SemIR::Node node,
  698. llvm::FoldingSetNodeID& canonical_id) -> void {
  699. switch (node.kind()) {
  700. case SemIR::NodeKind::ArrayType: {
  701. auto [bound_id, element_type_id] = node.GetAsArrayType();
  702. canonical_id.AddInteger(
  703. semantics_context.semantics_ir().GetArrayBoundValue(bound_id));
  704. canonical_id.AddInteger(element_type_id.index);
  705. break;
  706. }
  707. case SemIR::NodeKind::Builtin:
  708. canonical_id.AddInteger(node.GetAsBuiltin().AsInt());
  709. break;
  710. case SemIR::NodeKind::CrossReference: {
  711. // TODO: Cross-references should be canonicalized by looking at their
  712. // target rather than treating them as new unique types.
  713. auto [xref_id, node_id] = node.GetAsCrossReference();
  714. canonical_id.AddInteger(xref_id.index);
  715. canonical_id.AddInteger(node_id.index);
  716. break;
  717. }
  718. case SemIR::NodeKind::ConstType:
  719. canonical_id.AddInteger(
  720. semantics_context.GetUnqualifiedType(node.GetAsConstType()).index);
  721. break;
  722. case SemIR::NodeKind::PointerType:
  723. canonical_id.AddInteger(node.GetAsPointerType().index);
  724. break;
  725. case SemIR::NodeKind::StructType: {
  726. auto refs =
  727. semantics_context.semantics_ir().GetNodeBlock(node.GetAsStructType());
  728. for (const auto& ref_id : refs) {
  729. auto ref = semantics_context.semantics_ir().GetNode(ref_id);
  730. auto [name_id, type_id] = ref.GetAsStructTypeField();
  731. canonical_id.AddInteger(name_id.index);
  732. canonical_id.AddInteger(type_id.index);
  733. }
  734. break;
  735. }
  736. case SemIR::NodeKind::StubReference: {
  737. // We rely on stub references not referring to each other to ensure we
  738. // only recurse once here.
  739. auto inner =
  740. semantics_context.semantics_ir().GetNode(node.GetAsStubReference());
  741. CARBON_CHECK(inner.kind() != SemIR::NodeKind::StubReference)
  742. << "A stub reference should never refer to another stub reference.";
  743. ProfileType(semantics_context, inner, canonical_id);
  744. break;
  745. }
  746. case SemIR::NodeKind::TupleType:
  747. ProfileTupleType(
  748. semantics_context.semantics_ir().GetTypeBlock(node.GetAsTupleType()),
  749. canonical_id);
  750. break;
  751. default:
  752. CARBON_FATAL() << "Unexpected type node " << node;
  753. }
  754. }
  755. auto Context::CanonicalizeTypeAndAddNodeIfNew(SemIR::Node node)
  756. -> SemIR::TypeId {
  757. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  758. ProfileType(*this, node, canonical_id);
  759. };
  760. auto make_node = [&] { return AddNode(node); };
  761. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  762. }
  763. auto Context::CanonicalizeType(SemIR::NodeId node_id) -> SemIR::TypeId {
  764. auto it = canonical_types_.find(node_id);
  765. if (it != canonical_types_.end()) {
  766. return it->second;
  767. }
  768. auto node = semantics_ir_->GetNode(node_id);
  769. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  770. ProfileType(*this, node, canonical_id);
  771. };
  772. auto make_node = [&] { return node_id; };
  773. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  774. }
  775. auto Context::CanonicalizeStructType(Parse::Node parse_node,
  776. SemIR::NodeBlockId refs_id)
  777. -> SemIR::TypeId {
  778. return CanonicalizeTypeAndAddNodeIfNew(SemIR::Node::StructType::Make(
  779. parse_node, SemIR::TypeId::TypeType, refs_id));
  780. }
  781. auto Context::CanonicalizeTupleType(Parse::Node parse_node,
  782. llvm::ArrayRef<SemIR::TypeId> type_ids)
  783. -> SemIR::TypeId {
  784. // Defer allocating a SemIR::TypeBlockId until we know this is a new type.
  785. auto profile_tuple = [&](llvm::FoldingSetNodeID& canonical_id) {
  786. ProfileTupleType(type_ids, canonical_id);
  787. };
  788. auto make_tuple_node = [&] {
  789. return AddNode(
  790. SemIR::Node::TupleType::Make(parse_node, SemIR::TypeId::TypeType,
  791. semantics_ir_->AddTypeBlock(type_ids)));
  792. };
  793. return CanonicalizeTypeImpl(SemIR::NodeKind::TupleType, profile_tuple,
  794. make_tuple_node);
  795. }
  796. auto Context::GetPointerType(Parse::Node parse_node,
  797. SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  798. return CanonicalizeTypeAndAddNodeIfNew(SemIR::Node::PointerType::Make(
  799. parse_node, SemIR::TypeId::TypeType, pointee_type_id));
  800. }
  801. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  802. SemIR::Node type_node =
  803. semantics_ir_->GetNode(semantics_ir_->GetTypeAllowBuiltinTypes(type_id));
  804. if (type_node.kind() == SemIR::NodeKind::ConstType) {
  805. return type_node.GetAsConstType();
  806. }
  807. return type_id;
  808. }
  809. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  810. node_stack_.PrintForStackDump(output);
  811. node_block_stack_.PrintForStackDump(output);
  812. params_or_args_stack_.PrintForStackDump(output);
  813. args_type_info_stack_.PrintForStackDump(output);
  814. }
  815. } // namespace Carbon::Check