convert.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  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. SemIR::Inst init = sem_ir.insts().Get(init_id);
  23. switch (init.kind()) {
  24. default:
  25. CARBON_FATAL() << "Initialization from unexpected inst " << init;
  26. case SemIR::ClassInit::Kind:
  27. case SemIR::StructInit::Kind:
  28. case SemIR::TupleInit::Kind:
  29. // TODO: Track a return slot for these initializers.
  30. CARBON_FATAL() << init
  31. << " should be created with its return slot already "
  32. "filled in properly";
  33. case SemIR::InitializeFrom::Kind: {
  34. return init.As<SemIR::InitializeFrom>().dest_id;
  35. }
  36. case SemIR::Call::Kind: {
  37. auto call = init.As<SemIR::Call>();
  38. if (!SemIR::GetInitializingRepresentation(sem_ir, call.type_id)
  39. .has_return_slot()) {
  40. return SemIR::InstId::Invalid;
  41. }
  42. return sem_ir.inst_blocks().Get(call.args_id).back();
  43. }
  44. case SemIR::ArrayInit::Kind: {
  45. return sem_ir.inst_blocks()
  46. .Get(init.As<SemIR::ArrayInit>().inits_and_return_slot_id)
  47. .back();
  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 (GetExpressionCategory(context.sem_ir(), expr_id) ==
  106. SemIR::ExpressionCategory::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(ArrayInitFromExpressionArgCountMismatch, 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. ? ArrayInitFromExpressionArgCountMismatch
  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. // The last element of the refs block contains the return slot for the array
  276. // initialization. Flush the temporary here if we didn't insert it earlier.
  277. target_block->InsertHere();
  278. inits.push_back(return_slot_id);
  279. return context.AddInst(SemIR::ArrayInit{value.parse_node(), target.type_id,
  280. value_id,
  281. sem_ir.inst_blocks().Add(inits)});
  282. }
  283. // Performs a conversion from a tuple to a tuple type. This function only
  284. // converts the type, and does not perform a final conversion to the requested
  285. // expression category.
  286. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  287. SemIR::TupleType dest_type,
  288. SemIR::InstId value_id, ConversionTarget target)
  289. -> SemIR::InstId {
  290. auto& sem_ir = context.sem_ir();
  291. auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id);
  292. auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id);
  293. auto value = sem_ir.insts().Get(value_id);
  294. // If we're initializing from a tuple literal, we will use its elements
  295. // directly. Otherwise, materialize a temporary if needed and index into the
  296. // result.
  297. llvm::ArrayRef<SemIR::InstId> literal_elems;
  298. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  299. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  300. literal_elems_id = tuple_literal->elements_id;
  301. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  302. } else {
  303. value_id = MaterializeIfInitializing(context, value_id);
  304. }
  305. // Check that the tuples are the same size.
  306. if (src_elem_types.size() != dest_elem_types.size()) {
  307. CARBON_DIAGNOSTIC(TupleInitElementCountMismatch, Error,
  308. "Cannot initialize tuple of {0} element(s) from tuple "
  309. "with {1} element(s).",
  310. size_t, size_t);
  311. context.emitter().Emit(value.parse_node(), TupleInitElementCountMismatch,
  312. dest_elem_types.size(), src_elem_types.size());
  313. return SemIR::InstId::BuiltinError;
  314. }
  315. // If we're forming an initializer, then we want an initializer for each
  316. // element. Otherwise, we want a value representation for each element.
  317. // Perform a final destination store if we're performing an in-place
  318. // initialization.
  319. bool is_init = target.is_initializer();
  320. ConversionTarget::Kind inner_kind =
  321. !is_init ? ConversionTarget::Value
  322. : SemIR::GetInitializingRepresentation(sem_ir, target.type_id).kind ==
  323. SemIR::InitializingRepresentation::InPlace
  324. ? ConversionTarget::FullInitializer
  325. : ConversionTarget::Initializer;
  326. // Initialize each element of the destination from the corresponding element
  327. // of the source.
  328. // TODO: Annotate diagnostics coming from here with the element index.
  329. CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_types.size());
  330. for (auto [i, src_type_id, dest_type_id] :
  331. llvm::enumerate(src_elem_types, dest_elem_types)) {
  332. // TODO: This call recurses back into conversion. Switch to an iterative
  333. // approach.
  334. auto init_id =
  335. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  336. context, value.parse_node(), value_id, src_type_id, literal_elems,
  337. inner_kind, target.init_id, dest_type_id, target.init_block, i);
  338. if (init_id == SemIR::InstId::BuiltinError) {
  339. return SemIR::InstId::BuiltinError;
  340. }
  341. new_block.Set(i, init_id);
  342. }
  343. return is_init ? context.AddInst(SemIR::TupleInit{value.parse_node(),
  344. target.type_id, value_id,
  345. new_block.id()})
  346. : context.AddInst(SemIR::TupleValue{value.parse_node(),
  347. target.type_id, value_id,
  348. new_block.id()});
  349. }
  350. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  351. template <typename TargetAccessInstT>
  352. static auto ConvertStructToStructOrClass(Context& context,
  353. SemIR::StructType src_type,
  354. SemIR::StructType dest_type,
  355. SemIR::InstId value_id,
  356. ConversionTarget target, bool is_class)
  357. -> SemIR::InstId {
  358. auto& sem_ir = context.sem_ir();
  359. auto src_elem_fields = sem_ir.inst_blocks().Get(src_type.fields_id);
  360. auto dest_elem_fields = sem_ir.inst_blocks().Get(dest_type.fields_id);
  361. auto value = sem_ir.insts().Get(value_id);
  362. // If we're initializing from a struct literal, we will use its elements
  363. // directly. Otherwise, materialize a temporary if needed and index into the
  364. // result.
  365. llvm::ArrayRef<SemIR::InstId> literal_elems;
  366. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  367. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  368. literal_elems_id = struct_literal->elements_id;
  369. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  370. } else {
  371. value_id = MaterializeIfInitializing(context, value_id);
  372. }
  373. // Check that the structs are the same size.
  374. // TODO: If not, include the name of the first source field that doesn't
  375. // exist in the destination or vice versa in the diagnostic.
  376. if (src_elem_fields.size() != dest_elem_fields.size()) {
  377. CARBON_DIAGNOSTIC(StructInitElementCountMismatch, Error,
  378. "Cannot initialize {0} with {1} field(s) from struct "
  379. "with {2} field(s).",
  380. llvm::StringLiteral, size_t, size_t);
  381. context.emitter().Emit(
  382. value.parse_node(), StructInitElementCountMismatch,
  383. is_class ? llvm::StringLiteral("class") : llvm::StringLiteral("struct"),
  384. dest_elem_fields.size(), src_elem_fields.size());
  385. return SemIR::InstId::BuiltinError;
  386. }
  387. // Prepare to look up fields in the source by index.
  388. llvm::SmallDenseMap<SemIR::NameId, int32_t> src_field_indexes;
  389. if (src_type.fields_id != dest_type.fields_id) {
  390. for (auto [i, field_id] : llvm::enumerate(src_elem_fields)) {
  391. auto [it, added] = src_field_indexes.insert(
  392. {context.insts().GetAs<SemIR::StructTypeField>(field_id).name_id, i});
  393. CARBON_CHECK(added) << "Duplicate field in source structure";
  394. }
  395. }
  396. // If we're forming an initializer, then we want an initializer for each
  397. // element. Otherwise, we want a value representation for each element.
  398. // Perform a final destination store if we're performing an in-place
  399. // initialization.
  400. bool is_init = target.is_initializer();
  401. ConversionTarget::Kind inner_kind =
  402. !is_init ? ConversionTarget::Value
  403. : SemIR::GetInitializingRepresentation(sem_ir, target.type_id).kind ==
  404. SemIR::InitializingRepresentation::InPlace
  405. ? ConversionTarget::FullInitializer
  406. : ConversionTarget::Initializer;
  407. // Initialize each element of the destination from the corresponding element
  408. // of the source.
  409. // TODO: Annotate diagnostics coming from here with the element index.
  410. CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_fields.size());
  411. for (auto [i, dest_field_id] : llvm::enumerate(dest_elem_fields)) {
  412. auto dest_field =
  413. sem_ir.insts().GetAs<SemIR::StructTypeField>(dest_field_id);
  414. // Find the matching source field.
  415. auto src_field_index = i;
  416. if (src_type.fields_id != dest_type.fields_id) {
  417. auto src_field_it = src_field_indexes.find(dest_field.name_id);
  418. if (src_field_it == src_field_indexes.end()) {
  419. if (literal_elems_id.is_valid()) {
  420. CARBON_DIAGNOSTIC(
  421. StructInitMissingFieldInLiteral, Error,
  422. "Missing value for field `{0}` in struct initialization.",
  423. llvm::StringRef);
  424. context.emitter().Emit(
  425. value.parse_node(), StructInitMissingFieldInLiteral,
  426. sem_ir.names().GetFormatted(dest_field.name_id));
  427. } else {
  428. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  429. "Cannot convert from struct type `{0}` to `{1}`: "
  430. "missing field `{2}` in source type.",
  431. std::string, std::string, llvm::StringRef);
  432. context.emitter().Emit(
  433. value.parse_node(), StructInitMissingFieldInConversion,
  434. sem_ir.StringifyType(value.type_id()),
  435. sem_ir.StringifyType(target.type_id),
  436. sem_ir.names().GetFormatted(dest_field.name_id));
  437. }
  438. return SemIR::InstId::BuiltinError;
  439. }
  440. src_field_index = src_field_it->second;
  441. }
  442. auto src_field = sem_ir.insts().GetAs<SemIR::StructTypeField>(
  443. src_elem_fields[src_field_index]);
  444. // TODO: This call recurses back into conversion. Switch to an iterative
  445. // approach.
  446. auto init_id =
  447. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  448. context, value.parse_node(), value_id, src_field.field_type_id,
  449. literal_elems, inner_kind, target.init_id, dest_field.field_type_id,
  450. target.init_block, src_field_index);
  451. if (init_id == SemIR::InstId::BuiltinError) {
  452. return SemIR::InstId::BuiltinError;
  453. }
  454. new_block.Set(i, init_id);
  455. }
  456. if (is_class) {
  457. CARBON_CHECK(is_init)
  458. << "Converting directly to a class value is not supported";
  459. return context.AddInst(SemIR::ClassInit{value.parse_node(), target.type_id,
  460. value_id, new_block.id()});
  461. } else if (is_init) {
  462. return context.AddInst(SemIR::StructInit{value.parse_node(), target.type_id,
  463. value_id, new_block.id()});
  464. } else {
  465. return context.AddInst(SemIR::StructValue{
  466. value.parse_node(), target.type_id, value_id, new_block.id()});
  467. }
  468. }
  469. // Performs a conversion from a struct to a struct type. This function only
  470. // converts the type, and does not perform a final conversion to the requested
  471. // expression category.
  472. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  473. SemIR::StructType dest_type,
  474. SemIR::InstId value_id,
  475. ConversionTarget target) -> SemIR::InstId {
  476. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  477. context, src_type, dest_type, value_id, target, /*is_class=*/false);
  478. }
  479. // Performs a conversion from a struct to a class type. This function only
  480. // converts the type, and does not perform a final conversion to the requested
  481. // expression category.
  482. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  483. SemIR::ClassType dest_type,
  484. SemIR::InstId value_id,
  485. ConversionTarget target) -> SemIR::InstId {
  486. PendingBlock target_block(context);
  487. auto dest_struct_type = context.insts().GetAs<SemIR::StructType>(
  488. context.sem_ir().GetTypeAllowBuiltinTypes(
  489. context.classes().Get(dest_type.class_id).object_representation_id));
  490. // If we're trying to create a class value, form a temporary for the value to
  491. // point to.
  492. bool need_temporary = !target.is_initializer();
  493. if (need_temporary) {
  494. target.kind = ConversionTarget::Initializer;
  495. target.init_block = &target_block;
  496. target.init_id = target_block.AddInst(SemIR::TemporaryStorage{
  497. context.insts().Get(value_id).parse_node(), target.type_id});
  498. }
  499. auto result_id = ConvertStructToStructOrClass<SemIR::ClassFieldAccess>(
  500. context, src_type, dest_struct_type, value_id, target, /*is_class=*/true);
  501. if (need_temporary) {
  502. target_block.InsertHere();
  503. result_id = context.AddInst(
  504. SemIR::Temporary{context.insts().Get(value_id).parse_node(),
  505. target.type_id, target.init_id, result_id});
  506. }
  507. return result_id;
  508. }
  509. // Returns whether `category` is a valid expression category to produce as a
  510. // result of a conversion with kind `target_kind`, or at most needs a temporary
  511. // to be materialized.
  512. static bool IsValidExpressionCategoryForConversionTarget(
  513. SemIR::ExpressionCategory category, ConversionTarget::Kind target_kind) {
  514. switch (target_kind) {
  515. case ConversionTarget::Value:
  516. return category == SemIR::ExpressionCategory::Value;
  517. case ConversionTarget::ValueOrReference:
  518. case ConversionTarget::Discarded:
  519. return category == SemIR::ExpressionCategory::Value ||
  520. category == SemIR::ExpressionCategory::DurableReference ||
  521. category == SemIR::ExpressionCategory::EphemeralReference ||
  522. category == SemIR::ExpressionCategory::Initializing;
  523. case ConversionTarget::ExplicitAs:
  524. return true;
  525. case ConversionTarget::Initializer:
  526. case ConversionTarget::FullInitializer:
  527. return category == SemIR::ExpressionCategory::Initializing;
  528. }
  529. }
  530. static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node,
  531. SemIR::InstId value_id,
  532. ConversionTarget target) -> SemIR::InstId {
  533. auto& sem_ir = context.sem_ir();
  534. auto value = sem_ir.insts().Get(value_id);
  535. auto value_type_id = value.type_id();
  536. auto target_type_inst =
  537. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(target.type_id));
  538. // Various forms of implicit conversion are supported as builtin conversions,
  539. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  540. // prelude. There are a few reasons we need to perform some of these
  541. // conversions as builtins:
  542. //
  543. // 1) Conversions from struct and tuple *literals* have special rules that
  544. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  545. // recurse into the elements of the literal before performing
  546. // initialization in order to avoid unnecessary conversions between
  547. // expression categories that would be performed by `ImplicitAs.Convert`.
  548. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  549. // the value of the facet, not only its type, and therefore cannot be
  550. // modeled by `ImplicitAs`.
  551. // 3) Some of these conversions are used while checking the library
  552. // definition of `ImplicitAs` itself or implementations of it.
  553. //
  554. // We also expect to see better performance by avoiding an `impl` lookup for
  555. // common conversions.
  556. //
  557. // TODO: We should provide a debugging flag to turn off as many of these
  558. // builtin conversions as we can so that we can test that they do the same
  559. // thing as the library implementations.
  560. //
  561. // The builtin conversions that correspond to `impl`s in the library all
  562. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  563. // being specialized in any of these cases.
  564. // If the value is already of the right kind and expression category, there's
  565. // nothing to do. Performing a conversion would decompose and rebuild tuples
  566. // and structs, so it's important that we bail out early in this case.
  567. if (value_type_id == target.type_id) {
  568. auto value_cat = SemIR::GetExpressionCategory(sem_ir, value_id);
  569. if (IsValidExpressionCategoryForConversionTarget(value_cat, target.kind)) {
  570. return value_id;
  571. }
  572. // If the source is an initializing expression, we may be able to pull a
  573. // value right out of it.
  574. if (value_cat == SemIR::ExpressionCategory::Initializing &&
  575. IsValidExpressionCategoryForConversionTarget(
  576. SemIR::ExpressionCategory::Value, target.kind) &&
  577. SemIR::GetInitializingRepresentation(sem_ir, value_type_id).kind ==
  578. SemIR::InitializingRepresentation::ByCopy) {
  579. auto value_rep = SemIR::GetValueRepresentation(sem_ir, value_type_id);
  580. if (value_rep.kind == SemIR::ValueRepresentation::Copy &&
  581. value_rep.type_id == value_type_id) {
  582. // The initializer produces an object representation by copy, and the
  583. // value representation is a copy of the object representation, so we
  584. // already have a value of the right form.
  585. return context.AddInst(
  586. SemIR::ValueOfInitializer{parse_node, value_type_id, value_id});
  587. }
  588. }
  589. }
  590. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  591. // converts to Ui.
  592. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  593. auto value_type_inst =
  594. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  595. if (auto src_tuple_type = value_type_inst.TryAs<SemIR::TupleType>()) {
  596. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  597. value_id, target);
  598. }
  599. }
  600. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  601. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  602. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  603. // to Ui.
  604. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  605. auto value_type_inst =
  606. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  607. if (auto src_struct_type = value_type_inst.TryAs<SemIR::StructType>()) {
  608. return ConvertStructToStruct(context, *src_struct_type,
  609. *target_struct_type, value_id, target);
  610. }
  611. }
  612. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  613. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  614. auto value_type_inst =
  615. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  616. if (auto src_tuple_type = value_type_inst.TryAs<SemIR::TupleType>()) {
  617. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  618. value_id, target);
  619. }
  620. }
  621. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  622. // if it converts to the struct type that is the class's representation type
  623. // (a struct with the same fields as the class, plus a base field where
  624. // relevant).
  625. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  626. auto value_type_inst =
  627. sem_ir.insts().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id));
  628. if (auto src_struct_type = value_type_inst.TryAs<SemIR::StructType>()) {
  629. return ConvertStructToClass(context, *src_struct_type, *target_class_type,
  630. value_id, target);
  631. }
  632. }
  633. if (target.type_id == SemIR::TypeId::TypeType) {
  634. // A tuple of types converts to type `type`.
  635. // TODO: This should apply even for non-literal tuples.
  636. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  637. llvm::SmallVector<SemIR::TypeId> type_ids;
  638. for (auto tuple_inst_id :
  639. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  640. // TODO: This call recurses back into conversion. Switch to an
  641. // iterative approach.
  642. type_ids.push_back(
  643. ExpressionAsType(context, parse_node, tuple_inst_id));
  644. }
  645. auto tuple_type_id =
  646. context.CanonicalizeTupleType(parse_node, std::move(type_ids));
  647. return sem_ir.GetTypeAllowBuiltinTypes(tuple_type_id);
  648. }
  649. // `{}` converts to `{} as type`.
  650. // TODO: This conversion should also be performed for a non-literal value
  651. // of type `{}`.
  652. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  653. struct_literal &&
  654. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  655. value_id = sem_ir.GetTypeAllowBuiltinTypes(value_type_id);
  656. }
  657. }
  658. // No builtin conversion applies.
  659. return value_id;
  660. }
  661. // Given a value expression, form a corresponding initializer that copies from
  662. // that value, if it is possible to do so.
  663. static auto PerformCopy(Context& context, SemIR::InstId expr_id)
  664. -> SemIR::InstId {
  665. auto expr = context.insts().Get(expr_id);
  666. auto type_id = expr.type_id();
  667. if (type_id == SemIR::TypeId::Error) {
  668. return SemIR::InstId::BuiltinError;
  669. }
  670. // TODO: Directly track on the value representation whether it's a copy of
  671. // the object representation.
  672. auto value_rep = SemIR::GetValueRepresentation(context.sem_ir(), type_id);
  673. if (value_rep.kind == SemIR::ValueRepresentation::Copy &&
  674. value_rep.aggregate_kind == SemIR::ValueRepresentation::NotAggregate &&
  675. value_rep.type_id == type_id) {
  676. // For by-value scalar types, no explicit action is required. Initializing
  677. // from a value expression is treated as copying the value.
  678. return expr_id;
  679. }
  680. // TODO: We don't yet have rules for whether and when a class type is
  681. // copyable, or how to perform the copy.
  682. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  683. "Cannot copy value of type `{0}`.", std::string);
  684. context.emitter().Emit(expr.parse_node(), CopyOfUncopyableType,
  685. context.sem_ir().StringifyType(type_id));
  686. return SemIR::InstId::BuiltinError;
  687. }
  688. auto Convert(Context& context, Parse::Node parse_node, SemIR::InstId expr_id,
  689. ConversionTarget target) -> SemIR::InstId {
  690. auto& sem_ir = context.sem_ir();
  691. auto orig_expr_id = expr_id;
  692. // Start by making sure both sides are valid. If any part is invalid, the
  693. // result is invalid and we shouldn't error.
  694. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::TypeId::Error ||
  695. target.type_id == SemIR::TypeId::Error) {
  696. return SemIR::InstId::BuiltinError;
  697. }
  698. if (SemIR::GetExpressionCategory(sem_ir, expr_id) ==
  699. SemIR::ExpressionCategory::NotExpression) {
  700. // TODO: We currently encounter this for use of namespaces and functions.
  701. // We should provide a better diagnostic for inappropriate use of
  702. // namespace names, and allow use of functions as values.
  703. CARBON_DIAGNOSTIC(UseOfNonExpressionAsValue, Error,
  704. "Expression cannot be used as a value.");
  705. context.emitter().Emit(sem_ir.insts().Get(expr_id).parse_node(),
  706. UseOfNonExpressionAsValue);
  707. return SemIR::InstId::BuiltinError;
  708. }
  709. // We can only perform initialization for complete types.
  710. if (!context.TryToCompleteType(target.type_id, [&] {
  711. CARBON_DIAGNOSTIC(IncompleteTypeInInitialization, Error,
  712. "Initialization of incomplete type `{0}`.",
  713. std::string);
  714. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  715. "Forming value of incomplete type `{0}`.",
  716. std::string);
  717. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  718. "Invalid use of incomplete type `{0}`.", std::string);
  719. return context.emitter().Build(
  720. parse_node,
  721. target.is_initializer() ? IncompleteTypeInInitialization
  722. : target.kind == ConversionTarget::Value
  723. ? IncompleteTypeInValueConversion
  724. : IncompleteTypeInConversion,
  725. context.sem_ir().StringifyType(target.type_id, true));
  726. })) {
  727. return SemIR::InstId::BuiltinError;
  728. }
  729. // Check whether any builtin conversion applies.
  730. expr_id = PerformBuiltinConversion(context, parse_node, expr_id, target);
  731. if (expr_id == SemIR::InstId::BuiltinError) {
  732. return expr_id;
  733. }
  734. // If the types don't match at this point, we can't perform the conversion.
  735. // TODO: Look for an `ImplicitAs` impl, or an `As` impl in the case where
  736. // `target.kind == ConversionTarget::ExplicitAs`.
  737. SemIR::Inst expr = sem_ir.insts().Get(expr_id);
  738. if (expr.type_id() != target.type_id) {
  739. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  740. "Cannot implicitly convert from `{0}` to `{1}`.",
  741. std::string, std::string);
  742. CARBON_DIAGNOSTIC(ExplicitAsConversionFailure, Error,
  743. "Cannot convert from `{0}` to `{1}` with `as`.",
  744. std::string, std::string);
  745. context.emitter()
  746. .Build(parse_node,
  747. target.kind == ConversionTarget::ExplicitAs
  748. ? ExplicitAsConversionFailure
  749. : ImplicitAsConversionFailure,
  750. sem_ir.StringifyType(expr.type_id()),
  751. sem_ir.StringifyType(target.type_id))
  752. .Emit();
  753. return SemIR::InstId::BuiltinError;
  754. }
  755. // For `as`, don't perform any value category conversions. In particular, an
  756. // identity conversion shouldn't change the expression category.
  757. if (target.kind == ConversionTarget::ExplicitAs) {
  758. return expr_id;
  759. }
  760. // Now perform any necessary value category conversions.
  761. switch (SemIR::GetExpressionCategory(sem_ir, expr_id)) {
  762. case SemIR::ExpressionCategory::NotExpression:
  763. case SemIR::ExpressionCategory::Mixed:
  764. CARBON_FATAL() << "Unexpected expression " << expr
  765. << " after builtin conversions";
  766. case SemIR::ExpressionCategory::Error:
  767. return SemIR::InstId::BuiltinError;
  768. case SemIR::ExpressionCategory::Initializing:
  769. if (target.is_initializer()) {
  770. if (orig_expr_id == expr_id) {
  771. // Don't fill in the return slot if we created the expression through
  772. // a conversion. In that case, we will have created it with the
  773. // target already set.
  774. // TODO: Find a better way to track whether we need to do this.
  775. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  776. *target.init_block);
  777. }
  778. break;
  779. }
  780. // Commit to using a temporary for this initializing expression.
  781. // TODO: Don't create a temporary if the initializing representation
  782. // is already a value representation.
  783. expr_id = FinalizeTemporary(context, expr_id,
  784. target.kind == ConversionTarget::Discarded);
  785. // We now have an ephemeral reference.
  786. [[fallthrough]];
  787. case SemIR::ExpressionCategory::DurableReference:
  788. case SemIR::ExpressionCategory::EphemeralReference:
  789. // If a reference expression is an acceptable result, we're done.
  790. if (target.kind == ConversionTarget::ValueOrReference ||
  791. target.kind == ConversionTarget::Discarded) {
  792. break;
  793. }
  794. // If we have a reference and don't want one, form a value binding.
  795. // TODO: Support types with custom value representations.
  796. expr_id = context.AddInst(
  797. SemIR::BindValue{expr.parse_node(), expr.type_id(), expr_id});
  798. // We now have a value expression.
  799. [[fallthrough]];
  800. case SemIR::ExpressionCategory::Value:
  801. // When initializing from a value, perform a copy.
  802. if (target.is_initializer()) {
  803. expr_id = PerformCopy(context, expr_id);
  804. }
  805. break;
  806. }
  807. // Perform a final destination store, if necessary.
  808. if (target.kind == ConversionTarget::FullInitializer) {
  809. if (auto init_rep =
  810. SemIR::GetInitializingRepresentation(sem_ir, target.type_id);
  811. init_rep.kind == SemIR::InitializingRepresentation::ByCopy) {
  812. target.init_block->InsertHere();
  813. expr_id = context.AddInst(SemIR::InitializeFrom{
  814. parse_node, target.type_id, expr_id, target.init_id});
  815. }
  816. }
  817. return expr_id;
  818. }
  819. auto Initialize(Context& context, Parse::Node parse_node,
  820. SemIR::InstId target_id, SemIR::InstId value_id)
  821. -> SemIR::InstId {
  822. PendingBlock target_block(context);
  823. return Convert(context, parse_node, value_id,
  824. {.kind = ConversionTarget::Initializer,
  825. .type_id = context.sem_ir().insts().Get(target_id).type_id(),
  826. .init_id = target_id,
  827. .init_block = &target_block});
  828. }
  829. auto ConvertToValueExpression(Context& context, SemIR::InstId expr_id)
  830. -> SemIR::InstId {
  831. auto expr = context.sem_ir().insts().Get(expr_id);
  832. return Convert(context, expr.parse_node(), expr_id,
  833. {.kind = ConversionTarget::Value, .type_id = expr.type_id()});
  834. }
  835. auto ConvertToValueOrReferenceExpression(Context& context,
  836. SemIR::InstId expr_id)
  837. -> SemIR::InstId {
  838. auto expr = context.sem_ir().insts().Get(expr_id);
  839. return Convert(
  840. context, expr.parse_node(), expr_id,
  841. {.kind = ConversionTarget::ValueOrReference, .type_id = expr.type_id()});
  842. }
  843. auto ConvertToValueOfType(Context& context, Parse::Node parse_node,
  844. SemIR::InstId value_id, SemIR::TypeId type_id)
  845. -> SemIR::InstId {
  846. return Convert(context, parse_node, value_id,
  847. {.kind = ConversionTarget::Value, .type_id = type_id});
  848. }
  849. auto ConvertToBoolValue(Context& context, Parse::Node parse_node,
  850. SemIR::InstId value_id) -> SemIR::InstId {
  851. return ConvertToValueOfType(
  852. context, parse_node, value_id,
  853. context.GetBuiltinType(SemIR::BuiltinKind::BoolType));
  854. }
  855. auto ConvertForExplicitAs(Context& context, Parse::Node as_node,
  856. SemIR::InstId value_id, SemIR::TypeId type_id)
  857. -> SemIR::InstId {
  858. return Convert(context, as_node, value_id,
  859. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  860. }
  861. CARBON_DIAGNOSTIC(InCallToFunction, Note, "Calling function declared here.");
  862. // Convert the object argument in a method call to match the `self` parameter.
  863. static auto ConvertSelf(Context& context, Parse::Node call_parse_node,
  864. Parse::Node callee_parse_node,
  865. SemIR::SelfParameter self_param, SemIR::InstId self_id)
  866. -> SemIR::InstId {
  867. if (!self_id.is_valid()) {
  868. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  869. "Missing object argument in method call.");
  870. context.emitter()
  871. .Build(call_parse_node, MissingObjectInMethodCall)
  872. .Note(callee_parse_node, InCallToFunction)
  873. .Emit();
  874. return SemIR::InstId::BuiltinError;
  875. }
  876. DiagnosticAnnotationScope annotate_diagnostics(
  877. &context.emitter(), [&](auto& builder) {
  878. CARBON_DIAGNOSTIC(
  879. InCallToFunctionSelf, Note,
  880. "Initializing `{0}` parameter of method declared here.",
  881. llvm::StringLiteral);
  882. builder.Note(self_param.parse_node, InCallToFunctionSelf,
  883. self_param.is_addr_self.index
  884. ? llvm::StringLiteral("addr self")
  885. : llvm::StringLiteral("self"));
  886. });
  887. // For `addr self`, take the address of the object argument.
  888. auto self_or_addr_id = self_id;
  889. if (self_param.is_addr_self.index) {
  890. self_or_addr_id =
  891. ConvertToValueOrReferenceExpression(context, self_or_addr_id);
  892. auto self = context.insts().Get(self_or_addr_id);
  893. switch (SemIR::GetExpressionCategory(context.sem_ir(), self_id)) {
  894. case SemIR::ExpressionCategory::Error:
  895. case SemIR::ExpressionCategory::DurableReference:
  896. case SemIR::ExpressionCategory::EphemeralReference:
  897. break;
  898. default:
  899. CARBON_DIAGNOSTIC(AddrSelfIsNonReference, Error,
  900. "`addr self` method cannot be invoked on a value.");
  901. context.emitter().Emit(call_parse_node, AddrSelfIsNonReference);
  902. return SemIR::InstId::BuiltinError;
  903. }
  904. self_or_addr_id = context.AddInst(SemIR::AddressOf{
  905. self.parse_node(),
  906. context.GetPointerType(self.parse_node(), self.type_id()),
  907. self_or_addr_id});
  908. }
  909. return ConvertToValueOfType(context, call_parse_node, self_or_addr_id,
  910. self_param.type_id);
  911. }
  912. auto ConvertCallArgs(Context& context, Parse::Node call_parse_node,
  913. SemIR::InstId self_id,
  914. llvm::ArrayRef<SemIR::InstId> arg_refs,
  915. SemIR::InstId return_storage_id,
  916. Parse::Node callee_parse_node,
  917. SemIR::InstBlockId implicit_param_refs_id,
  918. SemIR::InstBlockId param_refs_id) -> SemIR::InstBlockId {
  919. auto implicit_param_refs =
  920. context.sem_ir().inst_blocks().Get(implicit_param_refs_id);
  921. auto param_refs = context.sem_ir().inst_blocks().Get(param_refs_id);
  922. // If sizes mismatch, fail early.
  923. if (arg_refs.size() != param_refs.size()) {
  924. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  925. "{0} argument(s) passed to function expecting "
  926. "{1} argument(s).",
  927. int, int);
  928. context.emitter()
  929. .Build(call_parse_node, CallArgCountMismatch, arg_refs.size(),
  930. param_refs.size())
  931. .Note(callee_parse_node, InCallToFunction)
  932. .Emit();
  933. return SemIR::InstBlockId::Invalid;
  934. }
  935. // Start building a block to hold the converted arguments.
  936. llvm::SmallVector<SemIR::InstId> args;
  937. args.reserve(implicit_param_refs.size() + param_refs.size() +
  938. return_storage_id.is_valid());
  939. // Check implicit parameters.
  940. for (auto implicit_param_id : implicit_param_refs) {
  941. auto param = context.insts().Get(implicit_param_id);
  942. if (auto self_param = param.TryAs<SemIR::SelfParameter>()) {
  943. auto converted_self_id = ConvertSelf(
  944. context, call_parse_node, callee_parse_node, *self_param, self_id);
  945. if (converted_self_id == SemIR::InstId::BuiltinError) {
  946. return SemIR::InstBlockId::Invalid;
  947. }
  948. args.push_back(converted_self_id);
  949. } else {
  950. // TODO: Form argument values for implicit parameters.
  951. context.TODO(call_parse_node, "Call with implicit parameters");
  952. return SemIR::InstBlockId::Invalid;
  953. }
  954. }
  955. int diag_param_index;
  956. DiagnosticAnnotationScope annotate_diagnostics(
  957. &context.emitter(), [&](auto& builder) {
  958. CARBON_DIAGNOSTIC(
  959. InCallToFunctionParam, Note,
  960. "Initializing parameter {0} of function declared here.", int);
  961. builder.Note(callee_parse_node, InCallToFunctionParam,
  962. diag_param_index + 1);
  963. });
  964. // Check type conversions per-element.
  965. for (auto [i, arg_id, param_id] : llvm::enumerate(arg_refs, param_refs)) {
  966. diag_param_index = i;
  967. auto param_type_id = context.sem_ir().insts().Get(param_id).type_id();
  968. // TODO: Convert to the proper expression category. For now, we assume
  969. // parameters are all `let` bindings.
  970. auto converted_arg_id =
  971. ConvertToValueOfType(context, call_parse_node, arg_id, param_type_id);
  972. if (converted_arg_id == SemIR::InstId::BuiltinError) {
  973. return SemIR::InstBlockId::Invalid;
  974. }
  975. args.push_back(converted_arg_id);
  976. }
  977. // Track the return storage, if present.
  978. if (return_storage_id.is_valid()) {
  979. args.push_back(return_storage_id);
  980. }
  981. return context.inst_blocks().Add(args);
  982. }
  983. auto ExpressionAsType(Context& context, Parse::Node parse_node,
  984. SemIR::InstId value_id) -> SemIR::TypeId {
  985. auto type_inst_id = ConvertToValueOfType(context, parse_node, value_id,
  986. SemIR::TypeId::TypeType);
  987. if (type_inst_id == SemIR::InstId::BuiltinError) {
  988. return SemIR::TypeId::Error;
  989. }
  990. auto type_id = context.CanonicalizeType(type_inst_id);
  991. if (type_id == SemIR::TypeId::Error) {
  992. CARBON_DIAGNOSTIC(TypeExpressionEvaluationFailure, Error,
  993. "Cannot evaluate type expression.");
  994. context.emitter().Emit(parse_node, TypeExpressionEvaluationFailure);
  995. }
  996. return type_id;
  997. }
  998. } // namespace Carbon::Check