convert.cpp 51 KB

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