convert.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  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 <optional>
  6. #include <string>
  7. #include <utility>
  8. #include "common/check.h"
  9. #include "common/map.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "toolchain/base/kind_switch.h"
  12. #include "toolchain/check/action.h"
  13. #include "toolchain/check/context.h"
  14. #include "toolchain/check/control_flow.h"
  15. #include "toolchain/check/diagnostic_helpers.h"
  16. #include "toolchain/check/eval.h"
  17. #include "toolchain/check/impl_lookup.h"
  18. #include "toolchain/check/import_ref.h"
  19. #include "toolchain/check/inst.h"
  20. #include "toolchain/check/operator.h"
  21. #include "toolchain/check/pattern_match.h"
  22. #include "toolchain/check/type.h"
  23. #include "toolchain/check/type_completion.h"
  24. #include "toolchain/diagnostics/format_providers.h"
  25. #include "toolchain/sem_ir/copy_on_write_block.h"
  26. #include "toolchain/sem_ir/expr_info.h"
  27. #include "toolchain/sem_ir/file.h"
  28. #include "toolchain/sem_ir/generic.h"
  29. #include "toolchain/sem_ir/ids.h"
  30. #include "toolchain/sem_ir/inst.h"
  31. #include "toolchain/sem_ir/type.h"
  32. #include "toolchain/sem_ir/typed_insts.h"
  33. // TODO: This contains a lot of recursion. Consider removing it in order to
  34. // prevent accidents.
  35. // NOLINTBEGIN(misc-no-recursion)
  36. namespace Carbon::Check {
  37. // Marks the initializer `init_id` as initializing `target_id`.
  38. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  39. SemIR::InstId target_id,
  40. PendingBlock& target_block) -> void {
  41. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  42. if (return_slot_arg_id.has_value()) {
  43. // Replace the temporary in the return slot with a reference to our target.
  44. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  45. SemIR::TemporaryStorage::Kind,
  46. "Return slot for initializer does not contain a temporary; "
  47. "initialized multiple times? Have {0}",
  48. sem_ir.insts().Get(return_slot_arg_id));
  49. target_block.MergeReplacing(return_slot_arg_id, target_id);
  50. }
  51. }
  52. // For a value or initializing expression using a copy value representation,
  53. // copy the value into a temporary object.
  54. static auto CopyValueToTemporary(Context& context, SemIR::InstId init_id)
  55. -> SemIR::InstId {
  56. // TODO: Consider using `None` to mean that we immediately materialize and
  57. // initialize a temporary, rather than two separate instructions.
  58. auto init = context.sem_ir().insts().Get(init_id);
  59. auto temporary_id = AddInst<SemIR::TemporaryStorage>(
  60. context, SemIR::LocId(init_id), {.type_id = init.type_id()});
  61. return AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(init_id),
  62. {.type_id = init.type_id(),
  63. .storage_id = temporary_id,
  64. .init_id = init_id});
  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::None`.
  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_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  75. if (return_slot_arg_id.has_value()) {
  76. // The return slot should already have a materialized temporary in it.
  77. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  78. SemIR::TemporaryStorage::Kind,
  79. "Return slot for initializer does not contain a temporary; "
  80. "initialized multiple times? Have {0}",
  81. sem_ir.insts().Get(return_slot_arg_id));
  82. auto init = sem_ir.insts().Get(init_id);
  83. return AddInstWithCleanup<SemIR::Temporary>(
  84. context, SemIR::LocId(init_id),
  85. {.type_id = init.type_id(),
  86. .storage_id = return_slot_arg_id,
  87. .init_id = init_id});
  88. }
  89. if (discarded) {
  90. // Don't invent a temporary that we're going to discard.
  91. return SemIR::InstId::None;
  92. }
  93. // The initializer has no return slot, but we want to produce a temporary
  94. // object. Materialize one now.
  95. return CopyValueToTemporary(context, 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. // Helper to allow `MakeElementAccessInst` to call `AddInst` with either a
  108. // `PendingBlock` or `Context` (defined in `inst.h`).
  109. template <typename AccessInstT>
  110. static auto AddInst(PendingBlock& block, SemIR::LocId loc_id, AccessInstT inst)
  111. -> SemIR::InstId {
  112. return block.AddInst<AccessInstT>(loc_id, inst);
  113. }
  114. // Creates and adds an instruction to perform element access into an aggregate.
  115. template <typename AccessInstT, typename InstBlockT>
  116. static auto MakeElementAccessInst(Context& context, SemIR::LocId loc_id,
  117. SemIR::InstId aggregate_id,
  118. SemIR::TypeId elem_type_id, InstBlockT& block,
  119. size_t i) -> SemIR::InstId {
  120. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  121. // TODO: Add a new instruction kind for indexing an array at a constant
  122. // index so that we don't need an integer literal instruction here, and
  123. // remove this special case.
  124. auto index_id = block.template AddInst<SemIR::IntValue>(
  125. loc_id, {.type_id = GetSingletonType(context,
  126. SemIR::IntLiteralType::TypeInstId),
  127. .int_id = context.ints().Add(static_cast<int64_t>(i))});
  128. return AddInst<AccessInstT>(block, loc_id,
  129. {elem_type_id, aggregate_id, index_id});
  130. } else {
  131. return AddInst<AccessInstT>(
  132. block, loc_id, {elem_type_id, aggregate_id, SemIR::ElementIndex(i)});
  133. }
  134. }
  135. // Converts an element of one aggregate so that it can be used as an element of
  136. // another aggregate.
  137. //
  138. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  139. // element type, `src_field_index` is the index, and `SourceAccessInstT` is the
  140. // kind of instruction used to access the source element.
  141. //
  142. // For the target: `kind` is the kind of conversion or initialization,
  143. // `target_elem_type` is the element type. For initialization, `target_id` is
  144. // the destination, `target_block` is a pending block for target location
  145. // calculations that will be spliced as the return slot of the initializer if
  146. // necessary, `target_field_index` is the index, and `TargetAccessInstT` is the
  147. // kind of instruction used to access the destination element.
  148. template <typename SourceAccessInstT, typename TargetAccessInstT>
  149. static auto ConvertAggregateElement(
  150. Context& context, SemIR::LocId loc_id, SemIR::InstId src_id,
  151. SemIR::TypeInstId src_elem_type_inst,
  152. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  153. ConversionTarget::Kind kind, SemIR::InstId target_id,
  154. SemIR::TypeInstId target_elem_type_inst, PendingBlock* target_block,
  155. size_t src_field_index, size_t target_field_index,
  156. SemIR::ClassType* vtable_class_type = nullptr) -> SemIR::InstId {
  157. auto src_elem_type =
  158. context.types().GetTypeIdForTypeInstId(src_elem_type_inst);
  159. auto target_elem_type =
  160. context.types().GetTypeIdForTypeInstId(target_elem_type_inst);
  161. // Compute the location of the source element. This goes into the current code
  162. // block, not into the target block.
  163. // TODO: Ideally we would discard this instruction if it's unused.
  164. auto src_elem_id = !src_literal_elems.empty()
  165. ? src_literal_elems[src_field_index]
  166. : MakeElementAccessInst<SourceAccessInstT>(
  167. context, loc_id, src_id, src_elem_type, context,
  168. src_field_index);
  169. // If we're performing a conversion rather than an initialization, we won't
  170. // have or need a target.
  171. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  172. if (!target.is_initializer()) {
  173. return Convert(context, loc_id, src_elem_id, target);
  174. }
  175. // Compute the location of the target element and initialize it.
  176. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  177. target.init_block = target_block;
  178. target.init_id = MakeElementAccessInst<TargetAccessInstT>(
  179. context, loc_id, target_id, target_elem_type, *target_block,
  180. target_field_index);
  181. return Convert(context, loc_id, src_elem_id, target, vtable_class_type);
  182. }
  183. // Performs a conversion from a tuple to an array type. This function only
  184. // converts the type, and does not perform a final conversion to the requested
  185. // expression category.
  186. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  187. SemIR::ArrayType array_type,
  188. SemIR::InstId value_id, ConversionTarget target)
  189. -> SemIR::InstId {
  190. auto& sem_ir = context.sem_ir();
  191. auto tuple_elem_types = sem_ir.inst_blocks().Get(tuple_type.type_elements_id);
  192. auto value = sem_ir.insts().Get(value_id);
  193. SemIR::LocId value_loc_id(value_id);
  194. // If we're initializing from a tuple literal, we will use its elements
  195. // directly. Otherwise, materialize a temporary if needed and index into the
  196. // result.
  197. llvm::ArrayRef<SemIR::InstId> literal_elems;
  198. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  199. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  200. } else {
  201. value_id = MaterializeIfInitializing(context, value_id);
  202. }
  203. // Check that the tuple is the right size.
  204. std::optional<uint64_t> array_bound =
  205. sem_ir.GetArrayBoundValue(array_type.bound_id);
  206. if (!array_bound) {
  207. // TODO: Should this fall back to using `ImplicitAs`?
  208. if (target.diagnose) {
  209. CARBON_DIAGNOSTIC(ArrayInitDependentBound, Error,
  210. "cannot initialize array with dependent bound from a "
  211. "list of initializers");
  212. context.emitter().Emit(value_loc_id, ArrayInitDependentBound);
  213. }
  214. return SemIR::ErrorInst::InstId;
  215. }
  216. if (tuple_elem_types.size() != array_bound) {
  217. if (target.diagnose) {
  218. CARBON_DIAGNOSTIC(ArrayInitFromLiteralArgCountMismatch, Error,
  219. "cannot initialize array of {0} element{0:s} from {1} "
  220. "initializer{1:s}",
  221. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  222. CARBON_DIAGNOSTIC(
  223. ArrayInitFromExprArgCountMismatch, Error,
  224. "cannot initialize array of {0} element{0:s} from tuple "
  225. "with {1} element{1:s}",
  226. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  227. context.emitter().Emit(value_loc_id,
  228. literal_elems.empty()
  229. ? ArrayInitFromExprArgCountMismatch
  230. : ArrayInitFromLiteralArgCountMismatch,
  231. *array_bound, tuple_elem_types.size());
  232. }
  233. return SemIR::ErrorInst::InstId;
  234. }
  235. PendingBlock target_block_storage(&context);
  236. PendingBlock* target_block =
  237. target.init_block ? target.init_block : &target_block_storage;
  238. // Arrays are always initialized in-place. Allocate a temporary as the
  239. // destination for the array initialization if we weren't given one.
  240. SemIR::InstId return_slot_arg_id = target.init_id;
  241. if (!target.init_id.has_value()) {
  242. return_slot_arg_id = target_block->AddInst<SemIR::TemporaryStorage>(
  243. value_loc_id, {.type_id = target.type_id});
  244. }
  245. // Initialize each element of the array from the corresponding element of the
  246. // tuple.
  247. // TODO: Annotate diagnostics coming from here with the array element index,
  248. // if initializing from a tuple literal.
  249. llvm::SmallVector<SemIR::InstId> inits;
  250. inits.reserve(*array_bound + 1);
  251. for (auto [i, src_type_inst_id] : llvm::enumerate(
  252. context.types().GetBlockAsTypeInstIds(tuple_elem_types))) {
  253. // TODO: This call recurses back into conversion. Switch to an iterative
  254. // approach.
  255. auto init_id =
  256. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  257. context, value_loc_id, value_id, src_type_inst_id, literal_elems,
  258. ConversionTarget::FullInitializer, return_slot_arg_id,
  259. array_type.element_type_inst_id, target_block, i, i);
  260. if (init_id == SemIR::ErrorInst::InstId) {
  261. return SemIR::ErrorInst::InstId;
  262. }
  263. inits.push_back(init_id);
  264. }
  265. // Flush the temporary here if we didn't insert it earlier, so we can add a
  266. // reference to the return slot.
  267. target_block->InsertHere();
  268. return AddInst<SemIR::ArrayInit>(context, value_loc_id,
  269. {.type_id = target.type_id,
  270. .inits_id = sem_ir.inst_blocks().Add(inits),
  271. .dest_id = return_slot_arg_id});
  272. }
  273. // Performs a conversion from a tuple to a tuple type. This function only
  274. // converts the type, and does not perform a final conversion to the requested
  275. // expression category.
  276. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  277. SemIR::TupleType dest_type,
  278. SemIR::InstId value_id, ConversionTarget target)
  279. -> SemIR::InstId {
  280. auto& sem_ir = context.sem_ir();
  281. auto src_elem_types = sem_ir.inst_blocks().Get(src_type.type_elements_id);
  282. auto dest_elem_types = sem_ir.inst_blocks().Get(dest_type.type_elements_id);
  283. auto value = sem_ir.insts().Get(value_id);
  284. SemIR::LocId value_loc_id(value_id);
  285. // If we're initializing from a tuple literal, we will use its elements
  286. // directly. Otherwise, materialize a temporary if needed and index into the
  287. // result.
  288. llvm::ArrayRef<SemIR::InstId> literal_elems;
  289. auto literal_elems_id = SemIR::InstBlockId::None;
  290. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  291. literal_elems_id = tuple_literal->elements_id;
  292. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  293. } else {
  294. value_id = MaterializeIfInitializing(context, value_id);
  295. }
  296. // Check that the tuples are the same size.
  297. if (src_elem_types.size() != dest_elem_types.size()) {
  298. if (target.diagnose) {
  299. CARBON_DIAGNOSTIC(
  300. TupleInitElementCountMismatch, Error,
  301. "cannot initialize tuple of {0} element{0:s} from tuple "
  302. "with {1} element{1:s}",
  303. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  304. context.emitter().Emit(value_loc_id, TupleInitElementCountMismatch,
  305. dest_elem_types.size(), src_elem_types.size());
  306. }
  307. return SemIR::ErrorInst::InstId;
  308. }
  309. // If we're forming an initializer, then we want an initializer for each
  310. // element. Otherwise, we want a value representation for each element.
  311. // Perform a final destination store if we're performing an in-place
  312. // initialization.
  313. bool is_init = target.is_initializer();
  314. ConversionTarget::Kind inner_kind =
  315. !is_init ? ConversionTarget::Value
  316. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  317. SemIR::InitRepr::InPlace
  318. ? ConversionTarget::FullInitializer
  319. : ConversionTarget::Initializer;
  320. // Initialize each element of the destination from the corresponding element
  321. // of the source.
  322. // TODO: Annotate diagnostics coming from here with the element index.
  323. auto new_block =
  324. literal_elems_id.has_value()
  325. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  326. : SemIR::CopyOnWriteInstBlock(
  327. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  328. src_elem_types.size()});
  329. for (auto [i, src_type_inst_id, dest_type_inst_id] : llvm::enumerate(
  330. context.types().GetBlockAsTypeInstIds(src_elem_types),
  331. context.types().GetBlockAsTypeInstIds(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_loc_id, value_id, src_type_inst_id, literal_elems,
  337. inner_kind, target.init_id, dest_type_inst_id, target.init_block, i,
  338. i);
  339. if (init_id == SemIR::ErrorInst::InstId) {
  340. return SemIR::ErrorInst::InstId;
  341. }
  342. new_block.Set(i, init_id);
  343. }
  344. if (is_init) {
  345. target.init_block->InsertHere();
  346. return AddInst<SemIR::TupleInit>(context, value_loc_id,
  347. {.type_id = target.type_id,
  348. .elements_id = new_block.id(),
  349. .dest_id = target.init_id});
  350. } else {
  351. return AddInst<SemIR::TupleValue>(
  352. context, value_loc_id,
  353. {.type_id = target.type_id, .elements_id = new_block.id()});
  354. }
  355. }
  356. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  357. template <typename TargetAccessInstT>
  358. static auto ConvertStructToStructOrClass(
  359. Context& context, SemIR::StructType src_type, SemIR::StructType dest_type,
  360. SemIR::InstId value_id, ConversionTarget target,
  361. SemIR::ClassType* vtable_class_type = nullptr) -> SemIR::InstId {
  362. static_assert(std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT> ||
  363. std::is_same_v<SemIR::StructAccess, TargetAccessInstT>);
  364. constexpr bool ToClass =
  365. std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT>;
  366. auto& sem_ir = context.sem_ir();
  367. auto src_elem_fields = sem_ir.struct_type_fields().Get(src_type.fields_id);
  368. auto dest_elem_fields = sem_ir.struct_type_fields().Get(dest_type.fields_id);
  369. bool dest_has_vptr = !dest_elem_fields.empty() &&
  370. dest_elem_fields.front().name_id == SemIR::NameId::Vptr;
  371. int dest_vptr_offset = (dest_has_vptr ? 1 : 0);
  372. auto dest_elem_fields_size = dest_elem_fields.size() - dest_vptr_offset;
  373. auto value = sem_ir.insts().Get(value_id);
  374. SemIR::LocId value_loc_id(value_id);
  375. // If we're initializing from a struct literal, we will use its elements
  376. // directly. Otherwise, materialize a temporary if needed and index into the
  377. // result.
  378. llvm::ArrayRef<SemIR::InstId> literal_elems;
  379. auto literal_elems_id = SemIR::InstBlockId::None;
  380. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  381. literal_elems_id = struct_literal->elements_id;
  382. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  383. } else {
  384. value_id = MaterializeIfInitializing(context, value_id);
  385. }
  386. // Check that the structs are the same size.
  387. // TODO: If not, include the name of the first source field that doesn't
  388. // exist in the destination or vice versa in the diagnostic.
  389. if (src_elem_fields.size() != dest_elem_fields_size) {
  390. if (target.diagnose) {
  391. CARBON_DIAGNOSTIC(
  392. StructInitElementCountMismatch, Error,
  393. "cannot initialize {0:class|struct} with {1} field{1:s} from struct "
  394. "with {2} field{2:s}",
  395. Diagnostics::BoolAsSelect, Diagnostics::IntAsSelect,
  396. Diagnostics::IntAsSelect);
  397. context.emitter().Emit(value_loc_id, StructInitElementCountMismatch,
  398. ToClass, dest_elem_fields_size,
  399. src_elem_fields.size());
  400. }
  401. return SemIR::ErrorInst::InstId;
  402. }
  403. // Prepare to look up fields in the source by index.
  404. Map<SemIR::NameId, int32_t> src_field_indexes;
  405. if (src_type.fields_id != dest_type.fields_id) {
  406. for (auto [i, field] : llvm::enumerate(src_elem_fields)) {
  407. auto result = src_field_indexes.Insert(field.name_id, i);
  408. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  409. }
  410. }
  411. // If we're forming an initializer, then we want an initializer for each
  412. // element. Otherwise, we want a value representation for each element.
  413. // Perform a final destination store if we're performing an in-place
  414. // initialization.
  415. bool is_init = target.is_initializer();
  416. ConversionTarget::Kind inner_kind =
  417. !is_init ? ConversionTarget::Value
  418. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  419. SemIR::InitRepr::InPlace
  420. ? ConversionTarget::FullInitializer
  421. : ConversionTarget::Initializer;
  422. // Initialize each element of the destination from the corresponding element
  423. // of the source.
  424. // TODO: Annotate diagnostics coming from here with the element index.
  425. auto new_block =
  426. literal_elems_id.has_value() && !dest_has_vptr
  427. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  428. : SemIR::CopyOnWriteInstBlock(
  429. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  430. dest_elem_fields.size()});
  431. for (auto [i, dest_field] : llvm::enumerate(dest_elem_fields)) {
  432. if (dest_field.name_id == SemIR::NameId::Vptr) {
  433. if constexpr (!ToClass) {
  434. CARBON_FATAL("Only classes should have vptrs.");
  435. }
  436. target.init_block->InsertHere();
  437. auto vptr_type_id =
  438. context.types().GetTypeIdForTypeInstId(dest_field.type_inst_id);
  439. auto dest_id =
  440. AddInst<SemIR::ClassElementAccess>(context, value_loc_id,
  441. {.type_id = vptr_type_id,
  442. .base_id = target.init_id,
  443. .index = SemIR::ElementIndex(i)});
  444. auto vtable_decl_id =
  445. context.classes().Get(vtable_class_type->class_id).vtable_decl_id;
  446. LoadImportRef(context, vtable_decl_id);
  447. auto canonical_vtable_decl_id =
  448. context.constant_values().GetConstantInstId(vtable_decl_id);
  449. auto vtable_ptr_id = AddInst<SemIR::VtablePtr>(
  450. context, value_loc_id,
  451. {.type_id = GetPointerType(context, SemIR::VtableType::TypeInstId),
  452. .vtable_id = context.insts()
  453. .GetAs<SemIR::VtableDecl>(canonical_vtable_decl_id)
  454. .vtable_id,
  455. .specific_id = vtable_class_type->specific_id});
  456. auto init_id = AddInst<SemIR::InitializeFrom>(context, value_loc_id,
  457. {.type_id = vptr_type_id,
  458. .src_id = vtable_ptr_id,
  459. .dest_id = dest_id});
  460. new_block.Set(i, init_id);
  461. continue;
  462. }
  463. // Find the matching source field.
  464. auto src_field_index = i;
  465. if (src_type.fields_id != dest_type.fields_id) {
  466. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  467. src_field_index = lookup.value();
  468. } else {
  469. if (target.diagnose) {
  470. if (literal_elems_id.has_value()) {
  471. CARBON_DIAGNOSTIC(
  472. StructInitMissingFieldInLiteral, Error,
  473. "missing value for field `{0}` in struct initialization",
  474. SemIR::NameId);
  475. context.emitter().Emit(value_loc_id,
  476. StructInitMissingFieldInLiteral,
  477. dest_field.name_id);
  478. } else {
  479. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  480. "cannot convert from struct type {0} to {1}: "
  481. "missing field `{2}` in source type",
  482. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  483. context.emitter().Emit(value_loc_id,
  484. StructInitMissingFieldInConversion, value_id,
  485. target.type_id, dest_field.name_id);
  486. }
  487. }
  488. return SemIR::ErrorInst::InstId;
  489. }
  490. }
  491. auto src_field = src_elem_fields[src_field_index];
  492. // TODO: This call recurses back into conversion. Switch to an iterative
  493. // approach.
  494. auto init_id =
  495. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  496. context, value_loc_id, value_id, src_field.type_inst_id,
  497. literal_elems, inner_kind, target.init_id, dest_field.type_inst_id,
  498. target.init_block, src_field_index,
  499. src_field_index + dest_vptr_offset, vtable_class_type);
  500. if (init_id == SemIR::ErrorInst::InstId) {
  501. return SemIR::ErrorInst::InstId;
  502. }
  503. new_block.Set(i, init_id);
  504. }
  505. if (ToClass) {
  506. target.init_block->InsertHere();
  507. CARBON_CHECK(is_init,
  508. "Converting directly to a class value is not supported");
  509. return AddInst<SemIR::ClassInit>(context, value_loc_id,
  510. {.type_id = target.type_id,
  511. .elements_id = new_block.id(),
  512. .dest_id = target.init_id});
  513. } else if (is_init) {
  514. target.init_block->InsertHere();
  515. return AddInst<SemIR::StructInit>(context, value_loc_id,
  516. {.type_id = target.type_id,
  517. .elements_id = new_block.id(),
  518. .dest_id = target.init_id});
  519. } else {
  520. return AddInst<SemIR::StructValue>(
  521. context, value_loc_id,
  522. {.type_id = target.type_id, .elements_id = new_block.id()});
  523. }
  524. }
  525. // Performs a conversion from a struct to a struct type. This function only
  526. // converts the type, and does not perform a final conversion to the requested
  527. // expression category.
  528. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  529. SemIR::StructType dest_type,
  530. SemIR::InstId value_id,
  531. ConversionTarget target) -> SemIR::InstId {
  532. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  533. context, src_type, dest_type, value_id, target);
  534. }
  535. // Performs a conversion from a struct to a class type. This function only
  536. // converts the type, and does not perform a final conversion to the requested
  537. // expression category.
  538. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  539. SemIR::ClassType dest_type,
  540. SemIR::InstId value_id,
  541. ConversionTarget target,
  542. SemIR::ClassType* vtable_class_type)
  543. -> SemIR::InstId {
  544. PendingBlock target_block(&context);
  545. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  546. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  547. auto object_repr_id =
  548. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  549. if (object_repr_id == SemIR::ErrorInst::TypeId) {
  550. return SemIR::ErrorInst::InstId;
  551. }
  552. if (context.types().Is<SemIR::CustomLayoutType>(object_repr_id)) {
  553. // Builtin conversion does not apply.
  554. return value_id;
  555. }
  556. auto dest_struct_type =
  557. context.types().GetAs<SemIR::StructType>(object_repr_id);
  558. // If we're trying to create a class value, form a temporary for the value to
  559. // point to.
  560. bool need_temporary = !target.is_initializer();
  561. if (need_temporary) {
  562. target.kind = ConversionTarget::Initializer;
  563. target.init_block = &target_block;
  564. target.init_id = target_block.AddInst<SemIR::TemporaryStorage>(
  565. SemIR::LocId(value_id), {.type_id = target.type_id});
  566. }
  567. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  568. context, src_type, dest_struct_type, value_id, target,
  569. vtable_class_type ? vtable_class_type : &dest_type);
  570. if (need_temporary) {
  571. target_block.InsertHere();
  572. result_id =
  573. AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(value_id),
  574. {.type_id = target.type_id,
  575. .storage_id = target.init_id,
  576. .init_id = result_id});
  577. }
  578. return result_id;
  579. }
  580. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  581. // in order from derived to base.
  582. using InheritancePath =
  583. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  584. // Computes the inheritance path from class `derived_id` to class `base_id`.
  585. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  586. static auto ComputeInheritancePath(Context& context, SemIR::LocId loc_id,
  587. SemIR::TypeId derived_id,
  588. SemIR::TypeId base_id)
  589. -> std::optional<InheritancePath> {
  590. // We intend for NRVO to be applied to `result`. All `return` statements in
  591. // this function should `return result;`.
  592. std::optional<InheritancePath> result(std::in_place);
  593. if (!TryToCompleteType(context, derived_id, loc_id)) {
  594. // TODO: Should we give an error here? If we don't, and there is an
  595. // inheritance path when the class is defined, we may have a coherence
  596. // problem.
  597. result = std::nullopt;
  598. return result;
  599. }
  600. while (derived_id != base_id) {
  601. auto derived_class_type =
  602. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  603. if (!derived_class_type) {
  604. result = std::nullopt;
  605. break;
  606. }
  607. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  608. auto base_type_id = derived_class.GetBaseType(
  609. context.sem_ir(), derived_class_type->specific_id);
  610. if (!base_type_id.has_value()) {
  611. result = std::nullopt;
  612. break;
  613. }
  614. result->push_back({derived_class.base_id, base_type_id});
  615. derived_id = base_type_id;
  616. }
  617. return result;
  618. }
  619. // Performs a conversion from a derived class value or reference to a base class
  620. // value or reference.
  621. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  622. SemIR::InstId value_id,
  623. const InheritancePath& path) -> SemIR::InstId {
  624. // Materialize a temporary if necessary.
  625. value_id = ConvertToValueOrRefExpr(context, value_id);
  626. // Preserve type qualifiers.
  627. auto quals = context.types()
  628. .GetUnqualifiedTypeAndQualifiers(
  629. context.insts().Get(value_id).type_id())
  630. .second;
  631. // Add a series of `.base` accesses.
  632. for (auto [base_id, base_type_id] : path) {
  633. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  634. value_id = AddInst<SemIR::ClassElementAccess>(
  635. context, loc_id,
  636. {.type_id = GetQualifiedType(context, base_type_id, quals),
  637. .base_id = value_id,
  638. .index = base_decl.index});
  639. }
  640. return value_id;
  641. }
  642. // Performs a conversion from a derived class pointer to a base class pointer.
  643. static auto ConvertDerivedPointerToBasePointer(
  644. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  645. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  646. const InheritancePath& path) -> SemIR::InstId {
  647. auto pointee_type_id =
  648. context.types().GetTypeIdForTypeInstId(src_ptr_type.pointee_id);
  649. // Form `*p`.
  650. ptr_id = ConvertToValueExpr(context, ptr_id);
  651. auto ref_id = AddInst<SemIR::Deref>(
  652. context, loc_id, {.type_id = pointee_type_id, .pointer_id = ptr_id});
  653. // Convert as a reference expression.
  654. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  655. // Take the address.
  656. return AddInst<SemIR::AddrOf>(
  657. context, loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  658. }
  659. // Returns whether `category` is a valid expression category to produce as a
  660. // result of a conversion with kind `target_kind`, or at most needs a temporary
  661. // to be materialized.
  662. static auto IsValidExprCategoryForConversionTarget(
  663. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  664. switch (target_kind) {
  665. case ConversionTarget::Value:
  666. return category == SemIR::ExprCategory::Value;
  667. case ConversionTarget::ValueOrRef:
  668. case ConversionTarget::Discarded:
  669. return category == SemIR::ExprCategory::Value ||
  670. category == SemIR::ExprCategory::DurableRef ||
  671. category == SemIR::ExprCategory::EphemeralRef ||
  672. category == SemIR::ExprCategory::Initializing;
  673. case ConversionTarget::DurableRef:
  674. return category == SemIR::ExprCategory::DurableRef;
  675. case ConversionTarget::CppThunkRef:
  676. return category == SemIR::ExprCategory::EphemeralRef;
  677. case ConversionTarget::ExplicitAs:
  678. case ConversionTarget::ExplicitUnsafeAs:
  679. return true;
  680. case ConversionTarget::Initializer:
  681. case ConversionTarget::FullInitializer:
  682. return category == SemIR::ExprCategory::Initializing;
  683. }
  684. }
  685. // Determines whether the initialization representation of the type is a copy of
  686. // the value representation.
  687. static auto InitReprIsCopyOfValueRepr(const SemIR::File& sem_ir,
  688. SemIR::TypeId type_id) -> bool {
  689. // The initializing representation is a copy of the value representation if
  690. // they're both copies of the object representation.
  691. return SemIR::InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  692. SemIR::ValueRepr::ForType(sem_ir, type_id)
  693. .IsCopyOfObjectRepr(sem_ir, type_id);
  694. }
  695. // Determines whether we can pull a value directly out of an initializing
  696. // expression of type `type_id` to initialize a target of type `type_id` and
  697. // kind `target_kind`.
  698. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  699. SemIR::TypeId type_id,
  700. ConversionTarget::Kind target_kind)
  701. -> bool {
  702. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  703. target_kind)) {
  704. // We don't want a value expression.
  705. return false;
  706. }
  707. // We can pull a value out of an initializing expression if it holds one.
  708. return InitReprIsCopyOfValueRepr(sem_ir, type_id);
  709. }
  710. // Determine whether the given set of qualifiers can be added by a conversion
  711. // of an expression of the given category.
  712. static auto CanAddQualifiers(SemIR::TypeQualifiers quals,
  713. SemIR::ExprCategory cat) -> bool {
  714. if (HasTypeQualifier(quals, SemIR::TypeQualifiers::MaybeUnformed) &&
  715. !SemIR::IsRefCategory(cat)) {
  716. // `MaybeUnformed(T)` may have a different value representation or
  717. // initializing representation from `T`, so only allow it to be added for a
  718. // reference expression.
  719. // TODO: We should allow converting an initializing expression of type `T`
  720. // to `MaybeUnformed(T)`. `PerformBuiltinConversion` will need to generate
  721. // an `InPlaceInit` instruction when needed.
  722. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  723. return false;
  724. }
  725. // `const` and `partial` can always be added.
  726. return true;
  727. }
  728. // Determine whether the given set of qualifiers can be removed by a conversion
  729. // of an expression of the given category.
  730. static auto CanRemoveQualifiers(SemIR::TypeQualifiers quals,
  731. SemIR::ExprCategory cat, bool allow_unsafe)
  732. -> bool {
  733. if (HasTypeQualifier(quals, SemIR::TypeQualifiers::Const) && !allow_unsafe &&
  734. SemIR::IsRefCategory(cat)) {
  735. // Removing `const` is an unsafe conversion for a reference expression.
  736. return false;
  737. }
  738. if (HasTypeQualifier(quals, SemIR::TypeQualifiers::Partial) &&
  739. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  740. // TODO: Allow removing `partial` for initializing expressions as a safe
  741. // conversion. `PerformBuiltinConversion` will need to initialize the vptr
  742. // as part of the conversion.
  743. return false;
  744. }
  745. if (HasTypeQualifier(quals, SemIR::TypeQualifiers::MaybeUnformed) &&
  746. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  747. // As an unsafe conversion, `MaybeUnformed` can be removed from a value or
  748. // reference expression.
  749. return false;
  750. }
  751. return true;
  752. }
  753. static auto DiagnoseConversionFailureToConstraintValue(
  754. Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  755. SemIR::TypeId target_type_id) -> void {
  756. CARBON_DCHECK(target_type_id == SemIR::TypeType::TypeId ||
  757. context.types().Is<SemIR::FacetType>(target_type_id));
  758. auto type_of_expr_id = context.insts().Get(expr_id).type_id();
  759. CARBON_CHECK(context.types().IsFacetType(type_of_expr_id));
  760. // If the source type is/has a facet value, then we can include its
  761. // FacetType in the diagnostic to help explain what interfaces the
  762. // source type implements.
  763. auto facet_value_inst_id = SemIR::InstId::None;
  764. if (auto facet_access_type =
  765. context.insts().TryGetAs<SemIR::FacetAccessType>(expr_id)) {
  766. facet_value_inst_id = facet_access_type->facet_value_inst_id;
  767. } else if (context.types().Is<SemIR::FacetType>(type_of_expr_id)) {
  768. facet_value_inst_id = expr_id;
  769. }
  770. if (facet_value_inst_id.has_value()) {
  771. CARBON_DIAGNOSTIC(ConversionFailureFacetToFacet, Error,
  772. "cannot convert type {0} that implements {1} into type "
  773. "implementing {2}",
  774. InstIdAsType, TypeOfInstId, SemIR::TypeId);
  775. context.emitter().Emit(loc_id, ConversionFailureFacetToFacet, expr_id,
  776. facet_value_inst_id, target_type_id);
  777. } else {
  778. CARBON_DIAGNOSTIC(ConversionFailureTypeToFacet, Error,
  779. "cannot convert type {0} into type implementing {1}",
  780. InstIdAsType, SemIR::TypeId);
  781. context.emitter().Emit(loc_id, ConversionFailureTypeToFacet, expr_id,
  782. target_type_id);
  783. }
  784. }
  785. static auto PerformBuiltinConversion(
  786. Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  787. ConversionTarget target, SemIR::ClassType* vtable_class_type = nullptr)
  788. -> SemIR::InstId {
  789. auto& sem_ir = context.sem_ir();
  790. auto value = sem_ir.insts().Get(value_id);
  791. auto value_type_id = value.type_id();
  792. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  793. // Various forms of implicit conversion are supported as builtin conversions,
  794. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  795. // prelude. There are a few reasons we need to perform some of these
  796. // conversions as builtins:
  797. //
  798. // 1) Conversions from struct and tuple *literals* have special rules that
  799. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  800. // recurse into the elements of the literal before performing
  801. // initialization in order to avoid unnecessary conversions between
  802. // expression categories that would be performed by `ImplicitAs.Convert`.
  803. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  804. // the value of the facet, not only its type, and therefore cannot be
  805. // modeled by `ImplicitAs`.
  806. // 3) Some of these conversions are used while checking the library
  807. // definition of `ImplicitAs` itself or implementations of it.
  808. //
  809. // We also expect to see better performance by avoiding an `impl` lookup for
  810. // common conversions.
  811. //
  812. // TODO: We should provide a debugging flag to turn off as many of these
  813. // builtin conversions as we can so that we can test that they do the same
  814. // thing as the library implementations.
  815. //
  816. // The builtin conversions that correspond to `impl`s in the library all
  817. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  818. // being specialized in any of these cases.
  819. // If the value is already of the right kind and expression category, there's
  820. // nothing to do. Performing a conversion would decompose and rebuild tuples
  821. // and structs, so it's important that we bail out early in this case.
  822. if (value_type_id == target.type_id) {
  823. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  824. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  825. return value_id;
  826. }
  827. // If the source is an initializing expression, we may be able to pull a
  828. // value right out of it.
  829. if (value_cat == SemIR::ExprCategory::Initializing &&
  830. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  831. return AddInst<SemIR::ValueOfInitializer>(
  832. context, loc_id, {.type_id = value_type_id, .init_id = value_id});
  833. }
  834. // PerformBuiltinConversion converts each part of a tuple or struct, even
  835. // when the types are the same. This is not done for classes since they have
  836. // to define their conversions as part of their api.
  837. //
  838. // If a class adapts a tuple or struct, we convert each of its parts when
  839. // there's no other conversion going on (the source and target types are the
  840. // same). To do so, we have to insert a conversion of the value up to the
  841. // foundation and back down, and a conversion of the initializing object if
  842. // there is one.
  843. //
  844. // Implementation note: We do the conversion through a call to
  845. // PerformBuiltinConversion() call rather than a Convert() call to avoid
  846. // extraneous `converted` semir instructions on the adapted types, and as a
  847. // shortcut to doing the explicit calls to walk the parts of the
  848. // tuple/struct which happens inside PerformBuiltinConversion().
  849. if (auto foundation_type_id =
  850. context.types().GetTransitiveAdaptedType(value_type_id);
  851. foundation_type_id != value_type_id &&
  852. (context.types().Is<SemIR::TupleType>(foundation_type_id) ||
  853. context.types().Is<SemIR::StructType>(foundation_type_id))) {
  854. auto foundation_value_id = AddInst<SemIR::AsCompatible>(
  855. context, loc_id,
  856. {.type_id = foundation_type_id, .source_id = value_id});
  857. auto foundation_init_id = target.init_id;
  858. if (foundation_init_id != SemIR::InstId::None) {
  859. foundation_init_id = target.init_block->AddInst<SemIR::AsCompatible>(
  860. loc_id,
  861. {.type_id = foundation_type_id, .source_id = target.init_id});
  862. }
  863. {
  864. // While the types are the same, the conversion can still fail if it
  865. // performs a copy while converting the value to another category, and
  866. // the type (or some part of it) is not copyable.
  867. Diagnostics::AnnotationScope annotate_diagnostics(
  868. &context.emitter(), [&](auto& builder) {
  869. CARBON_DIAGNOSTIC(InCopy, Note, "in copy of {0}", TypeOfInstId);
  870. builder.Note(value_id, InCopy, value_id);
  871. });
  872. foundation_value_id =
  873. PerformBuiltinConversion(context, loc_id, foundation_value_id,
  874. {.kind = target.kind,
  875. .type_id = foundation_type_id,
  876. .init_id = foundation_init_id,
  877. .init_block = target.init_block,
  878. .diagnose = target.diagnose});
  879. if (foundation_value_id == SemIR::ErrorInst::InstId) {
  880. return SemIR::ErrorInst::InstId;
  881. }
  882. }
  883. return AddInst<SemIR::AsCompatible>(
  884. context, loc_id,
  885. {.type_id = target.type_id, .source_id = foundation_value_id});
  886. }
  887. }
  888. // T explicitly converts to U if T is compatible with U, and we're allowed to
  889. // remove / add any qualifiers that differ.
  890. if (target.is_explicit_as() && target.type_id != value_type_id) {
  891. auto [target_foundation_id, target_quals] =
  892. context.types().GetTransitiveUnqualifiedAdaptedType(target.type_id);
  893. auto [value_foundation_id, value_quals] =
  894. context.types().GetTransitiveUnqualifiedAdaptedType(value_type_id);
  895. if (target_foundation_id == value_foundation_id) {
  896. auto category = SemIR::GetExprCategory(context.sem_ir(), value_id);
  897. auto added_quals = target_quals & ~value_quals;
  898. auto removed_quals = value_quals & ~target_quals;
  899. if (CanAddQualifiers(added_quals, category) &&
  900. CanRemoveQualifiers(
  901. removed_quals, category,
  902. target.kind == ConversionTarget::ExplicitUnsafeAs)) {
  903. // For a struct or tuple literal, perform a category conversion if
  904. // necessary.
  905. if (category == SemIR::ExprCategory::Mixed) {
  906. value_id = PerformBuiltinConversion(context, loc_id, value_id,
  907. {.kind = ConversionTarget::Value,
  908. .type_id = value_type_id,
  909. .diagnose = target.diagnose});
  910. }
  911. // `MaybeUnformed(T)` has a pointer value representation, and `T` might
  912. // not, so convert as needed when removing `MaybeUnformed`.
  913. bool need_value_binding = false;
  914. if ((removed_quals & SemIR::TypeQualifiers::MaybeUnformed) !=
  915. SemIR::TypeQualifiers::None &&
  916. category == SemIR::ExprCategory::Value) {
  917. value_id = AddInst<SemIR::ValueAsRef>(
  918. context, loc_id,
  919. {.type_id = value_type_id, .value_id = value_id});
  920. need_value_binding = true;
  921. }
  922. value_id = AddInst<SemIR::AsCompatible>(
  923. context, loc_id,
  924. {.type_id = target.type_id, .source_id = value_id});
  925. if (need_value_binding) {
  926. value_id = AddInst<SemIR::BindValue>(
  927. context, loc_id,
  928. {.type_id = target.type_id, .value_id = value_id});
  929. }
  930. return value_id;
  931. } else {
  932. // TODO: Produce a custom diagnostic explaining that we can't perform
  933. // this conversion due to the change in qualifiers and/or the expression
  934. // category.
  935. }
  936. }
  937. }
  938. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  939. // converts to Ui.
  940. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  941. if (auto src_tuple_type =
  942. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  943. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  944. value_id, target);
  945. }
  946. }
  947. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  948. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  949. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  950. // to Ui.
  951. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  952. if (auto src_struct_type =
  953. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  954. return ConvertStructToStruct(context, *src_struct_type,
  955. *target_struct_type, value_id, target);
  956. }
  957. }
  958. // No other conversions apply when the source and destination types are the
  959. // same.
  960. if (value_type_id == target.type_id) {
  961. return value_id;
  962. }
  963. // A tuple (T1, T2, ..., Tn) converts to array(T, n) if each Ti converts to T.
  964. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  965. if (auto src_tuple_type =
  966. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  967. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  968. value_id, target);
  969. }
  970. }
  971. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  972. // if it converts to the struct type that is the class's representation type
  973. // (a struct with the same fields as the class, plus a base field where
  974. // relevant).
  975. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  976. if (auto src_struct_type =
  977. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  978. if (!context.classes()
  979. .Get(target_class_type->class_id)
  980. .adapt_id.has_value()) {
  981. return ConvertStructToClass(context, *src_struct_type,
  982. *target_class_type, value_id, target,
  983. vtable_class_type);
  984. }
  985. }
  986. // An expression of type T converts to U if T is a class derived from U.
  987. if (auto path = ComputeInheritancePath(context, loc_id, value_type_id,
  988. target.type_id);
  989. path && !path->empty()) {
  990. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  991. }
  992. }
  993. // A pointer T* converts to [qualified] U* if T is the same as U, or is a
  994. // class derived from U.
  995. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  996. if (auto src_pointer_type =
  997. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  998. auto target_pointee_id = context.types().GetTypeIdForTypeInstId(
  999. target_pointer_type->pointee_id);
  1000. auto src_pointee_id =
  1001. context.types().GetTypeIdForTypeInstId(src_pointer_type->pointee_id);
  1002. // Try to complete the pointee types so that we can walk through adapters
  1003. // to their adapted types.
  1004. TryToCompleteType(context, target_pointee_id, loc_id);
  1005. TryToCompleteType(context, src_pointee_id, loc_id);
  1006. auto [unqual_target_pointee_type_id, target_quals] =
  1007. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(target_pointee_id);
  1008. auto [unqual_src_pointee_type_id, src_quals] =
  1009. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(src_pointee_id);
  1010. // If the qualifiers are incompatible, we can't perform a conversion,
  1011. // except with `unsafe as`.
  1012. if ((src_quals & ~target_quals) != SemIR::TypeQualifiers::None &&
  1013. target.kind != ConversionTarget::ExplicitUnsafeAs) {
  1014. // TODO: Consider producing a custom diagnostic here for a cast that
  1015. // discards constness.
  1016. return value_id;
  1017. }
  1018. if (unqual_target_pointee_type_id != unqual_src_pointee_type_id) {
  1019. // If there's an inheritance path from target to source, this is a
  1020. // derived to base conversion.
  1021. if (auto path = ComputeInheritancePath(context, loc_id,
  1022. unqual_src_pointee_type_id,
  1023. unqual_target_pointee_type_id);
  1024. path && !path->empty()) {
  1025. value_id = ConvertDerivedPointerToBasePointer(
  1026. context, loc_id, *src_pointer_type, target.type_id, value_id,
  1027. *path);
  1028. } else {
  1029. // No conversion was possible.
  1030. return value_id;
  1031. }
  1032. }
  1033. // Perform a compatible conversion to add any new qualifiers.
  1034. if (src_quals != target_quals) {
  1035. return AddInst<SemIR::AsCompatible>(
  1036. context, loc_id,
  1037. {.type_id = target.type_id, .source_id = value_id});
  1038. }
  1039. return value_id;
  1040. }
  1041. }
  1042. if (target.type_id == SemIR::TypeType::TypeId ||
  1043. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1044. auto type_value_id = SemIR::InstId::None;
  1045. // A tuple of types converts to type `type`.
  1046. // TODO: This should apply even for non-literal tuples.
  1047. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  1048. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  1049. for (auto tuple_inst_id :
  1050. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  1051. // TODO: This call recurses back into conversion. Switch to an
  1052. // iterative approach.
  1053. type_inst_ids.push_back(
  1054. ExprAsType(context, loc_id, tuple_inst_id, target.diagnose)
  1055. .inst_id);
  1056. }
  1057. // TODO: Should we add this as an instruction? It will contain references
  1058. // to local InstIds.
  1059. auto tuple_type_id = GetTupleType(context, type_inst_ids);
  1060. type_value_id = sem_ir.types().GetInstId(tuple_type_id);
  1061. }
  1062. // `{}` converts to `{} as type`.
  1063. // TODO: This conversion should also be performed for a non-literal value
  1064. // of type `{}`.
  1065. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  1066. struct_literal &&
  1067. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  1068. type_value_id = sem_ir.types().GetInstId(value_type_id);
  1069. }
  1070. if (type_value_id != SemIR::InstId::None) {
  1071. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1072. // Use the converted `TypeType` value for converting to a facet.
  1073. value_id = type_value_id;
  1074. value_type_id = SemIR::TypeType::TypeId;
  1075. } else {
  1076. // We wanted a `TypeType`, and we've done that.
  1077. return type_value_id;
  1078. }
  1079. }
  1080. }
  1081. // FacetType converts to Type by wrapping the facet value in
  1082. // FacetAccessType.
  1083. if (target.type_id == SemIR::TypeType::TypeId &&
  1084. sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1085. return AddInst<SemIR::FacetAccessType>(
  1086. context, loc_id,
  1087. {.type_id = target.type_id, .facet_value_inst_id = value_id});
  1088. }
  1089. // Type values can convert to facet values, and facet values can convert to
  1090. // other facet values, as long as they satisfy the required interfaces of the
  1091. // target `FacetType`.
  1092. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id) &&
  1093. (sem_ir.types().Is<SemIR::TypeType>(value_type_id) ||
  1094. sem_ir.types().Is<SemIR::FacetType>(value_type_id))) {
  1095. // The value is a type or facet value, so it has a constant value. We get
  1096. // that to unwrap things like NameRef and get to the underlying type or
  1097. // facet value instruction so that we can use `TryGetAs`.
  1098. auto const_value_id = sem_ir.constant_values().GetConstantInstId(value_id);
  1099. // TODO: Runtime facet values should be allowed to convert based on their
  1100. // FacetTypes, but we assume constant values for impl lookup at the moment.
  1101. if (!const_value_id.has_value()) {
  1102. context.TODO(loc_id, "conversion of runtime facet value");
  1103. const_value_id = SemIR::ErrorInst::InstId;
  1104. }
  1105. if (auto facet_access_type_inst =
  1106. sem_ir.insts().TryGetAs<SemIR::FacetAccessType>(const_value_id)) {
  1107. // Conversion from a `FacetAccessType` to a `FacetValue` of the target
  1108. // `FacetType` if the instruction in the `FacetAccessType` is of a
  1109. // `FacetType` that satisfies the requirements of the target `FacetType`.
  1110. // If the `FacetType` exactly matches the target `FacetType` then we can
  1111. // shortcut and use that value, and avoid impl lookup.
  1112. auto facet_value_inst_id = facet_access_type_inst->facet_value_inst_id;
  1113. if (sem_ir.insts().Get(facet_value_inst_id).type_id() == target.type_id) {
  1114. return facet_value_inst_id;
  1115. }
  1116. }
  1117. // Conversion from a facet value (which has type `FacetType`) or a type
  1118. // value (which has type `TypeType`) to a facet value. We can do this if the
  1119. // type satisfies the requirements of the target `FacetType`, as determined
  1120. // by finding impl witnesses for the target FacetType.
  1121. auto lookup_result = LookupImplWitness(
  1122. context, loc_id, sem_ir.constant_values().Get(const_value_id),
  1123. sem_ir.types().GetConstantId(target.type_id));
  1124. if (lookup_result.has_value()) {
  1125. if (lookup_result.has_error_value()) {
  1126. return SemIR::ErrorInst::InstId;
  1127. } else {
  1128. // We bind the input value to the target `FacetType` with a
  1129. // `FacetValue`, which requires an instruction of type `TypeType`. So if
  1130. // we are converting from a facet value, we get its `type` via an extra
  1131. // `FacetAccessType` instruction.
  1132. auto type_inst_id = SemIR::TypeInstId::None;
  1133. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1134. type_inst_id = AddTypeInst<SemIR::FacetAccessType>(
  1135. context, loc_id,
  1136. {.type_id = SemIR::TypeType::TypeId,
  1137. .facet_value_inst_id = const_value_id});
  1138. } else {
  1139. type_inst_id = context.types().GetAsTypeInstId(const_value_id);
  1140. }
  1141. // Note that `FacetValue`'s type is the same `FacetType` that was used
  1142. // to construct the set of witnesses, ie. the query to
  1143. // `LookupImplWitness()`. This ensures that the witnesses are in the
  1144. // same order as the `required_interfaces()` in the `FacetValue`'s type.
  1145. return AddInst<SemIR::FacetValue>(
  1146. context, loc_id,
  1147. {.type_id = target.type_id,
  1148. .type_inst_id = type_inst_id,
  1149. .witnesses_block_id = lookup_result.inst_block_id()});
  1150. }
  1151. } else {
  1152. // If impl lookup fails, don't keep looking for another way to convert.
  1153. // See https://github.com/carbon-language/carbon-lang/issues/5122.
  1154. // TODO: Pass this function into `LookupImplWitness` so it can construct
  1155. // the error add notes explaining failure.
  1156. if (target.diagnose) {
  1157. DiagnoseConversionFailureToConstraintValue(context, loc_id, value_id,
  1158. target.type_id);
  1159. }
  1160. return SemIR::ErrorInst::InstId;
  1161. }
  1162. }
  1163. // No builtin conversion applies.
  1164. return value_id;
  1165. }
  1166. // Given a value expression, form a corresponding initializer that copies from
  1167. // that value, if it is possible to do so.
  1168. static auto PerformCopy(Context& context, SemIR::InstId expr_id, bool diagnose)
  1169. -> SemIR::InstId {
  1170. auto expr = context.insts().Get(expr_id);
  1171. auto type_id = expr.type_id();
  1172. if (type_id == SemIR::ErrorInst::TypeId) {
  1173. return SemIR::ErrorInst::InstId;
  1174. }
  1175. if (InitReprIsCopyOfValueRepr(context.sem_ir(), type_id)) {
  1176. // For simple by-value types, no explicit action is required. Initializing
  1177. // from a value expression is treated as copying the value.
  1178. return expr_id;
  1179. }
  1180. // TODO: We don't yet have rules for whether and when a class type is
  1181. // copyable, or how to perform the copy.
  1182. if (diagnose) {
  1183. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  1184. "cannot copy value of type {0}", TypeOfInstId);
  1185. context.emitter().Emit(expr_id, CopyOfUncopyableType, expr_id);
  1186. }
  1187. return SemIR::ErrorInst::InstId;
  1188. }
  1189. // Convert a value expression so that it can be used to initialize a C++ thunk
  1190. // parameter.
  1191. static auto ConvertValueForCppThunkRef(Context& context, SemIR::InstId expr_id,
  1192. bool diagnose) -> SemIR::InstId {
  1193. auto expr = context.insts().Get(expr_id);
  1194. // If the expression has a pointer value representation, extract that and use
  1195. // it directly.
  1196. if (SemIR::ValueRepr::ForType(context.sem_ir(), expr.type_id()).kind ==
  1197. SemIR::ValueRepr::Pointer) {
  1198. return AddInst<SemIR::ValueAsRef>(
  1199. context, SemIR::LocId(expr_id),
  1200. {.type_id = expr.type_id(), .value_id = expr_id});
  1201. }
  1202. // Otherwise, we need a temporary to pass as the thunk argument. Create a copy
  1203. // and initialize a temporary from it.
  1204. expr_id = PerformCopy(context, expr_id, diagnose);
  1205. if (SemIR::GetExprCategory(context.sem_ir(), expr_id) ==
  1206. SemIR::ExprCategory::Value) {
  1207. // If we still have a value expression, then it's a value expression
  1208. // whose value is being used directly to initialize the object. Copy
  1209. // it into a temporary to form an ephemeral reference.
  1210. expr_id = CopyValueToTemporary(context, expr_id);
  1211. }
  1212. return expr_id;
  1213. }
  1214. // Returns the Core interface name to use for a given kind of conversion.
  1215. static auto GetConversionInterfaceName(ConversionTarget::Kind kind)
  1216. -> llvm::StringLiteral {
  1217. switch (kind) {
  1218. case ConversionTarget::ExplicitAs:
  1219. return "As";
  1220. case ConversionTarget::ExplicitUnsafeAs:
  1221. return "UnsafeAs";
  1222. default:
  1223. return "ImplicitAs";
  1224. }
  1225. }
  1226. auto PerformAction(Context& context, SemIR::LocId loc_id,
  1227. SemIR::ConvertToValueAction action) -> SemIR::InstId {
  1228. return Convert(context, loc_id, action.inst_id,
  1229. {.kind = ConversionTarget::Value,
  1230. .type_id = context.types().GetTypeIdForTypeInstId(
  1231. action.target_type_inst_id)});
  1232. }
  1233. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  1234. ConversionTarget target, SemIR::ClassType* vtable_class_type)
  1235. -> SemIR::InstId {
  1236. auto& sem_ir = context.sem_ir();
  1237. auto orig_expr_id = expr_id;
  1238. // Start by making sure both sides are non-errors. If any part is an error,
  1239. // the result is an error and we shouldn't diagnose.
  1240. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::ErrorInst::TypeId ||
  1241. target.type_id == SemIR::ErrorInst::TypeId) {
  1242. return SemIR::ErrorInst::InstId;
  1243. }
  1244. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  1245. // TODO: We currently encounter this for use of namespaces and functions.
  1246. // We should provide a better diagnostic for inappropriate use of
  1247. // namespace names, and allow use of functions as values.
  1248. if (target.diagnose) {
  1249. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  1250. "expression cannot be used as a value");
  1251. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  1252. }
  1253. return SemIR::ErrorInst::InstId;
  1254. }
  1255. // We can only perform initialization for complete, non-abstract types. Note
  1256. // that `RequireConcreteType` returns true for facet types, since their
  1257. // representation is fixed. This allows us to support using the `Self` of an
  1258. // interface inside its definition.
  1259. if (!RequireConcreteType(
  1260. context, target.type_id, loc_id,
  1261. [&] {
  1262. CARBON_CHECK(!target.is_initializer(),
  1263. "Initialization of incomplete types is expected to be "
  1264. "caught elsewhere.");
  1265. if (!target.diagnose) {
  1266. return context.emitter().BuildSuppressed();
  1267. }
  1268. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  1269. "forming value of incomplete type {0}",
  1270. SemIR::TypeId);
  1271. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  1272. "invalid use of incomplete type {0}",
  1273. SemIR::TypeId);
  1274. return context.emitter().Build(
  1275. loc_id,
  1276. target.kind == ConversionTarget::Value
  1277. ? IncompleteTypeInValueConversion
  1278. : IncompleteTypeInConversion,
  1279. target.type_id);
  1280. },
  1281. [&] {
  1282. if (!target.diagnose || !target.is_initializer()) {
  1283. return context.emitter().BuildSuppressed();
  1284. }
  1285. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  1286. "initialization of abstract type {0}",
  1287. SemIR::TypeId);
  1288. return context.emitter().Build(loc_id, AbstractTypeInInit,
  1289. target.type_id);
  1290. })) {
  1291. return SemIR::ErrorInst::InstId;
  1292. }
  1293. // The source type doesn't need to be complete, but its completeness can
  1294. // affect the result. For example, we don't know what type it adapts or
  1295. // derives from unless it's complete.
  1296. // TODO: Is there a risk of coherence problems if the source type is
  1297. // incomplete, but a conversion would have been possible or would have behaved
  1298. // differently if it were complete?
  1299. TryToCompleteType(context, context.insts().Get(expr_id).type_id(), loc_id);
  1300. // Check whether any builtin conversion applies.
  1301. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target,
  1302. vtable_class_type);
  1303. if (expr_id == SemIR::ErrorInst::InstId) {
  1304. return expr_id;
  1305. }
  1306. // Defer the action if it's dependent. We do this now rather than before
  1307. // attempting any conversion so that we can still perform builtin conversions
  1308. // on dependent arguments. This matters for things like converting a
  1309. // `template T:! SomeInterface` to `type`, where it's important to form a
  1310. // `FacetAccessType` when checking the template. But when running the action
  1311. // later, we need to try builtin conversions again, because one may apply that
  1312. // didn't apply in the template definition.
  1313. // TODO: Support this for targets other than `Value`.
  1314. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id &&
  1315. target.kind == ConversionTarget::Value &&
  1316. (OperandIsDependent(context, expr_id) ||
  1317. OperandIsDependent(context, target.type_id))) {
  1318. auto target_type_inst_id = context.types().GetInstId(target.type_id);
  1319. return AddDependentActionSplice(
  1320. context, loc_id,
  1321. SemIR::ConvertToValueAction{.type_id = SemIR::InstType::TypeId,
  1322. .inst_id = expr_id,
  1323. .target_type_inst_id = target_type_inst_id},
  1324. target_type_inst_id);
  1325. }
  1326. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  1327. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  1328. SemIR::InstId interface_args[] = {
  1329. context.types().GetInstId(target.type_id)};
  1330. Operator op = {
  1331. .interface_name = GetConversionInterfaceName(target.kind),
  1332. .interface_args_ref = interface_args,
  1333. .op_name = "Convert",
  1334. };
  1335. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  1336. if (!target.diagnose) {
  1337. return context.emitter().BuildSuppressed();
  1338. }
  1339. int target_kind_for_diag =
  1340. target.kind == ConversionTarget::ExplicitAs ? 1
  1341. : target.kind == ConversionTarget::ExplicitUnsafeAs ? 2
  1342. : 0;
  1343. if (target.type_id == SemIR::TypeType::TypeId ||
  1344. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1345. CARBON_DIAGNOSTIC(
  1346. ConversionFailureNonTypeToFacet, Error,
  1347. "cannot{0:=0: implicitly|:} convert non-type value of type {1} "
  1348. "{2:to|into type implementing} {3}"
  1349. "{0:=1: with `as`|=2: with `unsafe as`|:}",
  1350. Diagnostics::IntAsSelect, TypeOfInstId, Diagnostics::BoolAsSelect,
  1351. SemIR::TypeId);
  1352. return context.emitter().Build(
  1353. loc_id, ConversionFailureNonTypeToFacet, target_kind_for_diag,
  1354. expr_id, target.type_id == SemIR::TypeType::TypeId, target.type_id);
  1355. } else {
  1356. CARBON_DIAGNOSTIC(
  1357. ConversionFailure, Error,
  1358. "cannot{0:=0: implicitly|:} convert expression of type "
  1359. "{1} to {2}{0:=1: with `as`|=2: with `unsafe as`|:}",
  1360. Diagnostics::IntAsSelect, TypeOfInstId, SemIR::TypeId);
  1361. return context.emitter().Build(loc_id, ConversionFailure,
  1362. target_kind_for_diag, expr_id,
  1363. target.type_id);
  1364. }
  1365. });
  1366. // Pull a value directly out of the initializer if possible and wanted.
  1367. if (expr_id != SemIR::ErrorInst::InstId &&
  1368. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  1369. expr_id = AddInst<SemIR::ValueOfInitializer>(
  1370. context, loc_id, {.type_id = target.type_id, .init_id = expr_id});
  1371. }
  1372. }
  1373. // Track that we performed a type conversion, if we did so.
  1374. if (orig_expr_id != expr_id) {
  1375. expr_id = AddInst<SemIR::Converted>(context, loc_id,
  1376. {.type_id = target.type_id,
  1377. .original_id = orig_expr_id,
  1378. .result_id = expr_id});
  1379. }
  1380. // For `as`, don't perform any value category conversions. In particular, an
  1381. // identity conversion shouldn't change the expression category.
  1382. if (target.is_explicit_as()) {
  1383. return expr_id;
  1384. }
  1385. // Now perform any necessary value category conversions.
  1386. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  1387. case SemIR::ExprCategory::NotExpr:
  1388. case SemIR::ExprCategory::Mixed:
  1389. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  1390. sem_ir.insts().Get(expr_id));
  1391. case SemIR::ExprCategory::Error:
  1392. return SemIR::ErrorInst::InstId;
  1393. case SemIR::ExprCategory::Initializing:
  1394. if (target.is_initializer()) {
  1395. if (orig_expr_id == expr_id) {
  1396. // Don't fill in the return slot if we created the expression through
  1397. // a conversion. In that case, we will have created it with the
  1398. // target already set.
  1399. // TODO: Find a better way to track whether we need to do this.
  1400. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  1401. *target.init_block);
  1402. }
  1403. break;
  1404. }
  1405. // Commit to using a temporary for this initializing expression.
  1406. // TODO: Don't create a temporary if the initializing representation
  1407. // is already a value representation.
  1408. // TODO: If the target is DurableRef, materialize a VarStorage instead of
  1409. // a TemporaryStorage to lifetime-extend.
  1410. expr_id = FinalizeTemporary(context, expr_id,
  1411. target.kind == ConversionTarget::Discarded);
  1412. // We now have an ephemeral reference.
  1413. [[fallthrough]];
  1414. case SemIR::ExprCategory::DurableRef:
  1415. if (target.kind == ConversionTarget::DurableRef) {
  1416. break;
  1417. }
  1418. [[fallthrough]];
  1419. case SemIR::ExprCategory::EphemeralRef:
  1420. // If a reference expression is an acceptable result, we're done.
  1421. if (target.kind == ConversionTarget::ValueOrRef ||
  1422. target.kind == ConversionTarget::Discarded ||
  1423. target.kind == ConversionTarget::CppThunkRef) {
  1424. break;
  1425. }
  1426. // If we have a reference and don't want one, form a value binding.
  1427. // TODO: Support types with custom value representations.
  1428. expr_id = AddInst<SemIR::BindValue>(
  1429. context, SemIR::LocId(expr_id),
  1430. {.type_id = target.type_id, .value_id = expr_id});
  1431. // We now have a value expression.
  1432. [[fallthrough]];
  1433. case SemIR::ExprCategory::Value:
  1434. if (target.kind == ConversionTarget::DurableRef) {
  1435. if (target.diagnose) {
  1436. CARBON_DIAGNOSTIC(ConversionFailureNonRefToRef, Error,
  1437. "cannot bind durable reference to non-reference "
  1438. "value of type {0}",
  1439. SemIR::TypeId);
  1440. context.emitter().Emit(loc_id, ConversionFailureNonRefToRef,
  1441. target.type_id);
  1442. }
  1443. return SemIR::ErrorInst::InstId;
  1444. }
  1445. // When initializing from a value, perform a copy.
  1446. if (target.is_initializer()) {
  1447. expr_id = PerformCopy(context, expr_id, target.diagnose);
  1448. }
  1449. // When initializing a C++ thunk parameter, form a reference, creating a
  1450. // temporary if needed.
  1451. if (target.kind == ConversionTarget::CppThunkRef) {
  1452. expr_id = ConvertValueForCppThunkRef(context, expr_id, target.diagnose);
  1453. }
  1454. break;
  1455. }
  1456. // Perform a final destination store, if necessary.
  1457. if (target.kind == ConversionTarget::FullInitializer) {
  1458. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1459. init_rep.kind == SemIR::InitRepr::ByCopy) {
  1460. target.init_block->InsertHere();
  1461. expr_id = AddInst<SemIR::InitializeFrom>(context, loc_id,
  1462. {.type_id = target.type_id,
  1463. .src_id = expr_id,
  1464. .dest_id = target.init_id});
  1465. }
  1466. }
  1467. return expr_id;
  1468. }
  1469. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId target_id,
  1470. SemIR::InstId value_id) -> SemIR::InstId {
  1471. PendingBlock target_block(&context);
  1472. return Convert(context, loc_id, value_id,
  1473. {.kind = ConversionTarget::Initializer,
  1474. .type_id = context.insts().Get(target_id).type_id(),
  1475. .init_id = target_id,
  1476. .init_block = &target_block});
  1477. }
  1478. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1479. -> SemIR::InstId {
  1480. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1481. {.kind = ConversionTarget::Value,
  1482. .type_id = context.insts().Get(expr_id).type_id()});
  1483. }
  1484. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1485. -> SemIR::InstId {
  1486. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1487. {.kind = ConversionTarget::ValueOrRef,
  1488. .type_id = context.insts().Get(expr_id).type_id()});
  1489. }
  1490. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1491. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1492. -> SemIR::InstId {
  1493. return Convert(context, loc_id, expr_id,
  1494. {.kind = ConversionTarget::Value, .type_id = type_id});
  1495. }
  1496. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1497. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1498. -> SemIR::InstId {
  1499. return Convert(context, loc_id, expr_id,
  1500. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1501. }
  1502. // Like ConvertToValueOfType but failure to convert does not result in
  1503. // diagnostics. An ErrorInst instruction is still returned on failure.
  1504. auto TryConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1505. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1506. -> SemIR::InstId {
  1507. return Convert(
  1508. context, loc_id, expr_id,
  1509. {.kind = ConversionTarget::Value, .type_id = type_id, .diagnose = false});
  1510. }
  1511. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1512. SemIR::InstId value_id) -> SemIR::InstId {
  1513. return ConvertToValueOfType(
  1514. context, loc_id, value_id,
  1515. GetSingletonType(context, SemIR::BoolType::TypeInstId));
  1516. }
  1517. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1518. SemIR::InstId value_id, SemIR::TypeId type_id,
  1519. bool unsafe) -> SemIR::InstId {
  1520. return Convert(context, as_node, value_id,
  1521. {.kind = unsafe ? ConversionTarget::ExplicitUnsafeAs
  1522. : ConversionTarget::ExplicitAs,
  1523. .type_id = type_id});
  1524. }
  1525. // TODO: Consider moving this to pattern_match.h.
  1526. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1527. SemIR::InstId self_id,
  1528. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1529. SemIR::InstId return_slot_arg_id,
  1530. const SemIR::Function& callee,
  1531. SemIR::SpecificId callee_specific_id)
  1532. -> SemIR::InstBlockId {
  1533. auto param_patterns =
  1534. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1535. auto return_slot_pattern_id = callee.return_slot_pattern_id;
  1536. // The caller should have ensured this callee has the right arity.
  1537. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1538. if (callee.self_param_id.has_value() && !self_id.has_value()) {
  1539. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1540. "missing object argument in method call");
  1541. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1542. context.emitter()
  1543. .Build(call_loc_id, MissingObjectInMethodCall)
  1544. .Note(callee.latest_decl_id(), InCallToFunction)
  1545. .Emit();
  1546. self_id = SemIR::ErrorInst::InstId;
  1547. }
  1548. return CallerPatternMatch(context, callee_specific_id, callee.self_param_id,
  1549. callee.param_patterns_id, return_slot_pattern_id,
  1550. self_id, arg_refs, return_slot_arg_id);
  1551. }
  1552. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  1553. bool diagnose) -> TypeExpr {
  1554. auto type_inst_id =
  1555. ConvertToValueOfType(context, loc_id, value_id, SemIR::TypeType::TypeId);
  1556. if (type_inst_id == SemIR::ErrorInst::InstId) {
  1557. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1558. .type_id = SemIR::ErrorInst::TypeId};
  1559. }
  1560. auto type_const_id = context.constant_values().Get(type_inst_id);
  1561. if (!type_const_id.is_constant()) {
  1562. if (diagnose) {
  1563. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1564. "cannot evaluate type expression");
  1565. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1566. }
  1567. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1568. .type_id = SemIR::ErrorInst::TypeId};
  1569. }
  1570. return {.inst_id = context.types().GetAsTypeInstId(type_inst_id),
  1571. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1572. }
  1573. auto DiscardExpr(Context& context, SemIR::InstId expr_id) -> void {
  1574. // If we discard an initializing expression, convert it to a value or
  1575. // reference so that it has something to initialize.
  1576. auto expr = context.insts().Get(expr_id);
  1577. Convert(context, SemIR::LocId(expr_id), expr_id,
  1578. {.kind = ConversionTarget::Discarded, .type_id = expr.type_id()});
  1579. // TODO: This will eventually need to do some "do not discard" analysis.
  1580. }
  1581. } // namespace Carbon::Check
  1582. // NOLINTEND(misc-no-recursion)