type_completion.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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/type_completion.h"
  5. #include "common/concepts.h"
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/cpp/import.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/inst.h"
  11. #include "toolchain/check/literal.h"
  12. #include "toolchain/check/require_impls.h"
  13. #include "toolchain/check/type.h"
  14. #include "toolchain/diagnostics/format_providers.h"
  15. #include "toolchain/sem_ir/constant.h"
  16. #include "toolchain/sem_ir/generic.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/specific_interface.h"
  19. #include "toolchain/sem_ir/specific_named_constraint.h"
  20. #include "toolchain/sem_ir/type_info.h"
  21. #include "toolchain/sem_ir/typed_insts.h"
  22. namespace Carbon::Check {
  23. auto NoteIncompleteClass(Context& context, SemIR::ClassId class_id,
  24. DiagnosticBuilder& builder) -> void {
  25. const auto& class_info = context.classes().Get(class_id);
  26. CARBON_CHECK(!class_info.is_complete(), "Class is not incomplete");
  27. if (class_info.has_definition_started()) {
  28. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  29. "class is incomplete within its definition");
  30. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  31. } else {
  32. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  33. "class was forward declared here");
  34. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  35. }
  36. }
  37. auto NoteIncompleteInterface(Context& context, SemIR::InterfaceId interface_id,
  38. DiagnosticBuilder& builder) -> void {
  39. const auto& interface_info = context.interfaces().Get(interface_id);
  40. CARBON_CHECK(!interface_info.is_complete(), "Interface is not incomplete");
  41. if (interface_info.is_being_defined()) {
  42. CARBON_DIAGNOSTIC(InterfaceIncompleteWithinDefinition, Note,
  43. "interface is currently being defined");
  44. builder.Note(interface_info.definition_id,
  45. InterfaceIncompleteWithinDefinition);
  46. } else {
  47. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  48. "interface was forward declared here");
  49. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  50. }
  51. }
  52. auto NoteAbstractClass(Context& context, SemIR::ClassId class_id,
  53. bool direct_use, DiagnosticBuilder& builder) -> void {
  54. const auto& class_info = context.classes().Get(class_id);
  55. CARBON_CHECK(
  56. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  57. "Class is not abstract");
  58. CARBON_DIAGNOSTIC(
  59. ClassAbstractHere, Note,
  60. "{0:=0:uses class that|=1:class} was declared abstract here",
  61. Diagnostics::IntAsSelect);
  62. builder.Note(class_info.definition_id, ClassAbstractHere,
  63. static_cast<int>(direct_use));
  64. }
  65. static auto NoteIncompleteNamedConstraint(
  66. Context& context, SemIR::NamedConstraintId named_constraint_id,
  67. DiagnosticBuilder& builder) -> void {
  68. const auto& constraint = context.named_constraints().Get(named_constraint_id);
  69. CARBON_CHECK(!constraint.is_complete(), "Named constraint is not incomplete");
  70. if (constraint.is_being_defined()) {
  71. CARBON_DIAGNOSTIC(NamedConstraintIncompleteWithinDefinition, Note,
  72. "constraint is currently being defined");
  73. builder.Note(constraint.definition_id,
  74. NamedConstraintIncompleteWithinDefinition);
  75. } else {
  76. CARBON_DIAGNOSTIC(NamedConstraintForwardDeclaredHere, Note,
  77. "constraint was forward declared here");
  78. builder.Note(constraint.latest_decl_id(),
  79. NamedConstraintForwardDeclaredHere);
  80. }
  81. }
  82. static auto RequireCompleteFacetType(Context& context, SemIR::LocId loc_id,
  83. const SemIR::FacetType& facet_type,
  84. MakeDiagnosticBuilderFn diagnoser)
  85. -> bool {
  86. const auto& facet_type_info =
  87. context.facet_types().Get(facet_type.facet_type_id);
  88. for (auto extends : facet_type_info.extend_constraints) {
  89. auto interface_id = extends.interface_id;
  90. const auto& interface = context.interfaces().Get(interface_id);
  91. if (!interface.is_complete()) {
  92. if (diagnoser) {
  93. auto builder = diagnoser();
  94. NoteIncompleteInterface(context, interface_id, builder);
  95. builder.Emit();
  96. }
  97. return false;
  98. }
  99. if (interface.generic_id.has_value()) {
  100. ResolveSpecificDefinition(context, loc_id, extends.specific_id);
  101. }
  102. }
  103. for (auto extends : facet_type_info.extend_named_constraints) {
  104. auto named_constraint_id = extends.named_constraint_id;
  105. const auto& constraint =
  106. context.named_constraints().Get(named_constraint_id);
  107. if (!constraint.is_complete()) {
  108. if (diagnoser) {
  109. auto builder = diagnoser();
  110. NoteIncompleteNamedConstraint(context, named_constraint_id, builder);
  111. builder.Emit();
  112. }
  113. return false;
  114. }
  115. if (constraint.generic_id.has_value()) {
  116. ResolveSpecificDefinition(context, loc_id, extends.specific_id);
  117. }
  118. }
  119. return true;
  120. }
  121. namespace {
  122. // Worklist-based type completion mechanism.
  123. //
  124. // When attempting to complete a type, we may find other types that also need to
  125. // be completed: types nested within that type, and the value representation of
  126. // the type. In order to complete a type without recursing arbitrarily deeply,
  127. // we use a worklist of tasks:
  128. //
  129. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  130. // nested within a type to the work list.
  131. // - A `BuildInfo` step computes the `CompleteTypeInfo` for a type, once all of
  132. // its nested types are complete, and marks the type as complete.
  133. class TypeCompleter {
  134. public:
  135. // `context` mut not be null.
  136. TypeCompleter(Context* context, SemIR::LocId loc_id,
  137. MakeDiagnosticBuilderFn diagnoser)
  138. : context_(context), loc_id_(loc_id), diagnoser_(diagnoser) {}
  139. // Attempts to complete the given type. Returns true if it is now complete,
  140. // false if it could not be completed.
  141. auto Complete(SemIR::TypeId type_id) -> bool;
  142. private:
  143. enum class Phase : int8_t {
  144. // The next step is to add nested types to the list of types to complete.
  145. AddNestedIncompleteTypes,
  146. // The next step is to build the `CompleteTypeInfo` for the type.
  147. BuildInfo,
  148. };
  149. struct WorkItem {
  150. SemIR::TypeId type_id;
  151. Phase phase;
  152. };
  153. // Adds `type_id` to the work list, if it's not already complete.
  154. auto Push(SemIR::TypeId type_id) -> void;
  155. // Runs the next step.
  156. auto ProcessStep() -> bool;
  157. // Adds any types nested within `type_inst` that need to be complete for
  158. // `type_inst` to be complete to our work list.
  159. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool;
  160. // Makes an empty value representation, which is used for types that have no
  161. // state, such as empty structs and tuples.
  162. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr;
  163. // Makes a dependent value representation, which is used for symbolic types.
  164. auto MakeDependentValueRepr(SemIR::TypeId type_id) const -> SemIR::ValueRepr;
  165. // Makes a value representation that uses pass-by-copy, copying the given
  166. // type.
  167. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  168. SemIR::ValueRepr::AggregateKind aggregate_kind =
  169. SemIR::ValueRepr::NotAggregate) const
  170. -> SemIR::ValueRepr;
  171. // Makes a value representation that uses pass-by-address with the given
  172. // pointee type.
  173. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  174. SemIR::ValueRepr::AggregateKind aggregate_kind =
  175. SemIR::ValueRepr::NotAggregate) const
  176. -> SemIR::ValueRepr;
  177. // Gets the value representation of a nested type, which should already be
  178. // complete.
  179. auto GetNestedInfo(SemIR::TypeId nested_type_id) const
  180. -> SemIR::CompleteTypeInfo;
  181. template <typename InstT>
  182. requires(InstT::Kind.template IsAnyOf<
  183. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  184. SemIR::CharLiteralType, SemIR::ErrorInst, SemIR::FacetType,
  185. SemIR::FloatLiteralType, SemIR::FloatType, SemIR::FormType,
  186. SemIR::IntType, SemIR::IntLiteralType, SemIR::NamespaceType,
  187. SemIR::PatternType, SemIR::PointerType,
  188. SemIR::RequireSpecificDefinitionType, SemIR::SpecificFunctionType,
  189. SemIR::TypeType, SemIR::VtableType, SemIR::WitnessType>())
  190. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  191. -> SemIR::CompleteTypeInfo {
  192. return {.value_repr = MakeCopyValueRepr(type_id)};
  193. }
  194. auto BuildStructOrTupleValueRepr(size_t num_elements,
  195. SemIR::TypeId elementwise_rep,
  196. bool same_as_object_rep) const
  197. -> SemIR::ValueRepr;
  198. auto BuildInfoForInst(SemIR::TypeId type_id,
  199. SemIR::StructType struct_type) const
  200. -> SemIR::CompleteTypeInfo;
  201. auto BuildInfoForInst(SemIR::TypeId type_id,
  202. SemIR::TupleType tuple_type) const
  203. -> SemIR::CompleteTypeInfo;
  204. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::ArrayType /*inst*/) const
  205. -> SemIR::CompleteTypeInfo;
  206. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ClassType inst) const
  207. -> SemIR::CompleteTypeInfo;
  208. template <typename InstT>
  209. requires(InstT::Kind.template IsAnyOf<
  210. SemIR::AssociatedEntityType, SemIR::CppOverloadSetType,
  211. SemIR::CppTemplateNameType, SemIR::FunctionType,
  212. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  213. SemIR::GenericInterfaceType, SemIR::GenericNamedConstraintType,
  214. SemIR::InstType, SemIR::UnboundElementType, SemIR::WhereExpr>())
  215. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  216. -> SemIR::CompleteTypeInfo {
  217. // These types have no runtime operations, so we use an empty value
  218. // representation.
  219. //
  220. // TODO: There is information we could model here:
  221. // - For an interface, we could use a witness.
  222. // - For an associated entity, we could use an index into the witness.
  223. // - For an unbound element, we could use an index or offset.
  224. return {.value_repr = MakeEmptyValueRepr()};
  225. }
  226. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ConstType inst) const
  227. -> SemIR::CompleteTypeInfo;
  228. auto BuildInfoForInst(SemIR::TypeId type_id,
  229. SemIR::CustomLayoutType inst) const
  230. -> SemIR::CompleteTypeInfo;
  231. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  232. SemIR::MaybeUnformedType inst) const
  233. -> SemIR::CompleteTypeInfo;
  234. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  235. SemIR::PartialType inst) const
  236. -> SemIR::CompleteTypeInfo;
  237. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  238. SemIR::ImplWitnessAssociatedConstant inst) const
  239. -> SemIR::CompleteTypeInfo;
  240. template <typename InstT>
  241. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  242. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  243. -> SemIR::CompleteTypeInfo {
  244. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  245. }
  246. template <typename InstT>
  247. requires(InstT::Kind.is_symbolic_when_type())
  248. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  249. -> SemIR::CompleteTypeInfo {
  250. return {.value_repr = MakeDependentValueRepr(type_id)};
  251. }
  252. // Builds and returns the `CompleteTypeInfo` for the given type. All nested
  253. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  254. auto BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  255. -> SemIR::CompleteTypeInfo;
  256. Context* context_;
  257. llvm::SmallVector<WorkItem> work_list_;
  258. SemIR::LocId loc_id_;
  259. MakeDiagnosticBuilderFn diagnoser_;
  260. };
  261. } // namespace
  262. auto TypeCompleter::Complete(SemIR::TypeId type_id) -> bool {
  263. Push(type_id);
  264. while (!work_list_.empty()) {
  265. if (!ProcessStep()) {
  266. return false;
  267. }
  268. }
  269. return true;
  270. }
  271. auto TypeCompleter::Push(SemIR::TypeId type_id) -> void {
  272. if (!context_->types().IsComplete(type_id)) {
  273. work_list_.push_back(
  274. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  275. }
  276. }
  277. auto TypeCompleter::ProcessStep() -> bool {
  278. auto [type_id, phase] = work_list_.back();
  279. // We might have enqueued the same type more than once. Just skip the
  280. // type if it's already complete.
  281. if (context_->types().IsComplete(type_id)) {
  282. work_list_.pop_back();
  283. return true;
  284. }
  285. auto inst_id = context_->types().GetInstId(type_id);
  286. auto inst = context_->insts().Get(inst_id);
  287. auto old_work_list_size = work_list_.size();
  288. switch (phase) {
  289. case Phase::AddNestedIncompleteTypes:
  290. if (!AddNestedIncompleteTypes(inst)) {
  291. return false;
  292. }
  293. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  294. "AddNestedIncompleteTypes should not remove work items");
  295. work_list_[old_work_list_size - 1].phase = Phase::BuildInfo;
  296. break;
  297. case Phase::BuildInfo: {
  298. auto info = BuildInfo(type_id, inst);
  299. context_->types().SetComplete(type_id, info);
  300. CARBON_CHECK(old_work_list_size == work_list_.size(),
  301. "BuildInfo should not change work items");
  302. work_list_.pop_back();
  303. // Also complete the value representation type, if necessary. This
  304. // should never fail: the value representation shouldn't require any
  305. // additional nested types to be complete.
  306. if (!context_->types().IsComplete(info.value_repr.type_id)) {
  307. work_list_.push_back(
  308. {.type_id = info.value_repr.type_id, .phase = Phase::BuildInfo});
  309. }
  310. // For a pointer representation, the pointee also needs to be complete.
  311. if (info.value_repr.kind == SemIR::ValueRepr::Pointer) {
  312. if (info.value_repr.type_id == SemIR::ErrorInst::TypeId) {
  313. break;
  314. }
  315. auto pointee_type_id =
  316. context_->sem_ir().GetPointeeType(info.value_repr.type_id);
  317. if (!context_->types().IsComplete(pointee_type_id)) {
  318. work_list_.push_back(
  319. {.type_id = pointee_type_id, .phase = Phase::BuildInfo});
  320. }
  321. }
  322. break;
  323. }
  324. }
  325. return true;
  326. }
  327. auto TypeCompleter::AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  328. CARBON_KIND_SWITCH(type_inst) {
  329. case CARBON_KIND(SemIR::ArrayType inst): {
  330. Push(context_->types().GetTypeIdForTypeInstId(inst.element_type_inst_id));
  331. break;
  332. }
  333. case CARBON_KIND(SemIR::StructType inst): {
  334. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  335. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  336. }
  337. break;
  338. }
  339. case CARBON_KIND(SemIR::TupleType inst): {
  340. for (auto element_type_id : context_->types().GetBlockAsTypeIds(
  341. context_->inst_blocks().Get(inst.type_elements_id))) {
  342. Push(element_type_id);
  343. }
  344. break;
  345. }
  346. case CARBON_KIND(SemIR::ClassType inst): {
  347. auto& class_info = context_->classes().Get(inst.class_id);
  348. // If the class was imported from C++, ask Clang to try to complete it.
  349. if (!class_info.is_complete() && class_info.scope_id.has_value()) {
  350. auto& scope = context_->name_scopes().Get(class_info.scope_id);
  351. if (scope.clang_decl_context_id().has_value()) {
  352. if (!ImportClassDefinitionForClangDecl(
  353. *context_, loc_id_, inst.class_id,
  354. scope.clang_decl_context_id())) {
  355. // Clang produced a diagnostic. Don't produce one of our own.
  356. return false;
  357. }
  358. }
  359. }
  360. if (!class_info.is_complete()) {
  361. if (diagnoser_) {
  362. auto builder = diagnoser_();
  363. NoteIncompleteClass(*context_, inst.class_id, builder);
  364. builder.Emit();
  365. }
  366. return false;
  367. }
  368. if (inst.specific_id.has_value()) {
  369. ResolveSpecificDefinition(*context_, loc_id_, inst.specific_id);
  370. }
  371. if (auto adapted_type_id =
  372. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  373. adapted_type_id.has_value()) {
  374. Push(adapted_type_id);
  375. } else {
  376. Push(class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id));
  377. }
  378. break;
  379. }
  380. case CARBON_KIND(SemIR::ConstType inst): {
  381. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  382. break;
  383. }
  384. case CARBON_KIND(SemIR::CustomLayoutType inst): {
  385. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  386. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  387. }
  388. break;
  389. }
  390. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  391. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  392. break;
  393. }
  394. case CARBON_KIND(SemIR::PartialType inst): {
  395. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  396. break;
  397. }
  398. case CARBON_KIND(SemIR::FacetType inst): {
  399. if (!RequireCompleteFacetType(*context_, loc_id_, inst, diagnoser_)) {
  400. return false;
  401. }
  402. break;
  403. }
  404. default:
  405. break;
  406. }
  407. return true;
  408. }
  409. auto TypeCompleter::MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  410. return {.kind = SemIR::ValueRepr::None,
  411. .type_id = GetTupleType(*context_, {})};
  412. }
  413. auto TypeCompleter::MakeDependentValueRepr(SemIR::TypeId type_id) const
  414. -> SemIR::ValueRepr {
  415. return {.kind = SemIR::ValueRepr::Dependent, .type_id = type_id};
  416. }
  417. auto TypeCompleter::MakeCopyValueRepr(
  418. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  419. -> SemIR::ValueRepr {
  420. return {.kind = SemIR::ValueRepr::Copy,
  421. .aggregate_kind = aggregate_kind,
  422. .type_id = rep_id};
  423. }
  424. auto TypeCompleter::MakePointerValueRepr(
  425. SemIR::TypeId pointee_id,
  426. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  427. // TODO: Should we add `const` qualification to `pointee_id`?
  428. return {.kind = SemIR::ValueRepr::Pointer,
  429. .aggregate_kind = aggregate_kind,
  430. .type_id = GetPointerType(*context_,
  431. context_->types().GetInstId(pointee_id))};
  432. }
  433. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  434. -> SemIR::CompleteTypeInfo {
  435. CARBON_CHECK(context_->types().IsComplete(nested_type_id),
  436. "Nested type should already be complete");
  437. auto info = context_->types().GetCompleteTypeInfo(nested_type_id);
  438. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  439. "Complete type should have a value representation");
  440. return info;
  441. }
  442. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  443. SemIR::TypeId elementwise_rep,
  444. bool same_as_object_rep) const
  445. -> SemIR::ValueRepr {
  446. SemIR::ValueRepr::AggregateKind aggregate_kind =
  447. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  448. : SemIR::ValueRepr::ValueAggregate;
  449. if (num_elements == 1) {
  450. // The value representation for a struct or tuple with a single element
  451. // is a struct or tuple containing the value representation of the
  452. // element.
  453. // TODO: Consider doing the same whenever `elementwise_rep` is
  454. // sufficiently small.
  455. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  456. }
  457. // For a struct or tuple with multiple fields, we use a pointer
  458. // to the elementwise value representation.
  459. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  460. }
  461. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  462. SemIR::StructType struct_type) const
  463. -> SemIR::CompleteTypeInfo {
  464. auto fields = context_->struct_type_fields().Get(struct_type.fields_id);
  465. if (fields.empty()) {
  466. return {.value_repr = MakeEmptyValueRepr()};
  467. }
  468. // Find the value representation for each field, and construct a struct
  469. // of value representations.
  470. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  471. value_rep_fields.reserve(fields.size());
  472. bool same_as_object_rep = true;
  473. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  474. for (auto field : fields) {
  475. auto field_type_id =
  476. context_->types().GetTypeIdForTypeInstId(field.type_inst_id);
  477. auto field_info = GetNestedInfo(field_type_id);
  478. if (!field_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  479. field_type_id)) {
  480. same_as_object_rep = false;
  481. field.type_inst_id =
  482. context_->types().GetInstId(field_info.value_repr.type_id);
  483. }
  484. value_rep_fields.push_back(field);
  485. // Take the first non-None abstract_class_id, if any.
  486. if (field_info.abstract_class_id.has_value() &&
  487. !abstract_class_id.has_value()) {
  488. abstract_class_id = field_info.abstract_class_id;
  489. }
  490. }
  491. auto value_rep =
  492. same_as_object_rep
  493. ? type_id
  494. : GetStructType(
  495. *context_,
  496. context_->struct_type_fields().AddCanonical(value_rep_fields));
  497. return {.value_repr = BuildStructOrTupleValueRepr(fields.size(), value_rep,
  498. same_as_object_rep),
  499. .abstract_class_id = abstract_class_id};
  500. }
  501. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  502. SemIR::TupleType tuple_type) const
  503. -> SemIR::CompleteTypeInfo {
  504. // TODO: Share more code with structs.
  505. auto elements = context_->inst_blocks().Get(tuple_type.type_elements_id);
  506. if (elements.empty()) {
  507. return {.value_repr = MakeEmptyValueRepr()};
  508. }
  509. // Find the value representation for each element, and construct a tuple
  510. // of value representations.
  511. llvm::SmallVector<SemIR::InstId> value_rep_elements;
  512. value_rep_elements.reserve(elements.size());
  513. bool same_as_object_rep = true;
  514. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  515. for (auto element_type_id : context_->types().GetBlockAsTypeIds(elements)) {
  516. auto element_info = GetNestedInfo(element_type_id);
  517. if (!element_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  518. element_type_id)) {
  519. same_as_object_rep = false;
  520. }
  521. value_rep_elements.push_back(
  522. context_->types().GetInstId(element_info.value_repr.type_id));
  523. // Take the first non-None abstract_class_id, if any.
  524. if (element_info.abstract_class_id.has_value() &&
  525. !abstract_class_id.has_value()) {
  526. abstract_class_id = element_info.abstract_class_id;
  527. }
  528. }
  529. auto value_rep = same_as_object_rep
  530. ? type_id
  531. : GetTupleType(*context_, value_rep_elements);
  532. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  533. same_as_object_rep),
  534. .abstract_class_id = abstract_class_id};
  535. }
  536. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  537. SemIR::ArrayType /*inst*/) const
  538. -> SemIR::CompleteTypeInfo {
  539. // For arrays, it's convenient to always use a pointer representation,
  540. // even when the array has zero or one element, in order to support
  541. // indexing.
  542. return {.value_repr =
  543. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate)};
  544. }
  545. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  546. SemIR::ClassType inst) const
  547. -> SemIR::CompleteTypeInfo {
  548. auto& class_info = context_->classes().Get(inst.class_id);
  549. auto abstract_class_id =
  550. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  551. ? inst.class_id
  552. : SemIR::ClassId::None;
  553. // The value representation of an adapter is the value representation of
  554. // its adapted type.
  555. if (auto adapted_type_id =
  556. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  557. adapted_type_id.has_value()) {
  558. auto info = GetNestedInfo(adapted_type_id);
  559. info.abstract_class_id = abstract_class_id;
  560. return info;
  561. }
  562. // Otherwise, the value representation for a class is a pointer to the
  563. // object representation.
  564. // TODO: Support customized value representations for classes.
  565. // TODO: Pick a better value representation when possible.
  566. return {.value_repr = MakePointerValueRepr(
  567. class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id),
  568. SemIR::ValueRepr::ObjectAggregate),
  569. .abstract_class_id = abstract_class_id};
  570. }
  571. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  572. SemIR::ConstType inst) const
  573. -> SemIR::CompleteTypeInfo {
  574. // The value representation of `const T` is the same as that of `T`.
  575. // Objects are not modifiable through their value representations.
  576. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  577. }
  578. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  579. SemIR::CustomLayoutType /*inst*/) const
  580. -> SemIR::CompleteTypeInfo {
  581. // TODO: Should we support other value representations for custom layout
  582. // types?
  583. return {.value_repr = MakePointerValueRepr(type_id)};
  584. }
  585. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  586. SemIR::MaybeUnformedType inst) const
  587. -> SemIR::CompleteTypeInfo {
  588. // `MaybeUnformed(T)` has the same value representation as `T` if that value
  589. // representation preserves all the bytes of the value, including any padding
  590. // bits. Otherwise we need to use a different representation.
  591. auto inner_type_id = context_->types().GetTypeIdForTypeInstId(inst.inner_id);
  592. auto nested = GetNestedInfo(inner_type_id);
  593. if (nested.value_repr.kind == SemIR::ValueRepr::Custom) {
  594. nested.value_repr = MakePointerValueRepr(type_id);
  595. } else if (nested.value_repr.kind == SemIR::ValueRepr::Copy) {
  596. auto type_inst = context_->types().GetAsInst(nested.value_repr.type_id);
  597. // TODO: Should ValueRepr::IsCopyOfObjectRepr return false for `bool`?
  598. if (!nested.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  599. inner_type_id) ||
  600. type_inst.Is<SemIR::BoolType>()) {
  601. nested.value_repr = MakePointerValueRepr(type_id);
  602. }
  603. // TODO: Handle any other types that we treat as having discarded padding
  604. // bits. For now there are no such types, as all class types and all structs
  605. // and tuples with more than one element are passed indirectly.
  606. }
  607. return nested;
  608. }
  609. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  610. SemIR::PartialType inst) const
  611. -> SemIR::CompleteTypeInfo {
  612. // The value representation of `partial T` is the same as that of `T`.
  613. // Objects are not modifiable through their value representations.
  614. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  615. }
  616. auto TypeCompleter::BuildInfoForInst(
  617. SemIR::TypeId /*type_id*/, SemIR::ImplWitnessAssociatedConstant inst) const
  618. -> SemIR::CompleteTypeInfo {
  619. return GetNestedInfo(inst.type_id);
  620. }
  621. // Builds and returns the value representation for the given type. All nested
  622. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  623. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  624. -> SemIR::CompleteTypeInfo {
  625. // Use overload resolution to select the implementation, producing compile
  626. // errors when BuildInfoForInst isn't defined for a given instruction.
  627. CARBON_KIND_SWITCH(inst) {
  628. #define CARBON_SEM_IR_INST_KIND(Name) \
  629. case CARBON_KIND(SemIR::Name typed_inst): { \
  630. return BuildInfoForInst(type_id, typed_inst); \
  631. }
  632. #include "toolchain/sem_ir/inst_kind.def"
  633. }
  634. }
  635. auto TryToCompleteType(Context& context, SemIR::TypeId type_id,
  636. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  637. -> bool {
  638. return TypeCompleter(&context, loc_id, diagnoser).Complete(type_id);
  639. }
  640. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  641. bool complete =
  642. TypeCompleter(&context, SemIR::LocId::None, nullptr).Complete(type_id);
  643. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  644. context.types().GetAsInst(type_id));
  645. }
  646. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  647. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  648. -> bool {
  649. CARBON_CHECK(diagnoser);
  650. if (!TypeCompleter(&context, loc_id, diagnoser).Complete(type_id)) {
  651. return false;
  652. }
  653. // For a symbolic type, create an instruction to require the corresponding
  654. // specific type to be complete.
  655. if (type_id.is_symbolic()) {
  656. // TODO: Deduplicate these.
  657. AddInstInNoBlock(
  658. context, loc_id,
  659. SemIR::RequireCompleteType{
  660. .type_id =
  661. GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  662. .complete_type_inst_id = context.types().GetInstId(type_id)});
  663. }
  664. return true;
  665. }
  666. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  667. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  668. MakeDiagnosticBuilderFn abstract_diagnoser) -> bool {
  669. // TODO: For symbolic types, should add an implicit constraint that they are
  670. // not abstract.
  671. CARBON_CHECK(abstract_diagnoser);
  672. // The representation of a facet type does not depend on its definition, so
  673. // they are considered "concrete" even when not complete.
  674. if (context.types().IsFacetType(type_id)) {
  675. return true;
  676. }
  677. if (!RequireCompleteType(context, type_id, loc_id, diagnoser)) {
  678. return false;
  679. }
  680. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  681. if (complete_info.abstract_class_id.has_value()) {
  682. auto builder = abstract_diagnoser();
  683. if (builder) {
  684. bool direct_use = false;
  685. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  686. if (inst->class_id == complete_info.abstract_class_id) {
  687. direct_use = true;
  688. }
  689. }
  690. NoteAbstractClass(context, complete_info.abstract_class_id, direct_use,
  691. builder);
  692. builder.Emit();
  693. }
  694. return false;
  695. }
  696. return true;
  697. }
  698. // Require all named constraints in the facet type are identified. For a named
  699. // constraint, this means the constraint definition is complete.
  700. static auto RequireIdentifiedNamedConstraints(
  701. Context& context, const SemIR::FacetTypeInfo& facet_type_info,
  702. MakeDiagnosticBuilderFn diagnoser) -> bool {
  703. auto named_constraint_ids = llvm::map_range(
  704. llvm::concat<const SemIR::SpecificNamedConstraint>(
  705. facet_type_info.extend_named_constraints,
  706. facet_type_info.self_impls_named_constraints),
  707. [](SemIR::SpecificNamedConstraint s) { return s.named_constraint_id; });
  708. for (auto named_constraint_id : named_constraint_ids) {
  709. const auto& constraint =
  710. context.named_constraints().Get(named_constraint_id);
  711. if (!constraint.is_complete()) {
  712. if (diagnoser) {
  713. auto builder = diagnoser();
  714. NoteIncompleteNamedConstraint(context, named_constraint_id, builder);
  715. builder.Emit();
  716. }
  717. return false;
  718. }
  719. }
  720. return true;
  721. }
  722. // Returns the `facet_type` mapped into `specific_id`. If an error results, it
  723. // returns None. In particular, this can surface as a monomorphization error
  724. // where the facet type was valid as a symbolic but becomes invalid with some
  725. // concrete specific.
  726. static auto TryGetRequireImplsFacetTypeInEnclosingSpecific(
  727. Context& context, const SemIR::RequireImpls& require,
  728. SemIR::SpecificId enclosing_specific_id) -> SemIR::FacetTypeId {
  729. auto require_specific = GetRequireImplsSpecificFromEnclosingSpecific(
  730. context, require, enclosing_specific_id);
  731. auto const_id = GetConstantValueInRequireImplsSpecific(
  732. context, require_specific, require.facet_type_inst_id);
  733. if (auto facet_type_in_specific = context.insts().TryGetAs<SemIR::FacetType>(
  734. context.constant_values().GetInstId(const_id))) {
  735. return facet_type_in_specific->facet_type_id;
  736. }
  737. // An ErrorInst was encountered.
  738. return SemIR::FacetTypeId::None;
  739. }
  740. auto RequireIdentifiedFacetType(Context& context, SemIR::LocId loc_id,
  741. const SemIR::FacetType& facet_type,
  742. MakeDiagnosticBuilderFn diagnoser)
  743. -> SemIR::IdentifiedFacetTypeId {
  744. if (auto identified_id =
  745. context.identified_facet_types().TryGetId(facet_type.facet_type_id);
  746. identified_id.has_value()) {
  747. return identified_id;
  748. }
  749. // Work queue.
  750. llvm::SmallVector<SemIR::FacetTypeId> extend_facet_types = {
  751. facet_type.facet_type_id};
  752. llvm::SmallVector<SemIR::FacetTypeId> impls_facet_types;
  753. // Outputs for the IdentifiedFacetType.
  754. llvm::SmallVector<SemIR::SpecificInterface> extends;
  755. llvm::SmallVector<SemIR::SpecificInterface> self_impls;
  756. while (true) {
  757. auto next_facet_type_id = SemIR::FacetTypeId::None;
  758. bool facet_type_extends = false;
  759. if (!extend_facet_types.empty()) {
  760. next_facet_type_id = extend_facet_types.pop_back_val();
  761. facet_type_extends = true;
  762. } else if (!impls_facet_types.empty()) {
  763. next_facet_type_id = impls_facet_types.pop_back_val();
  764. facet_type_extends = false;
  765. } else {
  766. break;
  767. }
  768. const auto& facet_type_info = context.facet_types().Get(next_facet_type_id);
  769. if (!RequireIdentifiedNamedConstraints(context, facet_type_info,
  770. diagnoser)) {
  771. return SemIR::IdentifiedFacetTypeId::None;
  772. }
  773. if (facet_type_extends) {
  774. llvm::append_range(extends, facet_type_info.extend_constraints);
  775. } else {
  776. llvm::append_range(self_impls, facet_type_info.extend_constraints);
  777. }
  778. llvm::append_range(self_impls, facet_type_info.self_impls_constraints);
  779. Diagnostics::AnnotationScope annotate_diagnostics(
  780. &context.emitter(), [&](auto& builder) {
  781. CARBON_DIAGNOSTIC(IdentifyingFacetTypeHere, Note,
  782. "identifying facet type {0} here",
  783. SemIR::FacetTypeId);
  784. builder.Note(loc_id, IdentifyingFacetTypeHere,
  785. facet_type.facet_type_id);
  786. });
  787. for (auto extends : facet_type_info.extend_named_constraints) {
  788. const auto& constraint =
  789. context.named_constraints().Get(extends.named_constraint_id);
  790. for (auto require_impls_id : context.require_impls_blocks().Get(
  791. constraint.require_impls_block_id)) {
  792. const auto& require = context.require_impls().Get(require_impls_id);
  793. auto facet_type_id = TryGetRequireImplsFacetTypeInEnclosingSpecific(
  794. context, require, extends.specific_id);
  795. if (facet_type_id.has_value()) {
  796. if (facet_type_extends && require.extend_self) {
  797. extend_facet_types.push_back(facet_type_id);
  798. } else {
  799. impls_facet_types.push_back(facet_type_id);
  800. }
  801. }
  802. }
  803. }
  804. for (auto impls : facet_type_info.self_impls_named_constraints) {
  805. const auto& constraint =
  806. context.named_constraints().Get(impls.named_constraint_id);
  807. for (auto require_impls_id : context.require_impls_blocks().Get(
  808. constraint.require_impls_block_id)) {
  809. const auto& require = context.require_impls().Get(require_impls_id);
  810. auto facet_type_id = TryGetRequireImplsFacetTypeInEnclosingSpecific(
  811. context, require, impls.specific_id);
  812. if (facet_type_id.has_value()) {
  813. impls_facet_types.push_back(facet_type_id);
  814. }
  815. }
  816. }
  817. }
  818. // TODO: Process other kinds of requirements.
  819. return context.identified_facet_types().Add(facet_type.facet_type_id,
  820. {extends, self_impls});
  821. }
  822. auto AsCompleteType(Context& context, SemIR::TypeId type_id,
  823. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  824. -> SemIR::TypeId {
  825. return RequireCompleteType(context, type_id, loc_id, diagnoser)
  826. ? type_id
  827. : SemIR::ErrorInst::TypeId;
  828. }
  829. // Returns the type `type_id` if it is a concrete type, or produces an
  830. // incomplete or abstract type error and returns an error type. This is a
  831. // convenience wrapper around `RequireConcreteType`.
  832. auto AsConcreteType(Context& context, SemIR::TypeId type_id,
  833. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  834. MakeDiagnosticBuilderFn abstract_diagnoser)
  835. -> SemIR::TypeId {
  836. return RequireConcreteType(context, type_id, loc_id, diagnoser,
  837. abstract_diagnoser)
  838. ? type_id
  839. : SemIR::ErrorInst::TypeId;
  840. }
  841. } // namespace Carbon::Check