convert.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  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/convert.h"
  5. #include <string>
  6. #include <utility>
  7. #include "common/check.h"
  8. #include "llvm/ADT/STLExtras.h"
  9. #include "toolchain/check/context.h"
  10. #include "toolchain/diagnostics/diagnostic_kind.h"
  11. #include "toolchain/parse/node_kind.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/inst.h"
  14. #include "toolchain/sem_ir/inst_kind.h"
  15. namespace Carbon::Check {
  16. // Given an initializing expression, find its return slot. Returns `Invalid` if
  17. // there is no return slot, because the initialization is not performed in
  18. // place.
  19. static auto FindReturnSlotForInitializer(SemIR::File& sem_ir,
  20. SemIR::InstId init_id)
  21. -> SemIR::InstId {
  22. while (true) {
  23. SemIR::Inst init = sem_ir.insts().Get(init_id);
  24. switch (init.kind()) {
  25. default:
  26. CARBON_FATAL() << "Initialization from unexpected inst " << init;
  27. case SemIR::Converted::Kind:
  28. init_id = init.As<SemIR::Converted>().result_id;
  29. continue;
  30. case SemIR::ArrayInit::Kind:
  31. return init.As<SemIR::ArrayInit>().dest_id;
  32. case SemIR::ClassInit::Kind:
  33. return init.As<SemIR::ClassInit>().dest_id;
  34. case SemIR::StructInit::Kind:
  35. return init.As<SemIR::StructInit>().dest_id;
  36. case SemIR::TupleInit::Kind:
  37. return init.As<SemIR::TupleInit>().dest_id;
  38. case SemIR::InitializeFrom::Kind:
  39. return init.As<SemIR::InitializeFrom>().dest_id;
  40. case SemIR::Call::Kind: {
  41. auto call = init.As<SemIR::Call>();
  42. if (!SemIR::GetInitializingRepresentation(sem_ir, call.type_id)
  43. .has_return_slot()) {
  44. return SemIR::InstId::Invalid;
  45. }
  46. return sem_ir.inst_blocks().Get(call.args_id).back();
  47. }
  48. }
  49. }
  50. }
  51. // Marks the initializer `init_id` as initializing `target_id`.
  52. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  53. SemIR::InstId target_id,
  54. PendingBlock& target_block) -> void {
  55. auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id);
  56. if (return_slot_id.is_valid()) {
  57. // Replace the temporary in the return slot with a reference to our target.
  58. CARBON_CHECK(sem_ir.insts().Get(return_slot_id).kind() ==
  59. SemIR::TemporaryStorage::Kind)
  60. << "Return slot for initializer does not contain a temporary; "
  61. << "initialized multiple times? Have "
  62. << sem_ir.insts().Get(return_slot_id);
  63. target_block.MergeReplacing(return_slot_id, target_id);
  64. }
  65. }
  66. // Commits to using a temporary to store the result of the initializing
  67. // expression described by `init_id`, and returns the location of the
  68. // temporary. If `discarded` is `true`, the result is discarded, and no
  69. // temporary will be created if possible; if no temporary is created, the
  70. // return value will be `SemIR::InstId::Invalid`.
  71. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  72. bool discarded) -> SemIR::InstId {
  73. auto& sem_ir = context.sem_ir();
  74. auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id);
  75. if (return_slot_id.is_valid()) {
  76. // The return slot should already have a materialized temporary in it.
  77. CARBON_CHECK(sem_ir.insts().Get(return_slot_id).kind() ==
  78. SemIR::TemporaryStorage::Kind)
  79. << "Return slot for initializer does not contain a temporary; "
  80. << "initialized multiple times? Have "
  81. << sem_ir.insts().Get(return_slot_id);
  82. auto init = sem_ir.insts().Get(init_id);
  83. return context.AddInst(SemIR::Temporary{init.parse_node(), init.type_id(),
  84. return_slot_id, init_id});
  85. }
  86. if (discarded) {
  87. // Don't invent a temporary that we're going to discard.
  88. return SemIR::InstId::Invalid;
  89. }
  90. // The initializer has no return slot, but we want to produce a temporary
  91. // object. Materialize one now.
  92. // TODO: Consider using an invalid ID to mean that we immediately
  93. // materialize and initialize a temporary, rather than two separate
  94. // instructions.
  95. auto init = sem_ir.insts().Get(init_id);
  96. auto temporary_id = context.AddInst(
  97. SemIR::TemporaryStorage{init.parse_node(), init.type_id()});
  98. return context.AddInst(SemIR::Temporary{init.parse_node(), init.type_id(),
  99. temporary_id, init_id});
  100. }
  101. // Materialize a temporary to hold the result of the given expression if it is
  102. // an initializing expression.
  103. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  104. -> SemIR::InstId {
  105. if (GetExprCategory(context.sem_ir(), expr_id) ==
  106. SemIR::ExprCategory::Initializing) {
  107. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  108. }
  109. return expr_id;
  110. }
  111. // Creates and adds an instruction to perform element access into an aggregate.
  112. template <typename AccessInstT, typename InstBlockT>
  113. static auto MakeElemAccessInst(Context& context, Parse::Node parse_node,
  114. SemIR::InstId aggregate_id,
  115. SemIR::TypeId elem_type_id, InstBlockT& block,
  116. std::size_t i) {
  117. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  118. // TODO: Add a new instruction kind for indexing an array at a constant
  119. // index so that we don't need an integer literal instruction here, and
  120. // remove this special case.
  121. auto index_id = block.AddInst(SemIR::IntegerLiteral{
  122. parse_node, context.GetBuiltinType(SemIR::BuiltinKind::IntegerType),
  123. context.sem_ir().integers().Add(llvm::APInt(32, i))});
  124. return block.AddInst(
  125. AccessInstT{parse_node, elem_type_id, aggregate_id, index_id});
  126. } else {
  127. return block.AddInst(AccessInstT{parse_node, elem_type_id, aggregate_id,
  128. SemIR::MemberIndex(i)});
  129. }
  130. }
  131. // Converts an element of one aggregate so that it can be used as an element of
  132. // another aggregate.
  133. //
  134. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  135. // element type, `i` is the index, and `SourceAccessInstT` is the kind of
  136. // instruction used to access the source element.
  137. //
  138. // For the target: `kind` is the kind of conversion or initialization,
  139. // `target_elem_type` is the element type. For initialization, `target_id` is
  140. // the destination, `target_block` is a pending block for target location
  141. // calculations that will be spliced as the return slot of the initializer if
  142. // necessary, `i` is the index, and `TargetAccessInstT` is the kind of
  143. // instruction used to access the destination element.
  144. template <typename SourceAccessInstT, typename TargetAccessInstT>
  145. static auto ConvertAggregateElement(
  146. Context& context, Parse::Node parse_node, SemIR::InstId src_id,
  147. SemIR::TypeId src_elem_type,
  148. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  149. ConversionTarget::Kind kind, SemIR::InstId target_id,
  150. SemIR::TypeId target_elem_type, PendingBlock* target_block, std::size_t i) {
  151. // Compute the location of the source element. This goes into the current code
  152. // block, not into the target block.
  153. // TODO: Ideally we would discard this instruction if it's unused.
  154. auto src_elem_id =
  155. !src_literal_elems.empty()
  156. ? src_literal_elems[i]
  157. : MakeElemAccessInst<SourceAccessInstT>(context, parse_node, src_id,
  158. src_elem_type, context, i);
  159. // If we're performing a conversion rather than an initialization, we won't
  160. // have or need a target.
  161. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  162. if (!target.is_initializer()) {
  163. return Convert(context, parse_node, src_elem_id, target);
  164. }
  165. // Compute the location of the target element and initialize it.
  166. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  167. target.init_block = target_block;
  168. target.init_id = MakeElemAccessInst<TargetAccessInstT>(
  169. context, parse_node, target_id, target_elem_type, *target_block, i);
  170. return Convert(context, parse_node, src_elem_id, target);
  171. }
  172. namespace {
  173. // A handle to a new block that may be modified, with copy-on-write semantics.
  174. //
  175. // The constructor is given the ID of an existing block that provides the
  176. // initial contents of the new block. The new block is lazily allocated; if no
  177. // modifications have been made, the `id()` function will return the original
  178. // block ID.
  179. //
  180. // This is intended to avoid an unnecessary block allocation in the case where
  181. // the new block ends up being exactly the same as the original block.
  182. class CopyOnWriteBlock {
  183. public:
  184. // Constructs the block. If `source_id` is valid, it is used as the initial
  185. // value of the block. Otherwise, uninitialized storage for `size` elements
  186. // is allocated.
  187. CopyOnWriteBlock(SemIR::File& file, SemIR::InstBlockId source_id, size_t size)
  188. : file_(file), source_id_(source_id) {
  189. if (!source_id_.is_valid()) {
  190. id_ = file_.inst_blocks().AddUninitialized(size);
  191. }
  192. }
  193. auto id() -> SemIR::InstBlockId const { return id_; }
  194. auto Set(int i, SemIR::InstId value) -> void {
  195. if (source_id_.is_valid() && file_.inst_blocks().Get(id_)[i] == value) {
  196. return;
  197. }
  198. if (id_ == source_id_) {
  199. id_ = file_.inst_blocks().Add(file_.inst_blocks().Get(source_id_));
  200. }
  201. file_.inst_blocks().Get(id_)[i] = value;
  202. }
  203. private:
  204. SemIR::File& file_;
  205. SemIR::InstBlockId source_id_;
  206. SemIR::InstBlockId id_ = source_id_;
  207. };
  208. } // namespace
  209. // Performs a conversion from a tuple to an array type. This function only
  210. // converts the type, and does not perform a final conversion to the requested
  211. // expression category.
  212. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  213. SemIR::ArrayType array_type,
  214. SemIR::InstId value_id, ConversionTarget target)
  215. -> SemIR::InstId {
  216. auto& sem_ir = context.sem_ir();
  217. auto tuple_elem_types = sem_ir.type_blocks().Get(tuple_type.elements_id);
  218. auto value = sem_ir.insts().Get(value_id);
  219. // If we're initializing from a tuple literal, we will use its elements
  220. // directly. Otherwise, materialize a temporary if needed and index into the
  221. // result.
  222. llvm::ArrayRef<SemIR::InstId> literal_elems;
  223. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  224. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  225. } else {
  226. value_id = MaterializeIfInitializing(context, value_id);
  227. }
  228. // Check that the tuple is the right size.
  229. uint64_t array_bound = sem_ir.GetArrayBoundValue(array_type.bound_id);
  230. if (tuple_elem_types.size() != array_bound) {
  231. CARBON_DIAGNOSTIC(
  232. ArrayInitFromLiteralArgCountMismatch, Error,
  233. "Cannot initialize array of {0} element(s) from {1} initializer(s).",
  234. uint64_t, size_t);
  235. CARBON_DIAGNOSTIC(ArrayInitFromExprArgCountMismatch, Error,
  236. "Cannot initialize array of {0} element(s) from tuple "
  237. "with {1} element(s).",
  238. uint64_t, size_t);
  239. context.emitter().Emit(value.parse_node(),
  240. literal_elems.empty()
  241. ? ArrayInitFromExprArgCountMismatch
  242. : ArrayInitFromLiteralArgCountMismatch,
  243. array_bound, tuple_elem_types.size());
  244. return SemIR::InstId::BuiltinError;
  245. }
  246. PendingBlock target_block_storage(context);
  247. PendingBlock* target_block =
  248. target.init_block ? target.init_block : &target_block_storage;
  249. // Arrays are always initialized in-place. Allocate a temporary as the
  250. // destination for the array initialization if we weren't given one.
  251. SemIR::InstId return_slot_id = target.init_id;
  252. if (!target.init_id.is_valid()) {
  253. return_slot_id = target_block->AddInst(
  254. SemIR::TemporaryStorage{value.parse_node(), target.type_id});
  255. }
  256. // Initialize each element of the array from the corresponding element of the
  257. // tuple.
  258. // TODO: Annotate diagnostics coming from here with the array element index,
  259. // if initializing from a tuple literal.
  260. llvm::SmallVector<SemIR::InstId> inits;
  261. inits.reserve(array_bound + 1);
  262. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  263. // TODO: This call recurses back into conversion. Switch to an iterative
  264. // approach.
  265. auto init_id =
  266. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  267. context, value.parse_node(), value_id, src_type_id, literal_elems,
  268. ConversionTarget::FullInitializer, return_slot_id,
  269. array_type.element_type_id, target_block, i);
  270. if (init_id == SemIR::InstId::BuiltinError) {
  271. return SemIR::InstId::BuiltinError;
  272. }
  273. inits.push_back(init_id);
  274. }
  275. // Flush the temporary here if we didn't insert it earlier, so we can add a
  276. // reference to the return slot.
  277. target_block->InsertHere();
  278. return context.AddInst(SemIR::ArrayInit{value.parse_node(), target.type_id,
  279. sem_ir.inst_blocks().Add(inits),
  280. return_slot_id});
  281. }
  282. // Performs a conversion from a tuple to a tuple type. This function only
  283. // converts the type, and does not perform a final conversion to the requested
  284. // expression category.
  285. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  286. SemIR::TupleType dest_type,
  287. SemIR::InstId value_id, ConversionTarget target)
  288. -> SemIR::InstId {
  289. auto& sem_ir = context.sem_ir();
  290. auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id);
  291. auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id);
  292. auto value = sem_ir.insts().Get(value_id);
  293. // If we're initializing from a tuple literal, we will use its elements
  294. // directly. Otherwise, materialize a temporary if needed and index into the
  295. // result.
  296. llvm::ArrayRef<SemIR::InstId> literal_elems;
  297. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  298. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  299. literal_elems_id = tuple_literal->elements_id;
  300. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  301. } else {
  302. value_id = MaterializeIfInitializing(context, value_id);
  303. }
  304. // Check that the tuples are the same size.
  305. if (src_elem_types.size() != dest_elem_types.size()) {
  306. CARBON_DIAGNOSTIC(TupleInitElementCountMismatch, Error,
  307. "Cannot initialize tuple of {0} element(s) from tuple "
  308. "with {1} element(s).",
  309. size_t, size_t);
  310. context.emitter().Emit(value.parse_node(), TupleInitElementCountMismatch,
  311. dest_elem_types.size(), src_elem_types.size());
  312. return SemIR::InstId::BuiltinError;
  313. }
  314. // If we're forming an initializer, then we want an initializer for each
  315. // element. Otherwise, we want a value representation for each element.
  316. // Perform a final destination store if we're performing an in-place
  317. // initialization.
  318. bool is_init = target.is_initializer();
  319. ConversionTarget::Kind inner_kind =
  320. !is_init ? ConversionTarget::Value
  321. : SemIR::GetInitializingRepresentation(sem_ir, target.type_id).kind ==
  322. SemIR::InitializingRepresentation::InPlace
  323. ? ConversionTarget::FullInitializer
  324. : ConversionTarget::Initializer;
  325. // Initialize each element of the destination from the corresponding element
  326. // of the source.
  327. // TODO: Annotate diagnostics coming from here with the element index.
  328. CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_types.size());
  329. for (auto [i, src_type_id, dest_type_id] :
  330. llvm::enumerate(src_elem_types, dest_elem_types)) {
  331. // TODO: This call recurses back into conversion. Switch to an iterative
  332. // approach.
  333. auto init_id =
  334. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  335. context, value.parse_node(), value_id, src_type_id, literal_elems,
  336. inner_kind, target.init_id, dest_type_id, target.init_block, i);
  337. if (init_id == SemIR::InstId::BuiltinError) {
  338. return SemIR::InstId::BuiltinError;
  339. }
  340. new_block.Set(i, init_id);
  341. }
  342. if (is_init) {
  343. target.init_block->InsertHere();
  344. return context.AddInst(SemIR::TupleInit{value.parse_node(), target.type_id,
  345. new_block.id(), target.init_id});
  346. } else {
  347. return context.AddInst(
  348. SemIR::TupleValue{value.parse_node(), target.type_id, new_block.id()});
  349. }
  350. }
  351. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  352. template <typename TargetAccessInstT>
  353. static auto ConvertStructToStructOrClass(Context& context,
  354. SemIR::StructType src_type,
  355. SemIR::StructType dest_type,
  356. SemIR::InstId value_id,
  357. ConversionTarget target, bool is_class)
  358. -> SemIR::InstId {
  359. auto& sem_ir = context.sem_ir();
  360. auto src_elem_fields = sem_ir.inst_blocks().Get(src_type.fields_id);
  361. auto dest_elem_fields = sem_ir.inst_blocks().Get(dest_type.fields_id);
  362. auto value = sem_ir.insts().Get(value_id);
  363. // If we're initializing from a struct literal, we will use its elements
  364. // directly. Otherwise, materialize a temporary if needed and index into the
  365. // result.
  366. llvm::ArrayRef<SemIR::InstId> literal_elems;
  367. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  368. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  369. literal_elems_id = struct_literal->elements_id;
  370. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  371. } else {
  372. value_id = MaterializeIfInitializing(context, value_id);
  373. }
  374. // Check that the structs are the same size.
  375. // TODO: If not, include the name of the first source field that doesn't
  376. // exist in the destination or vice versa in the diagnostic.
  377. if (src_elem_fields.size() != dest_elem_fields.size()) {
  378. CARBON_DIAGNOSTIC(StructInitElementCountMismatch, Error,
  379. "Cannot initialize {0} with {1} field(s) from struct "
  380. "with {2} field(s).",
  381. llvm::StringLiteral, size_t, size_t);
  382. context.emitter().Emit(
  383. value.parse_node(), StructInitElementCountMismatch,
  384. is_class ? llvm::StringLiteral("class") : llvm::StringLiteral("struct"),
  385. dest_elem_fields.size(), src_elem_fields.size());
  386. return SemIR::InstId::BuiltinError;
  387. }
  388. // Prepare to look up fields in the source by index.
  389. llvm::SmallDenseMap<SemIR::NameId, int32_t> src_field_indexes;
  390. if (src_type.fields_id != dest_type.fields_id) {
  391. for (auto [i, field_id] : llvm::enumerate(src_elem_fields)) {
  392. auto [it, added] = src_field_indexes.insert(
  393. {context.insts().GetAs<SemIR::StructTypeField>(field_id).name_id, i});
  394. CARBON_CHECK(added) << "Duplicate field in source structure";
  395. }
  396. }
  397. // If we're forming an initializer, then we want an initializer for each
  398. // element. Otherwise, we want a value representation for each element.
  399. // Perform a final destination store if we're performing an in-place
  400. // initialization.
  401. bool is_init = target.is_initializer();
  402. ConversionTarget::Kind inner_kind =
  403. !is_init ? ConversionTarget::Value
  404. : SemIR::GetInitializingRepresentation(sem_ir, target.type_id).kind ==
  405. SemIR::InitializingRepresentation::InPlace
  406. ? ConversionTarget::FullInitializer
  407. : ConversionTarget::Initializer;
  408. // Initialize each element of the destination from the corresponding element
  409. // of the source.
  410. // TODO: Annotate diagnostics coming from here with the element index.
  411. CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_fields.size());
  412. for (auto [i, dest_field_id] : llvm::enumerate(dest_elem_fields)) {
  413. auto dest_field =
  414. sem_ir.insts().GetAs<SemIR::StructTypeField>(dest_field_id);
  415. // Find the matching source field.
  416. auto src_field_index = i;
  417. if (src_type.fields_id != dest_type.fields_id) {
  418. auto src_field_it = src_field_indexes.find(dest_field.name_id);
  419. if (src_field_it == src_field_indexes.end()) {
  420. if (literal_elems_id.is_valid()) {
  421. CARBON_DIAGNOSTIC(
  422. StructInitMissingFieldInLiteral, Error,
  423. "Missing value for field `{0}` in struct initialization.",
  424. llvm::StringRef);
  425. context.emitter().Emit(
  426. value.parse_node(), StructInitMissingFieldInLiteral,
  427. sem_ir.names().GetFormatted(dest_field.name_id));
  428. } else {
  429. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  430. "Cannot convert from struct type `{0}` to `{1}`: "
  431. "missing field `{2}` in source type.",
  432. std::string, std::string, llvm::StringRef);
  433. context.emitter().Emit(
  434. value.parse_node(), StructInitMissingFieldInConversion,
  435. sem_ir.StringifyType(value.type_id()),
  436. sem_ir.StringifyType(target.type_id),
  437. sem_ir.names().GetFormatted(dest_field.name_id));
  438. }
  439. return SemIR::InstId::BuiltinError;
  440. }
  441. src_field_index = src_field_it->second;
  442. }
  443. auto src_field = sem_ir.insts().GetAs<SemIR::StructTypeField>(
  444. src_elem_fields[src_field_index]);
  445. // TODO: This call recurses back into conversion. Switch to an iterative
  446. // approach.
  447. auto init_id =
  448. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  449. context, value.parse_node(), value_id, src_field.field_type_id,
  450. literal_elems, inner_kind, target.init_id, dest_field.field_type_id,
  451. target.init_block, src_field_index);
  452. if (init_id == SemIR::InstId::BuiltinError) {
  453. return SemIR::InstId::BuiltinError;
  454. }
  455. new_block.Set(i, init_id);
  456. }
  457. if (is_class) {
  458. target.init_block->InsertHere();
  459. CARBON_CHECK(is_init)
  460. << "Converting directly to a class value is not supported";
  461. return context.AddInst(SemIR::ClassInit{value.parse_node(), target.type_id,
  462. new_block.id(), target.init_id});
  463. } else if (is_init) {
  464. target.init_block->InsertHere();
  465. return context.AddInst(SemIR::StructInit{value.parse_node(), target.type_id,
  466. new_block.id(), target.init_id});
  467. } else {
  468. return context.AddInst(
  469. SemIR::StructValue{value.parse_node(), target.type_id, new_block.id()});
  470. }
  471. }
  472. // Performs a conversion from a struct to a struct type. This function only
  473. // converts the type, and does not perform a final conversion to the requested
  474. // expression category.
  475. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  476. SemIR::StructType dest_type,
  477. SemIR::InstId value_id,
  478. ConversionTarget target) -> SemIR::InstId {
  479. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  480. context, src_type, dest_type, value_id, target, /*is_class=*/false);
  481. }
  482. // Performs a conversion from a struct to a class type. This function only
  483. // converts the type, and does not perform a final conversion to the requested
  484. // expression category.
  485. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  486. SemIR::ClassType dest_type,
  487. SemIR::InstId value_id,
  488. ConversionTarget target) -> SemIR::InstId {
  489. PendingBlock target_block(context);
  490. auto& class_info = context.classes().Get(dest_type.class_id);
  491. if (class_info.inheritance_kind == SemIR::Class::Abstract) {
  492. CARBON_DIAGNOSTIC(ConstructionOfAbstractClass, Error,
  493. "Cannot construct instance of abstract class. "
  494. "Consider using `partial {0}` instead.",
  495. std::string);
  496. context.emitter().Emit(context.insts().Get(value_id).parse_node(),
  497. ConstructionOfAbstractClass,
  498. context.sem_ir().StringifyType(target.type_id));
  499. return SemIR::InstId::BuiltinError;
  500. }
  501. auto dest_struct_type = context.insts().GetAs<SemIR::StructType>(
  502. context.sem_ir().GetTypeAllowBuiltinTypes(
  503. class_info.object_representation_id));
  504. // If we're trying to create a class value, form a temporary for the value to
  505. // point to.
  506. bool need_temporary = !target.is_initializer();
  507. if (need_temporary) {
  508. target.kind = ConversionTarget::Initializer;
  509. target.init_block = &target_block;
  510. target.init_id = target_block.AddInst(SemIR::TemporaryStorage{
  511. context.insts().Get(value_id).parse_node(), target.type_id});
  512. }
  513. auto result_id = ConvertStructToStructOrClass<SemIR::ClassFieldAccess>(
  514. context, src_type, dest_struct_type, value_id, target, /*is_class=*/true);
  515. if (need_temporary) {
  516. target_block.InsertHere();
  517. result_id = context.AddInst(
  518. SemIR::Temporary{context.insts().Get(value_id).parse_node(),
  519. target.type_id, target.init_id, result_id});
  520. }
  521. return result_id;
  522. }
  523. // Returns whether `category` is a valid expression category to produce as a
  524. // result of a conversion with kind `target_kind`, or at most needs a temporary
  525. // to be materialized.
  526. static bool IsValidExprCategoryForConversionTarget(
  527. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) {
  528. switch (target_kind) {
  529. case ConversionTarget::Value:
  530. return category == SemIR::ExprCategory::Value;
  531. case ConversionTarget::ValueOrReference:
  532. case ConversionTarget::Discarded:
  533. return category == SemIR::ExprCategory::Value ||
  534. category == SemIR::ExprCategory::DurableReference ||
  535. category == SemIR::ExprCategory::EphemeralReference ||
  536. category == SemIR::ExprCategory::Initializing;
  537. case ConversionTarget::ExplicitAs:
  538. return true;
  539. case ConversionTarget::Initializer:
  540. case ConversionTarget::FullInitializer:
  541. return category == SemIR::ExprCategory::Initializing;
  542. }
  543. }
  544. static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node,
  545. SemIR::InstId value_id,
  546. ConversionTarget target) -> SemIR::InstId {
  547. auto& sem_ir = context.sem_ir();
  548. auto value = sem_ir.insts().Get(value_id);
  549. auto value_type_id = value.type_id();
  550. auto target_type_inst =
  551. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(target.type_id));
  552. // Various forms of implicit conversion are supported as builtin conversions,
  553. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  554. // prelude. There are a few reasons we need to perform some of these
  555. // conversions as builtins:
  556. //
  557. // 1) Conversions from struct and tuple *literals* have special rules that
  558. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  559. // recurse into the elements of the literal before performing
  560. // initialization in order to avoid unnecessary conversions between
  561. // expression categories that would be performed by `ImplicitAs.Convert`.
  562. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  563. // the value of the facet, not only its type, and therefore cannot be
  564. // modeled by `ImplicitAs`.
  565. // 3) Some of these conversions are used while checking the library
  566. // definition of `ImplicitAs` itself or implementations of it.
  567. //
  568. // We also expect to see better performance by avoiding an `impl` lookup for
  569. // common conversions.
  570. //
  571. // TODO: We should provide a debugging flag to turn off as many of these
  572. // builtin conversions as we can so that we can test that they do the same
  573. // thing as the library implementations.
  574. //
  575. // The builtin conversions that correspond to `impl`s in the library all
  576. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  577. // being specialized in any of these cases.
  578. // If the value is already of the right kind and expression category, there's
  579. // nothing to do. Performing a conversion would decompose and rebuild tuples
  580. // and structs, so it's important that we bail out early in this case.
  581. if (value_type_id == target.type_id) {
  582. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  583. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  584. return value_id;
  585. }
  586. // If the source is an initializing expression, we may be able to pull a
  587. // value right out of it.
  588. if (value_cat == SemIR::ExprCategory::Initializing &&
  589. IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  590. target.kind) &&
  591. SemIR::GetInitializingRepresentation(sem_ir, value_type_id).kind ==
  592. SemIR::InitializingRepresentation::ByCopy) {
  593. auto value_rep = SemIR::GetValueRepresentation(sem_ir, value_type_id);
  594. if (value_rep.kind == SemIR::ValueRepresentation::Copy &&
  595. value_rep.type_id == value_type_id) {
  596. // The initializer produces an object representation by copy, and the
  597. // value representation is a copy of the object representation, so we
  598. // already have a value of the right form.
  599. return context.AddInst(
  600. SemIR::ValueOfInitializer{parse_node, value_type_id, value_id});
  601. }
  602. }
  603. }
  604. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  605. // converts to Ui.
  606. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  607. auto value_type_inst =
  608. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  609. if (auto src_tuple_type = value_type_inst.TryAs<SemIR::TupleType>()) {
  610. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  611. value_id, target);
  612. }
  613. }
  614. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  615. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  616. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  617. // to Ui.
  618. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  619. auto value_type_inst =
  620. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  621. if (auto src_struct_type = value_type_inst.TryAs<SemIR::StructType>()) {
  622. return ConvertStructToStruct(context, *src_struct_type,
  623. *target_struct_type, value_id, target);
  624. }
  625. }
  626. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  627. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  628. auto value_type_inst =
  629. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  630. if (auto src_tuple_type = value_type_inst.TryAs<SemIR::TupleType>()) {
  631. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  632. value_id, target);
  633. }
  634. }
  635. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  636. // if it converts to the struct type that is the class's representation type
  637. // (a struct with the same fields as the class, plus a base field where
  638. // relevant).
  639. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  640. auto value_type_inst =
  641. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  642. if (auto src_struct_type = value_type_inst.TryAs<SemIR::StructType>()) {
  643. return ConvertStructToClass(context, *src_struct_type, *target_class_type,
  644. value_id, target);
  645. }
  646. }
  647. if (target.type_id == SemIR::TypeId::TypeType) {
  648. // A tuple of types converts to type `type`.
  649. // TODO: This should apply even for non-literal tuples.
  650. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  651. llvm::SmallVector<SemIR::TypeId> type_ids;
  652. for (auto tuple_inst_id :
  653. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  654. // TODO: This call recurses back into conversion. Switch to an
  655. // iterative approach.
  656. type_ids.push_back(ExprAsType(context, parse_node, tuple_inst_id));
  657. }
  658. auto tuple_type_id =
  659. context.CanonicalizeTupleType(parse_node, std::move(type_ids));
  660. return sem_ir.GetTypeAllowBuiltinTypes(tuple_type_id);
  661. }
  662. // `{}` converts to `{} as type`.
  663. // TODO: This conversion should also be performed for a non-literal value
  664. // of type `{}`.
  665. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  666. struct_literal &&
  667. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  668. value_id = sem_ir.GetTypeAllowBuiltinTypes(value_type_id);
  669. }
  670. }
  671. // No builtin conversion applies.
  672. return value_id;
  673. }
  674. // Given a value expression, form a corresponding initializer that copies from
  675. // that value, if it is possible to do so.
  676. static auto PerformCopy(Context& context, SemIR::InstId expr_id)
  677. -> SemIR::InstId {
  678. auto expr = context.insts().Get(expr_id);
  679. auto type_id = expr.type_id();
  680. if (type_id == SemIR::TypeId::Error) {
  681. return SemIR::InstId::BuiltinError;
  682. }
  683. // TODO: Directly track on the value representation whether it's a copy of
  684. // the object representation.
  685. auto value_rep = SemIR::GetValueRepresentation(context.sem_ir(), type_id);
  686. if (value_rep.kind == SemIR::ValueRepresentation::Copy &&
  687. value_rep.aggregate_kind == SemIR::ValueRepresentation::NotAggregate &&
  688. value_rep.type_id == type_id) {
  689. // For by-value scalar types, no explicit action is required. Initializing
  690. // from a value expression is treated as copying the value.
  691. return expr_id;
  692. }
  693. // TODO: We don't yet have rules for whether and when a class type is
  694. // copyable, or how to perform the copy.
  695. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  696. "Cannot copy value of type `{0}`.", std::string);
  697. context.emitter().Emit(expr.parse_node(), CopyOfUncopyableType,
  698. context.sem_ir().StringifyType(type_id));
  699. return SemIR::InstId::BuiltinError;
  700. }
  701. auto Convert(Context& context, Parse::Node parse_node, SemIR::InstId expr_id,
  702. ConversionTarget target) -> SemIR::InstId {
  703. auto& sem_ir = context.sem_ir();
  704. auto orig_expr_id = expr_id;
  705. // Start by making sure both sides are valid. If any part is invalid, the
  706. // result is invalid and we shouldn't error.
  707. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::TypeId::Error ||
  708. target.type_id == SemIR::TypeId::Error) {
  709. return SemIR::InstId::BuiltinError;
  710. }
  711. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  712. // TODO: We currently encounter this for use of namespaces and functions.
  713. // We should provide a better diagnostic for inappropriate use of
  714. // namespace names, and allow use of functions as values.
  715. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  716. "Expression cannot be used as a value.");
  717. context.emitter().Emit(sem_ir.insts().Get(expr_id).parse_node(),
  718. UseOfNonExprAsValue);
  719. return SemIR::InstId::BuiltinError;
  720. }
  721. // We can only perform initialization for complete types.
  722. if (!context.TryToCompleteType(target.type_id, [&] {
  723. CARBON_DIAGNOSTIC(IncompleteTypeInInitialization, Error,
  724. "Initialization of incomplete type `{0}`.",
  725. std::string);
  726. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  727. "Forming value of incomplete type `{0}`.",
  728. std::string);
  729. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  730. "Invalid use of incomplete type `{0}`.", std::string);
  731. return context.emitter().Build(
  732. parse_node,
  733. target.is_initializer() ? IncompleteTypeInInitialization
  734. : target.kind == ConversionTarget::Value
  735. ? IncompleteTypeInValueConversion
  736. : IncompleteTypeInConversion,
  737. context.sem_ir().StringifyType(target.type_id, true));
  738. })) {
  739. return SemIR::InstId::BuiltinError;
  740. }
  741. // Check whether any builtin conversion applies.
  742. expr_id = PerformBuiltinConversion(context, parse_node, expr_id, target);
  743. if (expr_id == SemIR::InstId::BuiltinError) {
  744. return expr_id;
  745. }
  746. // If the types don't match at this point, we can't perform the conversion.
  747. // TODO: Look for an `ImplicitAs` impl, or an `As` impl in the case where
  748. // `target.kind == ConversionTarget::ExplicitAs`.
  749. SemIR::Inst expr = sem_ir.insts().Get(expr_id);
  750. if (expr.type_id() != target.type_id) {
  751. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  752. "Cannot implicitly convert from `{0}` to `{1}`.",
  753. std::string, std::string);
  754. CARBON_DIAGNOSTIC(ExplicitAsConversionFailure, Error,
  755. "Cannot convert from `{0}` to `{1}` with `as`.",
  756. std::string, std::string);
  757. context.emitter()
  758. .Build(parse_node,
  759. target.kind == ConversionTarget::ExplicitAs
  760. ? ExplicitAsConversionFailure
  761. : ImplicitAsConversionFailure,
  762. sem_ir.StringifyType(expr.type_id()),
  763. sem_ir.StringifyType(target.type_id))
  764. .Emit();
  765. return SemIR::InstId::BuiltinError;
  766. }
  767. // Track that we performed a type conversion, if we did so.
  768. if (orig_expr_id != expr_id) {
  769. expr_id = context.AddInst(SemIR::Converted{
  770. expr.parse_node(), target.type_id, orig_expr_id, expr_id});
  771. }
  772. // For `as`, don't perform any value category conversions. In particular, an
  773. // identity conversion shouldn't change the expression category.
  774. if (target.kind == ConversionTarget::ExplicitAs) {
  775. return expr_id;
  776. }
  777. // Now perform any necessary value category conversions.
  778. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  779. case SemIR::ExprCategory::NotExpr:
  780. case SemIR::ExprCategory::Mixed:
  781. CARBON_FATAL() << "Unexpected expression " << expr
  782. << " after builtin conversions";
  783. case SemIR::ExprCategory::Error:
  784. return SemIR::InstId::BuiltinError;
  785. case SemIR::ExprCategory::Initializing:
  786. if (target.is_initializer()) {
  787. if (orig_expr_id == expr_id) {
  788. // Don't fill in the return slot if we created the expression through
  789. // a conversion. In that case, we will have created it with the
  790. // target already set.
  791. // TODO: Find a better way to track whether we need to do this.
  792. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  793. *target.init_block);
  794. }
  795. break;
  796. }
  797. // Commit to using a temporary for this initializing expression.
  798. // TODO: Don't create a temporary if the initializing representation
  799. // is already a value representation.
  800. expr_id = FinalizeTemporary(context, expr_id,
  801. target.kind == ConversionTarget::Discarded);
  802. // We now have an ephemeral reference.
  803. [[fallthrough]];
  804. case SemIR::ExprCategory::DurableReference:
  805. case SemIR::ExprCategory::EphemeralReference:
  806. // If a reference expression is an acceptable result, we're done.
  807. if (target.kind == ConversionTarget::ValueOrReference ||
  808. target.kind == ConversionTarget::Discarded) {
  809. break;
  810. }
  811. // If we have a reference and don't want one, form a value binding.
  812. // TODO: Support types with custom value representations.
  813. expr_id = context.AddInst(
  814. SemIR::BindValue{expr.parse_node(), expr.type_id(), expr_id});
  815. // We now have a value expression.
  816. [[fallthrough]];
  817. case SemIR::ExprCategory::Value:
  818. // When initializing from a value, perform a copy.
  819. if (target.is_initializer()) {
  820. expr_id = PerformCopy(context, expr_id);
  821. }
  822. break;
  823. }
  824. // Perform a final destination store, if necessary.
  825. if (target.kind == ConversionTarget::FullInitializer) {
  826. if (auto init_rep =
  827. SemIR::GetInitializingRepresentation(sem_ir, target.type_id);
  828. init_rep.kind == SemIR::InitializingRepresentation::ByCopy) {
  829. target.init_block->InsertHere();
  830. expr_id = context.AddInst(SemIR::InitializeFrom{
  831. parse_node, target.type_id, expr_id, target.init_id});
  832. }
  833. }
  834. return expr_id;
  835. }
  836. auto Initialize(Context& context, Parse::Node parse_node,
  837. SemIR::InstId target_id, SemIR::InstId value_id)
  838. -> SemIR::InstId {
  839. PendingBlock target_block(context);
  840. return Convert(context, parse_node, value_id,
  841. {.kind = ConversionTarget::Initializer,
  842. .type_id = context.sem_ir().insts().Get(target_id).type_id(),
  843. .init_id = target_id,
  844. .init_block = &target_block});
  845. }
  846. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  847. -> SemIR::InstId {
  848. auto expr = context.sem_ir().insts().Get(expr_id);
  849. return Convert(context, expr.parse_node(), expr_id,
  850. {.kind = ConversionTarget::Value, .type_id = expr.type_id()});
  851. }
  852. auto ConvertToValueOrReferenceExpr(Context& context, SemIR::InstId expr_id)
  853. -> SemIR::InstId {
  854. auto expr = context.sem_ir().insts().Get(expr_id);
  855. return Convert(
  856. context, expr.parse_node(), expr_id,
  857. {.kind = ConversionTarget::ValueOrReference, .type_id = expr.type_id()});
  858. }
  859. auto ConvertToValueOfType(Context& context, Parse::Node parse_node,
  860. SemIR::InstId value_id, SemIR::TypeId type_id)
  861. -> SemIR::InstId {
  862. return Convert(context, parse_node, value_id,
  863. {.kind = ConversionTarget::Value, .type_id = type_id});
  864. }
  865. auto ConvertToBoolValue(Context& context, Parse::Node parse_node,
  866. SemIR::InstId value_id) -> SemIR::InstId {
  867. return ConvertToValueOfType(
  868. context, parse_node, value_id,
  869. context.GetBuiltinType(SemIR::BuiltinKind::BoolType));
  870. }
  871. auto ConvertForExplicitAs(Context& context, Parse::Node as_node,
  872. SemIR::InstId value_id, SemIR::TypeId type_id)
  873. -> SemIR::InstId {
  874. return Convert(context, as_node, value_id,
  875. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  876. }
  877. CARBON_DIAGNOSTIC(InCallToFunction, Note, "Calling function declared here.");
  878. // Convert the object argument in a method call to match the `self` parameter.
  879. static auto ConvertSelf(Context& context, Parse::Node call_parse_node,
  880. Parse::Node callee_parse_node,
  881. SemIR::SelfParam self_param, SemIR::InstId self_id)
  882. -> SemIR::InstId {
  883. if (!self_id.is_valid()) {
  884. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  885. "Missing object argument in method call.");
  886. context.emitter()
  887. .Build(call_parse_node, MissingObjectInMethodCall)
  888. .Note(callee_parse_node, InCallToFunction)
  889. .Emit();
  890. return SemIR::InstId::BuiltinError;
  891. }
  892. DiagnosticAnnotationScope annotate_diagnostics(
  893. &context.emitter(), [&](auto& builder) {
  894. CARBON_DIAGNOSTIC(
  895. InCallToFunctionSelf, Note,
  896. "Initializing `{0}` parameter of method declared here.",
  897. llvm::StringLiteral);
  898. builder.Note(self_param.parse_node, InCallToFunctionSelf,
  899. self_param.is_addr_self.index
  900. ? llvm::StringLiteral("addr self")
  901. : llvm::StringLiteral("self"));
  902. });
  903. // For `addr self`, take the address of the object argument.
  904. auto self_or_addr_id = self_id;
  905. if (self_param.is_addr_self.index) {
  906. self_or_addr_id = ConvertToValueOrReferenceExpr(context, self_or_addr_id);
  907. auto self = context.insts().Get(self_or_addr_id);
  908. switch (SemIR::GetExprCategory(context.sem_ir(), self_id)) {
  909. case SemIR::ExprCategory::Error:
  910. case SemIR::ExprCategory::DurableReference:
  911. case SemIR::ExprCategory::EphemeralReference:
  912. break;
  913. default:
  914. CARBON_DIAGNOSTIC(AddrSelfIsNonReference, Error,
  915. "`addr self` method cannot be invoked on a value.");
  916. context.emitter().Emit(call_parse_node, AddrSelfIsNonReference);
  917. return SemIR::InstId::BuiltinError;
  918. }
  919. self_or_addr_id = context.AddInst(SemIR::AddressOf{
  920. self.parse_node(),
  921. context.GetPointerType(self.parse_node(), self.type_id()),
  922. self_or_addr_id});
  923. }
  924. return ConvertToValueOfType(context, call_parse_node, self_or_addr_id,
  925. self_param.type_id);
  926. }
  927. auto ConvertCallArgs(Context& context, Parse::Node call_parse_node,
  928. SemIR::InstId self_id,
  929. llvm::ArrayRef<SemIR::InstId> arg_refs,
  930. SemIR::InstId return_storage_id,
  931. Parse::Node callee_parse_node,
  932. SemIR::InstBlockId implicit_param_refs_id,
  933. SemIR::InstBlockId param_refs_id) -> SemIR::InstBlockId {
  934. auto implicit_param_refs =
  935. context.sem_ir().inst_blocks().Get(implicit_param_refs_id);
  936. auto param_refs = context.sem_ir().inst_blocks().Get(param_refs_id);
  937. // If sizes mismatch, fail early.
  938. if (arg_refs.size() != param_refs.size()) {
  939. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  940. "{0} argument(s) passed to function expecting "
  941. "{1} argument(s).",
  942. int, int);
  943. context.emitter()
  944. .Build(call_parse_node, CallArgCountMismatch, arg_refs.size(),
  945. param_refs.size())
  946. .Note(callee_parse_node, InCallToFunction)
  947. .Emit();
  948. return SemIR::InstBlockId::Invalid;
  949. }
  950. // Start building a block to hold the converted arguments.
  951. llvm::SmallVector<SemIR::InstId> args;
  952. args.reserve(implicit_param_refs.size() + param_refs.size() +
  953. return_storage_id.is_valid());
  954. // Check implicit parameters.
  955. for (auto implicit_param_id : implicit_param_refs) {
  956. auto param = context.insts().Get(implicit_param_id);
  957. if (auto self_param = param.TryAs<SemIR::SelfParam>()) {
  958. auto converted_self_id = ConvertSelf(
  959. context, call_parse_node, callee_parse_node, *self_param, self_id);
  960. if (converted_self_id == SemIR::InstId::BuiltinError) {
  961. return SemIR::InstBlockId::Invalid;
  962. }
  963. args.push_back(converted_self_id);
  964. } else {
  965. // TODO: Form argument values for implicit parameters.
  966. context.TODO(call_parse_node, "Call with implicit parameters");
  967. return SemIR::InstBlockId::Invalid;
  968. }
  969. }
  970. int diag_param_index;
  971. DiagnosticAnnotationScope annotate_diagnostics(
  972. &context.emitter(), [&](auto& builder) {
  973. CARBON_DIAGNOSTIC(
  974. InCallToFunctionParam, Note,
  975. "Initializing parameter {0} of function declared here.", int);
  976. builder.Note(callee_parse_node, InCallToFunctionParam,
  977. diag_param_index + 1);
  978. });
  979. // Check type conversions per-element.
  980. for (auto [i, arg_id, param_id] : llvm::enumerate(arg_refs, param_refs)) {
  981. diag_param_index = i;
  982. auto param_type_id = context.sem_ir().insts().Get(param_id).type_id();
  983. // TODO: Convert to the proper expression category. For now, we assume
  984. // parameters are all `let` bindings.
  985. auto converted_arg_id =
  986. ConvertToValueOfType(context, call_parse_node, arg_id, param_type_id);
  987. if (converted_arg_id == SemIR::InstId::BuiltinError) {
  988. return SemIR::InstBlockId::Invalid;
  989. }
  990. args.push_back(converted_arg_id);
  991. }
  992. // Track the return storage, if present.
  993. if (return_storage_id.is_valid()) {
  994. args.push_back(return_storage_id);
  995. }
  996. return context.inst_blocks().Add(args);
  997. }
  998. auto ExprAsType(Context& context, Parse::Node parse_node,
  999. SemIR::InstId value_id) -> SemIR::TypeId {
  1000. auto type_inst_id = ConvertToValueOfType(context, parse_node, value_id,
  1001. SemIR::TypeId::TypeType);
  1002. if (type_inst_id == SemIR::InstId::BuiltinError) {
  1003. return SemIR::TypeId::Error;
  1004. }
  1005. auto type_id = context.CanonicalizeType(type_inst_id);
  1006. if (type_id == SemIR::TypeId::Error) {
  1007. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1008. "Cannot evaluate type expression.");
  1009. context.emitter().Emit(parse_node, TypeExprEvaluationFailure);
  1010. }
  1011. return type_id;
  1012. }
  1013. } // namespace Carbon::Check