context.cpp 36 KB

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