convert.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098
  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/core_identifier.h"
  16. #include "toolchain/check/diagnostic_helpers.h"
  17. #include "toolchain/check/eval.h"
  18. #include "toolchain/check/impl_lookup.h"
  19. #include "toolchain/check/import_ref.h"
  20. #include "toolchain/check/inst.h"
  21. #include "toolchain/check/operator.h"
  22. #include "toolchain/check/pattern_match.h"
  23. #include "toolchain/check/type.h"
  24. #include "toolchain/check/type_completion.h"
  25. #include "toolchain/diagnostics/emitter.h"
  26. #include "toolchain/diagnostics/format_providers.h"
  27. #include "toolchain/sem_ir/copy_on_write_block.h"
  28. #include "toolchain/sem_ir/expr_info.h"
  29. #include "toolchain/sem_ir/file.h"
  30. #include "toolchain/sem_ir/generic.h"
  31. #include "toolchain/sem_ir/ids.h"
  32. #include "toolchain/sem_ir/inst.h"
  33. #include "toolchain/sem_ir/type.h"
  34. #include "toolchain/sem_ir/type_info.h"
  35. #include "toolchain/sem_ir/typed_insts.h"
  36. // TODO: This contains a lot of recursion. Consider removing it in order to
  37. // prevent accidents.
  38. // NOLINTBEGIN(misc-no-recursion)
  39. namespace Carbon::Check {
  40. // If the initializing expression `init_id` has a storage argument that refers
  41. // to a temporary, overwrites it with the inst at `target.storage_id`, and
  42. // returns the ID that should now be used to refer to `init_id`'s storage. Has
  43. // no effect and returns `target.storage_id` unchanged if `target.storage_id` is
  44. // None, if `init_id` doesn't have a storage arg, or if the storage argument
  45. // doesn't point to a temporary. In the latter case, we assume it was set
  46. // correctly when the instruction was created.
  47. static auto OverwriteTemporaryStorageArg(SemIR::File& sem_ir,
  48. SemIR::InstId init_id,
  49. const ConversionTarget& target)
  50. -> SemIR::InstId {
  51. CARBON_CHECK(target.is_initializer());
  52. if (!target.storage_id.has_value()) {
  53. return SemIR::InstId::None;
  54. }
  55. auto storage_arg_id = FindStorageArgForInitializer(sem_ir, init_id);
  56. if (!storage_arg_id.has_value() || storage_arg_id == target.storage_id ||
  57. !sem_ir.insts().Is<SemIR::TemporaryStorage>(storage_arg_id)) {
  58. return target.storage_id;
  59. }
  60. // Replace the temporary in the storage argument with a reference to our
  61. // target.
  62. return target.storage_access_block->MergeReplacing(storage_arg_id,
  63. target.storage_id);
  64. }
  65. // Materializes and returns a temporary initialized from the initializer
  66. // `init_id`. If `init_id` has a storage arg, it must be a `TemporaryStorage`;
  67. // if not, this function allocates one for it.
  68. static auto MaterializeTemporary(Context& context, SemIR::InstId init_id)
  69. -> SemIR::InstId {
  70. auto& sem_ir = context.sem_ir();
  71. auto category = SemIR::GetExprCategory(sem_ir, init_id);
  72. CARBON_CHECK(SemIR::IsInitializerCategory(category));
  73. auto init = sem_ir.insts().Get(init_id);
  74. auto storage_id = FindStorageArgForInitializer(sem_ir, init_id);
  75. if (!storage_id.has_value()) {
  76. CARBON_CHECK(category == SemIR::ExprCategory::ReprInitializing);
  77. // The initializer has no storage arg, but we want to produce an ephemeral
  78. // reference, so we need to allocate temporary storage.
  79. storage_id = AddInst<SemIR::TemporaryStorage>(
  80. context, SemIR::LocId(init_id), {.type_id = init.type_id()});
  81. }
  82. CARBON_CHECK(
  83. sem_ir.insts().Get(storage_id).kind() == SemIR::TemporaryStorage::Kind,
  84. "Storage arg for initializer does not contain a temporary; "
  85. "initialized multiple times? Have {0}",
  86. sem_ir.insts().Get(storage_id));
  87. return AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(init_id),
  88. {.type_id = init.type_id(),
  89. .storage_id = storage_id,
  90. .init_id = init_id});
  91. }
  92. // Discards the initializer `init_id`. If `init_id` intrinsically writes to
  93. // memory, this materializes a temporary for it and starts its lifetime.
  94. //
  95. // TODO: We should probably start its lifetime unconditionally, because
  96. // types with by-copy representations can still have nontrivial destructors.
  97. static auto DiscardInitializer(Context& context, SemIR::InstId init_id)
  98. -> void {
  99. auto& sem_ir = context.sem_ir();
  100. auto storage_id = FindStorageArgForInitializer(sem_ir, init_id);
  101. if (!storage_id.has_value()) {
  102. CARBON_CHECK(SemIR::GetExprCategory(sem_ir, init_id) ==
  103. SemIR::ExprCategory::ReprInitializing);
  104. return;
  105. }
  106. // init_id writes to temporary storage, so we need to materialize a temporary
  107. // for it.
  108. MaterializeTemporary(context, init_id);
  109. }
  110. // If `expr_id` is an initializer, materializes it and returns the resulting
  111. // ephemeral reference expression. Otherwise, returns `expr_id`.
  112. static auto MaterializeIfInitializer(Context& context, SemIR::InstId expr_id)
  113. -> SemIR::InstId {
  114. if (SemIR::IsInitializerCategory(
  115. SemIR::GetExprCategory(context.sem_ir(), expr_id))) {
  116. return MaterializeTemporary(context, expr_id);
  117. } else {
  118. return expr_id;
  119. }
  120. }
  121. // Helper to allow `MakeElementAccessInst` to call `AddInst` with either a
  122. // `PendingBlock` or `Context` (defined in `inst.h`).
  123. template <typename AccessInstT>
  124. static auto AddInst(PendingBlock& block, SemIR::LocId loc_id, AccessInstT inst)
  125. -> SemIR::InstId {
  126. return block.AddInst<AccessInstT>(loc_id, inst);
  127. }
  128. // Creates and adds an instruction to perform element access into an aggregate.
  129. template <typename AccessInstT, typename InstBlockT>
  130. static auto MakeElementAccessInst(Context& context, SemIR::LocId loc_id,
  131. SemIR::InstId aggregate_id,
  132. SemIR::TypeId elem_type_id, InstBlockT& block,
  133. size_t i) -> SemIR::InstId {
  134. if (!aggregate_id.has_value()) {
  135. return SemIR::InstId::None;
  136. }
  137. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  138. // TODO: Add a new instruction kind for indexing an array at a constant
  139. // index so that we don't need an integer literal instruction here, and
  140. // remove this special case.
  141. auto index_id = block.template AddInst<SemIR::IntValue>(
  142. loc_id, {.type_id = GetSingletonType(context,
  143. SemIR::IntLiteralType::TypeInstId),
  144. .int_id = context.ints().Add(static_cast<int64_t>(i))});
  145. return AddInst<AccessInstT>(block, loc_id,
  146. {elem_type_id, aggregate_id, index_id});
  147. } else {
  148. return AddInst<AccessInstT>(
  149. block, loc_id, {elem_type_id, aggregate_id, SemIR::ElementIndex(i)});
  150. }
  151. }
  152. // Get the conversion target kind to use when initializing an element of an
  153. // aggregate.
  154. static auto GetAggregateElementConversionTargetKind(SemIR::File& sem_ir,
  155. ConversionTarget target)
  156. -> ConversionTarget::Kind {
  157. // If we're forming an initializer, then we want an initializer for each
  158. // element.
  159. if (target.is_initializer()) {
  160. // Perform a final destination store if we're performing an in-place
  161. // initialization.
  162. auto init_repr = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  163. CARBON_CHECK(init_repr.kind != SemIR::InitRepr::Dependent,
  164. "Aggregate should not have dependent init kind");
  165. if (init_repr.kind == SemIR::InitRepr::InPlace) {
  166. return ConversionTarget::InPlaceInitializing;
  167. }
  168. return ConversionTarget::Initializing;
  169. }
  170. // Otherwise, we want a value representation for each element.
  171. return ConversionTarget::Value;
  172. }
  173. // Converts an element of one aggregate so that it can be used as an element of
  174. // another aggregate.
  175. //
  176. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  177. // element type, `src_field_index` is the index, and `SourceAccessInstT` is the
  178. // kind of instruction used to access the source element.
  179. //
  180. // For the target: `kind` is the kind of conversion or initialization,
  181. // `target_elem_type` is the element type. For initialization, `target_id` is
  182. // the destination, `target_block` is a pending block for target location
  183. // calculations that will be spliced as the return slot of the initializer if
  184. // necessary, `target_field_index` is the index, and `TargetAccessInstT` is the
  185. // kind of instruction used to access the destination element.
  186. template <typename SourceAccessInstT, typename TargetAccessInstT>
  187. static auto ConvertAggregateElement(
  188. Context& context, SemIR::LocId loc_id, SemIR::InstId src_id,
  189. SemIR::TypeInstId src_elem_type_inst,
  190. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  191. ConversionTarget::Kind kind, SemIR::InstId target_id,
  192. SemIR::TypeInstId target_elem_type_inst, PendingBlock* target_block,
  193. size_t src_field_index, size_t target_field_index,
  194. SemIR::ClassType* vtable_class_type = nullptr) -> SemIR::InstId {
  195. auto src_elem_type =
  196. context.types().GetTypeIdForTypeInstId(src_elem_type_inst);
  197. auto target_elem_type =
  198. context.types().GetTypeIdForTypeInstId(target_elem_type_inst);
  199. // Compute the location of the source element. This goes into the current code
  200. // block, not into the target block.
  201. // TODO: Ideally we would discard this instruction if it's unused.
  202. auto src_elem_id = !src_literal_elems.empty()
  203. ? src_literal_elems[src_field_index]
  204. : MakeElementAccessInst<SourceAccessInstT>(
  205. context, loc_id, src_id, src_elem_type, context,
  206. src_field_index);
  207. // If we're performing a conversion rather than an initialization, we won't
  208. // have or need a target.
  209. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  210. if (!target.is_initializer()) {
  211. return Convert(context, loc_id, src_elem_id, target);
  212. }
  213. // Compute the location of the target element and initialize it.
  214. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  215. target.storage_access_block = target_block;
  216. target.storage_id = MakeElementAccessInst<TargetAccessInstT>(
  217. context, loc_id, target_id, target_elem_type, *target_block,
  218. target_field_index);
  219. return Convert(context, loc_id, src_elem_id, target, vtable_class_type);
  220. }
  221. // Performs a conversion from a tuple to an array type. This function only
  222. // converts the type, and does not perform a final conversion to the requested
  223. // expression category.
  224. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  225. SemIR::ArrayType array_type,
  226. SemIR::InstId value_id, ConversionTarget target)
  227. -> SemIR::InstId {
  228. auto& sem_ir = context.sem_ir();
  229. auto tuple_elem_types = sem_ir.inst_blocks().Get(tuple_type.type_elements_id);
  230. auto value = sem_ir.insts().Get(value_id);
  231. SemIR::LocId value_loc_id(value_id);
  232. // If we're initializing from a tuple literal, we will use its elements
  233. // directly. Otherwise, materialize a temporary if needed and index into the
  234. // result.
  235. llvm::ArrayRef<SemIR::InstId> literal_elems;
  236. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  237. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  238. } else {
  239. value_id = MaterializeIfInitializer(context, value_id);
  240. }
  241. // Check that the tuple is the right size.
  242. std::optional<uint64_t> array_bound =
  243. sem_ir.GetArrayBoundValue(array_type.bound_id);
  244. if (!array_bound) {
  245. // TODO: Should this fall back to using `ImplicitAs`?
  246. if (target.diagnose) {
  247. CARBON_DIAGNOSTIC(ArrayInitDependentBound, Error,
  248. "cannot initialize array with dependent bound from a "
  249. "list of initializers");
  250. context.emitter().Emit(value_loc_id, ArrayInitDependentBound);
  251. }
  252. return SemIR::ErrorInst::InstId;
  253. }
  254. if (tuple_elem_types.size() != array_bound) {
  255. if (target.diagnose) {
  256. CARBON_DIAGNOSTIC(ArrayInitFromLiteralArgCountMismatch, Error,
  257. "cannot initialize array of {0} element{0:s} from {1} "
  258. "initializer{1:s}",
  259. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  260. CARBON_DIAGNOSTIC(
  261. ArrayInitFromExprArgCountMismatch, Error,
  262. "cannot initialize array of {0} element{0:s} from tuple "
  263. "with {1} element{1:s}",
  264. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  265. context.emitter().Emit(value_loc_id,
  266. literal_elems.empty()
  267. ? ArrayInitFromExprArgCountMismatch
  268. : ArrayInitFromLiteralArgCountMismatch,
  269. *array_bound, tuple_elem_types.size());
  270. }
  271. return SemIR::ErrorInst::InstId;
  272. }
  273. PendingBlock target_block_storage(&context);
  274. PendingBlock* target_block = target.storage_access_block
  275. ? target.storage_access_block
  276. : &target_block_storage;
  277. // Arrays are always initialized in-place. Allocate a temporary as the
  278. // destination for the array initialization if we weren't given one.
  279. SemIR::InstId return_slot_arg_id = target.storage_id;
  280. if (!target.storage_id.has_value()) {
  281. return_slot_arg_id = target_block->AddInst<SemIR::TemporaryStorage>(
  282. value_loc_id, {.type_id = target.type_id});
  283. }
  284. // Initialize each element of the array from the corresponding element of the
  285. // tuple.
  286. // TODO: Annotate diagnostics coming from here with the array element index,
  287. // if initializing from a tuple literal.
  288. llvm::SmallVector<SemIR::InstId> inits;
  289. inits.reserve(*array_bound + 1);
  290. for (auto [i, src_type_inst_id] : llvm::enumerate(
  291. context.types().GetBlockAsTypeInstIds(tuple_elem_types))) {
  292. // TODO: This call recurses back into conversion. Switch to an iterative
  293. // approach.
  294. auto init_id =
  295. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  296. context, value_loc_id, value_id, src_type_inst_id, literal_elems,
  297. ConversionTarget::InPlaceInitializing, return_slot_arg_id,
  298. array_type.element_type_inst_id, target_block, i, i);
  299. if (init_id == SemIR::ErrorInst::InstId) {
  300. return SemIR::ErrorInst::InstId;
  301. }
  302. inits.push_back(init_id);
  303. }
  304. // Flush the temporary here if we didn't insert it earlier, so we can add a
  305. // reference to the return slot.
  306. target_block->InsertHere();
  307. return AddInst<SemIR::ArrayInit>(context, value_loc_id,
  308. {.type_id = target.type_id,
  309. .inits_id = sem_ir.inst_blocks().Add(inits),
  310. .dest_id = return_slot_arg_id});
  311. }
  312. // Performs a conversion from a tuple to a tuple type. This function only
  313. // converts the type, and does not perform a final conversion to the requested
  314. // expression category.
  315. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  316. SemIR::TupleType dest_type,
  317. SemIR::InstId value_id, ConversionTarget target)
  318. -> SemIR::InstId {
  319. auto& sem_ir = context.sem_ir();
  320. auto src_elem_types = sem_ir.inst_blocks().Get(src_type.type_elements_id);
  321. auto dest_elem_types = sem_ir.inst_blocks().Get(dest_type.type_elements_id);
  322. auto value = sem_ir.insts().Get(value_id);
  323. SemIR::LocId value_loc_id(value_id);
  324. // If we're initializing from a tuple literal, we will use its elements
  325. // directly. Otherwise, materialize a temporary if needed and index into the
  326. // result.
  327. llvm::ArrayRef<SemIR::InstId> literal_elems;
  328. auto literal_elems_id = SemIR::InstBlockId::None;
  329. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  330. literal_elems_id = tuple_literal->elements_id;
  331. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  332. } else {
  333. value_id = MaterializeIfInitializer(context, value_id);
  334. }
  335. // Check that the tuples are the same size.
  336. if (src_elem_types.size() != dest_elem_types.size()) {
  337. if (target.diagnose) {
  338. CARBON_DIAGNOSTIC(
  339. TupleInitElementCountMismatch, Error,
  340. "cannot initialize tuple of {0} element{0:s} from tuple "
  341. "with {1} element{1:s}",
  342. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  343. context.emitter().Emit(value_loc_id, TupleInitElementCountMismatch,
  344. dest_elem_types.size(), src_elem_types.size());
  345. }
  346. return SemIR::ErrorInst::InstId;
  347. }
  348. ConversionTarget::Kind inner_kind =
  349. GetAggregateElementConversionTargetKind(sem_ir, target);
  350. // Initialize each element of the destination from the corresponding element
  351. // of the source.
  352. // TODO: Annotate diagnostics coming from here with the element index.
  353. auto new_block =
  354. literal_elems_id.has_value()
  355. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  356. : SemIR::CopyOnWriteInstBlock(
  357. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  358. src_elem_types.size()});
  359. for (auto [i, src_type_inst_id, dest_type_inst_id] : llvm::enumerate(
  360. context.types().GetBlockAsTypeInstIds(src_elem_types),
  361. context.types().GetBlockAsTypeInstIds(dest_elem_types))) {
  362. // TODO: This call recurses back into conversion. Switch to an iterative
  363. // approach.
  364. auto init_id =
  365. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  366. context, value_loc_id, value_id, src_type_inst_id, literal_elems,
  367. inner_kind, target.storage_id, dest_type_inst_id,
  368. target.storage_access_block, i, i);
  369. if (init_id == SemIR::ErrorInst::InstId) {
  370. return SemIR::ErrorInst::InstId;
  371. }
  372. new_block.Set(i, init_id);
  373. }
  374. if (target.is_initializer()) {
  375. target.storage_access_block->InsertHere();
  376. return AddInst<SemIR::TupleInit>(context, value_loc_id,
  377. {.type_id = target.type_id,
  378. .elements_id = new_block.id(),
  379. .dest_id = target.storage_id});
  380. } else {
  381. return AddInst<SemIR::TupleValue>(
  382. context, value_loc_id,
  383. {.type_id = target.type_id, .elements_id = new_block.id()});
  384. }
  385. }
  386. // Converts a tuple of elements that are convertible to `type` into a `type`
  387. // that is a tuple of types.
  388. static auto ConvertTupleToType(Context& context, SemIR::LocId loc_id,
  389. SemIR::InstId value_id,
  390. SemIR::TypeId value_type_id,
  391. ConversionTarget target) -> SemIR::TypeInstId {
  392. auto value_const_id = context.constant_values().Get(value_id);
  393. if (!value_const_id.is_constant()) {
  394. // Types are constants. The input value must have a constant value to
  395. // convert.
  396. return SemIR::TypeInstId::None;
  397. }
  398. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  399. auto value_const_inst_id =
  400. context.constant_values().GetInstId(value_const_id);
  401. if (auto tuple_value =
  402. context.insts().TryGetAs<SemIR::TupleValue>(value_const_inst_id)) {
  403. for (auto tuple_inst_id :
  404. context.inst_blocks().Get(tuple_value->elements_id)) {
  405. // TODO: This call recurses back into conversion. Switch to an
  406. // iterative approach.
  407. type_inst_ids.push_back(
  408. ExprAsType(context, loc_id, tuple_inst_id, target.diagnose).inst_id);
  409. }
  410. } else {
  411. // A value of type TupleType that isn't a TupleValue must be a symbolic
  412. // binding.
  413. CARBON_CHECK(
  414. context.insts().Is<SemIR::SymbolicBinding>(value_const_inst_id));
  415. // Form a TupleAccess for each element in the symbolic value, which is then
  416. // converted to a `type` or diagnosed as an error.
  417. auto tuple_type = context.types().GetAs<SemIR::TupleType>(value_type_id);
  418. auto type_elements = context.types().GetBlockAsTypeIds(
  419. context.inst_blocks().Get(tuple_type.type_elements_id));
  420. for (auto [i, type_id] : llvm::enumerate(type_elements)) {
  421. auto access_inst_id =
  422. GetOrAddInst<SemIR::TupleAccess>(context, loc_id,
  423. {.type_id = type_id,
  424. .tuple_id = value_id,
  425. .index = SemIR::ElementIndex(i)});
  426. // TODO: This call recurses back into conversion. Switch to an
  427. // iterative approach.
  428. type_inst_ids.push_back(
  429. ExprAsType(context, loc_id, access_inst_id, target.diagnose).inst_id);
  430. }
  431. }
  432. // TODO: Should we add this as an instruction? It will contain
  433. // references to local InstIds.
  434. auto tuple_type_id = GetTupleType(context, type_inst_ids);
  435. return context.types().GetTypeInstId(tuple_type_id);
  436. }
  437. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  438. template <typename TargetAccessInstT>
  439. static auto ConvertStructToStructOrClass(
  440. Context& context, SemIR::StructType src_type, SemIR::StructType dest_type,
  441. SemIR::InstId value_id, ConversionTarget target,
  442. SemIR::ClassType* vtable_class_type = nullptr) -> SemIR::InstId {
  443. static_assert(std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT> ||
  444. std::is_same_v<SemIR::StructAccess, TargetAccessInstT>);
  445. constexpr bool ToClass =
  446. std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT>;
  447. auto& sem_ir = context.sem_ir();
  448. auto src_elem_fields = sem_ir.struct_type_fields().Get(src_type.fields_id);
  449. auto dest_elem_fields = sem_ir.struct_type_fields().Get(dest_type.fields_id);
  450. bool dest_has_vptr = !dest_elem_fields.empty() &&
  451. dest_elem_fields.front().name_id == SemIR::NameId::Vptr;
  452. int dest_vptr_offset = (dest_has_vptr ? 1 : 0);
  453. auto dest_elem_fields_size = dest_elem_fields.size() - dest_vptr_offset;
  454. auto value = sem_ir.insts().Get(value_id);
  455. SemIR::LocId value_loc_id(value_id);
  456. // If we're initializing from a struct literal, we will use its elements
  457. // directly. Otherwise, materialize a temporary if needed and index into the
  458. // result.
  459. llvm::ArrayRef<SemIR::InstId> literal_elems;
  460. auto literal_elems_id = SemIR::InstBlockId::None;
  461. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  462. literal_elems_id = struct_literal->elements_id;
  463. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  464. } else {
  465. value_id = MaterializeIfInitializer(context, value_id);
  466. }
  467. // Check that the structs are the same size.
  468. // TODO: If not, include the name of the first source field that doesn't
  469. // exist in the destination or vice versa in the diagnostic.
  470. if (src_elem_fields.size() != dest_elem_fields_size) {
  471. if (target.diagnose) {
  472. CARBON_DIAGNOSTIC(
  473. StructInitElementCountMismatch, Error,
  474. "cannot initialize {0:class|struct} with {1} field{1:s} from struct "
  475. "with {2} field{2:s}",
  476. Diagnostics::BoolAsSelect, Diagnostics::IntAsSelect,
  477. Diagnostics::IntAsSelect);
  478. context.emitter().Emit(value_loc_id, StructInitElementCountMismatch,
  479. ToClass, dest_elem_fields_size,
  480. src_elem_fields.size());
  481. }
  482. return SemIR::ErrorInst::InstId;
  483. }
  484. // Prepare to look up fields in the source by index.
  485. Map<SemIR::NameId, int32_t> src_field_indexes;
  486. if (src_type.fields_id != dest_type.fields_id) {
  487. for (auto [i, field] : llvm::enumerate(src_elem_fields)) {
  488. auto result = src_field_indexes.Insert(field.name_id, i);
  489. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  490. }
  491. }
  492. ConversionTarget::Kind inner_kind =
  493. GetAggregateElementConversionTargetKind(sem_ir, target);
  494. // Initialize each element of the destination from the corresponding element
  495. // of the source.
  496. // TODO: Annotate diagnostics coming from here with the element index.
  497. auto new_block =
  498. literal_elems_id.has_value() && !dest_has_vptr
  499. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  500. : SemIR::CopyOnWriteInstBlock(
  501. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  502. dest_elem_fields.size()});
  503. for (auto [i, dest_field] : llvm::enumerate(dest_elem_fields)) {
  504. if (dest_field.name_id == SemIR::NameId::Vptr) {
  505. if constexpr (!ToClass) {
  506. CARBON_FATAL("Only classes should have vptrs.");
  507. }
  508. target.storage_access_block->InsertHere();
  509. auto vptr_type_id =
  510. context.types().GetTypeIdForTypeInstId(dest_field.type_inst_id);
  511. auto dest_id =
  512. AddInst<SemIR::ClassElementAccess>(context, value_loc_id,
  513. {.type_id = vptr_type_id,
  514. .base_id = target.storage_id,
  515. .index = SemIR::ElementIndex(i)});
  516. auto vtable_decl_id =
  517. context.classes().Get(vtable_class_type->class_id).vtable_decl_id;
  518. LoadImportRef(context, vtable_decl_id);
  519. auto canonical_vtable_decl_id =
  520. context.constant_values().GetConstantInstId(vtable_decl_id);
  521. auto vtable_ptr_id = AddInst<SemIR::VtablePtr>(
  522. context, value_loc_id,
  523. {.type_id = GetPointerType(context, SemIR::VtableType::TypeInstId),
  524. .vtable_id = context.insts()
  525. .GetAs<SemIR::VtableDecl>(canonical_vtable_decl_id)
  526. .vtable_id,
  527. .specific_id = vtable_class_type->specific_id});
  528. auto init_id = AddInst<SemIR::InPlaceInit>(context, value_loc_id,
  529. {.type_id = vptr_type_id,
  530. .src_id = vtable_ptr_id,
  531. .dest_id = dest_id});
  532. new_block.Set(i, init_id);
  533. continue;
  534. }
  535. // Find the matching source field.
  536. auto src_field_index = i;
  537. if (src_type.fields_id != dest_type.fields_id) {
  538. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  539. src_field_index = lookup.value();
  540. } else {
  541. if (target.diagnose) {
  542. if (literal_elems_id.has_value()) {
  543. CARBON_DIAGNOSTIC(
  544. StructInitMissingFieldInLiteral, Error,
  545. "missing value for field `{0}` in struct initialization",
  546. SemIR::NameId);
  547. context.emitter().Emit(value_loc_id,
  548. StructInitMissingFieldInLiteral,
  549. dest_field.name_id);
  550. } else {
  551. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  552. "cannot convert from struct type {0} to {1}: "
  553. "missing field `{2}` in source type",
  554. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  555. context.emitter().Emit(value_loc_id,
  556. StructInitMissingFieldInConversion, value_id,
  557. target.type_id, dest_field.name_id);
  558. }
  559. }
  560. return SemIR::ErrorInst::InstId;
  561. }
  562. }
  563. auto src_field = src_elem_fields[src_field_index];
  564. // TODO: This call recurses back into conversion. Switch to an iterative
  565. // approach.
  566. auto init_id =
  567. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  568. context, value_loc_id, value_id, src_field.type_inst_id,
  569. literal_elems, inner_kind, target.storage_id,
  570. dest_field.type_inst_id, target.storage_access_block,
  571. src_field_index, src_field_index + dest_vptr_offset,
  572. vtable_class_type);
  573. if (init_id == SemIR::ErrorInst::InstId) {
  574. return SemIR::ErrorInst::InstId;
  575. }
  576. new_block.Set(i, init_id);
  577. }
  578. bool is_init = target.is_initializer();
  579. if (ToClass) {
  580. target.storage_access_block->InsertHere();
  581. CARBON_CHECK(is_init,
  582. "Converting directly to a class value is not supported");
  583. return AddInst<SemIR::ClassInit>(context, value_loc_id,
  584. {.type_id = target.type_id,
  585. .elements_id = new_block.id(),
  586. .dest_id = target.storage_id});
  587. } else if (is_init) {
  588. target.storage_access_block->InsertHere();
  589. return AddInst<SemIR::StructInit>(context, value_loc_id,
  590. {.type_id = target.type_id,
  591. .elements_id = new_block.id(),
  592. .dest_id = target.storage_id});
  593. } else {
  594. return AddInst<SemIR::StructValue>(
  595. context, value_loc_id,
  596. {.type_id = target.type_id, .elements_id = new_block.id()});
  597. }
  598. }
  599. // Performs a conversion from a struct to a struct type. This function only
  600. // converts the type, and does not perform a final conversion to the requested
  601. // expression category.
  602. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  603. SemIR::StructType dest_type,
  604. SemIR::InstId value_id,
  605. ConversionTarget target) -> SemIR::InstId {
  606. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  607. context, src_type, dest_type, value_id, target);
  608. }
  609. // Performs a conversion from a struct to a class type. This function only
  610. // converts the type, and does not perform a final conversion to the requested
  611. // expression category.
  612. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  613. SemIR::ClassType dest_type,
  614. SemIR::InstId value_id,
  615. ConversionTarget target,
  616. SemIR::ClassType* vtable_class_type)
  617. -> SemIR::InstId {
  618. PendingBlock target_block(&context);
  619. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  620. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  621. auto object_repr_id =
  622. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  623. if (object_repr_id == SemIR::ErrorInst::TypeId) {
  624. return SemIR::ErrorInst::InstId;
  625. }
  626. if (context.types().Is<SemIR::CustomLayoutType>(object_repr_id)) {
  627. // Builtin conversion does not apply.
  628. return value_id;
  629. }
  630. auto dest_struct_type =
  631. context.types().GetAs<SemIR::StructType>(object_repr_id);
  632. // If we're trying to create a class value, form a temporary for the value to
  633. // point to.
  634. bool need_temporary = !target.is_initializer();
  635. if (need_temporary) {
  636. target.kind = ConversionTarget::Initializing;
  637. target.storage_access_block = &target_block;
  638. target.storage_id = target_block.AddInst<SemIR::TemporaryStorage>(
  639. SemIR::LocId(value_id), {.type_id = target.type_id});
  640. }
  641. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  642. context, src_type, dest_struct_type, value_id, target,
  643. vtable_class_type ? vtable_class_type : &dest_type);
  644. if (need_temporary) {
  645. target_block.InsertHere();
  646. result_id =
  647. AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(value_id),
  648. {.type_id = target.type_id,
  649. .storage_id = target.storage_id,
  650. .init_id = result_id});
  651. }
  652. return result_id;
  653. }
  654. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  655. // in order from derived to base.
  656. using InheritancePath =
  657. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  658. // Computes the inheritance path from class `derived_id` to class `base_id`.
  659. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  660. static auto ComputeInheritancePath(Context& context, SemIR::LocId loc_id,
  661. SemIR::TypeId derived_id,
  662. SemIR::TypeId base_id)
  663. -> std::optional<InheritancePath> {
  664. // We intend for NRVO to be applied to `result`. All `return` statements in
  665. // this function should `return result;`.
  666. std::optional<InheritancePath> result(std::in_place);
  667. if (!TryToCompleteType(context, derived_id, loc_id)) {
  668. // TODO: Should we give an error here? If we don't, and there is an
  669. // inheritance path when the class is defined, we may have a coherence
  670. // problem.
  671. result = std::nullopt;
  672. return result;
  673. }
  674. while (derived_id != base_id) {
  675. auto derived_class_type =
  676. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  677. if (!derived_class_type) {
  678. result = std::nullopt;
  679. break;
  680. }
  681. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  682. auto base_type_id = derived_class.GetBaseType(
  683. context.sem_ir(), derived_class_type->specific_id);
  684. if (!base_type_id.has_value()) {
  685. result = std::nullopt;
  686. break;
  687. }
  688. result->push_back({derived_class.base_id, base_type_id});
  689. derived_id = base_type_id;
  690. }
  691. return result;
  692. }
  693. // Performs a conversion from a derived class value or reference to a base class
  694. // value or reference.
  695. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  696. SemIR::InstId value_id,
  697. const InheritancePath& path) -> SemIR::InstId {
  698. // Materialize a temporary if necessary.
  699. value_id = ConvertToValueOrRefExpr(context, value_id);
  700. // Preserve type qualifiers.
  701. auto quals = context.types()
  702. .GetUnqualifiedTypeAndQualifiers(
  703. context.insts().Get(value_id).type_id())
  704. .second;
  705. // Add a series of `.base` accesses.
  706. for (auto [base_id, base_type_id] : path) {
  707. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  708. value_id = AddInst<SemIR::ClassElementAccess>(
  709. context, loc_id,
  710. {.type_id = GetQualifiedType(context, base_type_id, quals),
  711. .base_id = value_id,
  712. .index = base_decl.index});
  713. }
  714. return value_id;
  715. }
  716. // Performs a conversion from a derived class pointer to a base class pointer.
  717. static auto ConvertDerivedPointerToBasePointer(
  718. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  719. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  720. const InheritancePath& path) -> SemIR::InstId {
  721. auto pointee_type_id =
  722. context.types().GetTypeIdForTypeInstId(src_ptr_type.pointee_id);
  723. // Form `*p`.
  724. ptr_id = ConvertToValueExpr(context, ptr_id);
  725. auto ref_id = AddInst<SemIR::Deref>(
  726. context, loc_id, {.type_id = pointee_type_id, .pointer_id = ptr_id});
  727. // Convert as a reference expression.
  728. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  729. // Take the address.
  730. return AddInst<SemIR::AddrOf>(
  731. context, loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  732. }
  733. // Returns whether `category` is a valid expression category to produce as a
  734. // result of a conversion with kind `target_kind`.
  735. static auto IsValidExprCategoryForConversionTarget(
  736. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  737. switch (target_kind) {
  738. case ConversionTarget::Value:
  739. return category == SemIR::ExprCategory::Value;
  740. case ConversionTarget::ValueOrRef:
  741. return category == SemIR::ExprCategory::Value ||
  742. category == SemIR::ExprCategory::DurableRef ||
  743. category == SemIR::ExprCategory::EphemeralRef;
  744. case ConversionTarget::Discarded:
  745. return category == SemIR::ExprCategory::Value ||
  746. category == SemIR::ExprCategory::DurableRef ||
  747. category == SemIR::ExprCategory::EphemeralRef ||
  748. category == SemIR::ExprCategory::ReprInitializing ||
  749. category == SemIR::ExprCategory::InPlaceInitializing;
  750. case ConversionTarget::RefParam:
  751. case ConversionTarget::UnmarkedRefParam:
  752. return category == SemIR::ExprCategory::DurableRef ||
  753. category == SemIR::ExprCategory::EphemeralRef;
  754. case ConversionTarget::DurableRef:
  755. return category == SemIR::ExprCategory::DurableRef;
  756. case ConversionTarget::CppThunkRef:
  757. return category == SemIR::ExprCategory::EphemeralRef;
  758. case ConversionTarget::ExplicitAs:
  759. case ConversionTarget::ExplicitUnsafeAs:
  760. return true;
  761. case ConversionTarget::InPlaceInitializing:
  762. return category == SemIR::ExprCategory::InPlaceInitializing;
  763. case ConversionTarget::Initializing:
  764. return category == SemIR::ExprCategory::ReprInitializing;
  765. }
  766. }
  767. // Determines whether the initialization representation of the type is a copy of
  768. // the value representation.
  769. static auto InitReprIsCopyOfValueRepr(const SemIR::File& sem_ir,
  770. SemIR::TypeId type_id) -> bool {
  771. // The initializing representation is a copy of the value representation if
  772. // they're both copies of the object representation.
  773. return SemIR::InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  774. SemIR::ValueRepr::ForType(sem_ir, type_id)
  775. .IsCopyOfObjectRepr(sem_ir, type_id);
  776. }
  777. // Determines whether we can pull a value directly out of an initializing
  778. // expression of type `type_id` to initialize a target of type `type_id` and
  779. // kind `target_kind`.
  780. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  781. SemIR::TypeId type_id,
  782. ConversionTarget::Kind target_kind)
  783. -> bool {
  784. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  785. target_kind)) {
  786. // We don't want a value expression.
  787. return false;
  788. }
  789. // We can pull a value out of an initializing expression if it holds one.
  790. return InitReprIsCopyOfValueRepr(sem_ir, type_id);
  791. }
  792. // Determine whether the given set of qualifiers can be added by a conversion
  793. // of an expression of the given category.
  794. static auto CanAddQualifiers(SemIR::TypeQualifiers quals,
  795. SemIR::ExprCategory cat) -> bool {
  796. if (quals.HasAnyOf(SemIR::TypeQualifiers::MaybeUnformed) &&
  797. !SemIR::IsRefCategory(cat)) {
  798. // `MaybeUnformed(T)` may have a different value representation or
  799. // initializing representation from `T`, so only allow it to be added for a
  800. // reference expression.
  801. // TODO: We should allow converting an initializing expression of type `T`
  802. // to `MaybeUnformed(T)`. `PerformBuiltinConversion` will need to generate
  803. // an `InPlaceInit` instruction when needed.
  804. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  805. return false;
  806. }
  807. // `const` and `partial` can always be added.
  808. return true;
  809. }
  810. // Determine whether the given set of qualifiers can be removed by a conversion
  811. // of an expression of the given category.
  812. static auto CanRemoveQualifiers(SemIR::TypeQualifiers quals,
  813. SemIR::ExprCategory cat,
  814. ConversionTarget::Kind kind) -> bool {
  815. bool allow_unsafe = kind == ConversionTarget::ExplicitUnsafeAs;
  816. if (quals.HasAnyOf(SemIR::TypeQualifiers::Const) && !allow_unsafe &&
  817. SemIR::IsRefCategory(cat) &&
  818. IsValidExprCategoryForConversionTarget(cat, kind)) {
  819. // Removing `const` is an unsafe conversion for a reference expression. But
  820. // it's OK if we will be converting to a different category as part of this
  821. // overall conversion anyway.
  822. return false;
  823. }
  824. if (quals.HasAnyOf(SemIR::TypeQualifiers::Partial) &&
  825. (!allow_unsafe || SemIR::IsInitializerCategory(cat))) {
  826. // TODO: Allow removing `partial` for initializing expressions as a safe
  827. // conversion. `PerformBuiltinConversion` will need to initialize the vptr
  828. // as part of the conversion.
  829. return false;
  830. }
  831. if (quals.HasAnyOf(SemIR::TypeQualifiers::MaybeUnformed) &&
  832. (!allow_unsafe || SemIR::IsInitializerCategory(cat))) {
  833. // As an unsafe conversion, `MaybeUnformed` can be removed from a value or
  834. // reference expression.
  835. return false;
  836. }
  837. return true;
  838. }
  839. static auto DiagnoseConversionFailureToConstraintValue(
  840. Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  841. SemIR::TypeId target_type_id) -> void {
  842. CARBON_CHECK(context.types().IsFacetType(target_type_id));
  843. // If the source type is/has a facet value (converted with `as type` or
  844. // otherwise), then we can include its `FacetType` in the diagnostic to help
  845. // explain what interfaces the source type implements.
  846. auto const_expr_id = GetCanonicalFacetOrTypeValue(context, expr_id);
  847. auto const_expr_type_id = context.insts().Get(const_expr_id).type_id();
  848. if (context.types().Is<SemIR::FacetType>(const_expr_type_id)) {
  849. CARBON_DIAGNOSTIC(ConversionFailureFacetToFacet, Error,
  850. "cannot convert type {0} that implements {1} into type "
  851. "implementing {2}",
  852. InstIdAsType, SemIR::TypeId, SemIR::TypeId);
  853. context.emitter().Emit(loc_id, ConversionFailureFacetToFacet, expr_id,
  854. const_expr_type_id, target_type_id);
  855. } else {
  856. CARBON_DIAGNOSTIC(ConversionFailureTypeToFacet, Error,
  857. "cannot convert type {0} into type implementing {1}",
  858. InstIdAsType, SemIR::TypeId);
  859. context.emitter().Emit(loc_id, ConversionFailureTypeToFacet, expr_id,
  860. target_type_id);
  861. }
  862. }
  863. static auto PerformBuiltinConversion(
  864. Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  865. ConversionTarget target, SemIR::ClassType* vtable_class_type = nullptr)
  866. -> SemIR::InstId {
  867. auto& sem_ir = context.sem_ir();
  868. auto value = sem_ir.insts().Get(value_id);
  869. auto value_type_id = value.type_id();
  870. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  871. // Various forms of implicit conversion are supported as builtin conversions,
  872. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  873. // prelude. There are a few reasons we need to perform some of these
  874. // conversions as builtins:
  875. //
  876. // 1) Conversions from struct and tuple *literals* have special rules that
  877. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  878. // recurse into the elements of the literal before performing
  879. // initialization in order to avoid unnecessary conversions between
  880. // expression categories that would be performed by `ImplicitAs.Convert`.
  881. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  882. // the value of the facet, not only its type, and therefore cannot be
  883. // modeled by `ImplicitAs`.
  884. // 3) Some of these conversions are used while checking the library
  885. // definition of `ImplicitAs` itself or implementations of it.
  886. //
  887. // We also expect to see better performance by avoiding an `impl` lookup for
  888. // common conversions.
  889. //
  890. // TODO: We should provide a debugging flag to turn off as many of these
  891. // builtin conversions as we can so that we can test that they do the same
  892. // thing as the library implementations.
  893. //
  894. // The builtin conversions that correspond to `impl`s in the library all
  895. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  896. // being specialized in any of these cases.
  897. // If the value is already of the right kind and expression category, there's
  898. // nothing to do. Performing a conversion would decompose and rebuild tuples
  899. // and structs, so it's important that we bail out early in this case.
  900. if (value_type_id == target.type_id) {
  901. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  902. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  903. return value_id;
  904. }
  905. // If the source is an initializing expression, we may be able to pull a
  906. // value right out of it.
  907. if (value_cat == SemIR::ExprCategory::ReprInitializing &&
  908. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  909. return AddInst<SemIR::ValueOfInitializer>(
  910. context, loc_id, {.type_id = value_type_id, .init_id = value_id});
  911. }
  912. // Materialization is handled as part of the enclosing conversion.
  913. if (SemIR::IsInitializerCategory(value_cat) &&
  914. target.kind == ConversionTarget::ValueOrRef) {
  915. return value_id;
  916. }
  917. // Final destination store is handled as part of the enclosing conversion.
  918. if (value_cat == SemIR::ExprCategory::ReprInitializing &&
  919. target.kind == ConversionTarget::InPlaceInitializing) {
  920. return value_id;
  921. }
  922. // PerformBuiltinConversion converts each part of a tuple or struct, even
  923. // when the types are the same. This is not done for classes since they have
  924. // to define their conversions as part of their api.
  925. //
  926. // If a class adapts a tuple or struct, we convert each of its parts when
  927. // there's no other conversion going on (the source and target types are the
  928. // same). To do so, we have to insert a conversion of the value up to the
  929. // foundation and back down, and a conversion of the initializing object if
  930. // there is one.
  931. //
  932. // Implementation note: We do the conversion through a call to
  933. // PerformBuiltinConversion() call rather than a Convert() call to avoid
  934. // extraneous `converted` semir instructions on the adapted types, and as a
  935. // shortcut to doing the explicit calls to walk the parts of the
  936. // tuple/struct which happens inside PerformBuiltinConversion().
  937. if (auto foundation_type_id =
  938. context.types().GetTransitiveAdaptedType(value_type_id);
  939. foundation_type_id != value_type_id &&
  940. context.types().IsOneOf<SemIR::StructType, SemIR::TupleType>(
  941. foundation_type_id)) {
  942. auto foundation_value_id = AddInst<SemIR::AsCompatible>(
  943. context, loc_id,
  944. {.type_id = foundation_type_id, .source_id = value_id});
  945. auto foundation_init_id = target.storage_id;
  946. if (foundation_init_id != SemIR::InstId::None) {
  947. foundation_init_id =
  948. target.storage_access_block->AddInst<SemIR::AsCompatible>(
  949. loc_id, {.type_id = foundation_type_id,
  950. .source_id = target.storage_id});
  951. }
  952. {
  953. // While the types are the same, the conversion can still fail if it
  954. // performs a copy while converting the value to another category, and
  955. // the type (or some part of it) is not copyable.
  956. Diagnostics::AnnotationScope annotate_diagnostics(
  957. &context.emitter(), [&](auto& builder) {
  958. CARBON_DIAGNOSTIC(InCopy, Note, "in copy of {0}", TypeOfInstId);
  959. builder.Note(value_id, InCopy, value_id);
  960. });
  961. foundation_value_id = PerformBuiltinConversion(
  962. context, loc_id, foundation_value_id,
  963. {.kind = target.kind,
  964. .type_id = foundation_type_id,
  965. .storage_id = foundation_init_id,
  966. .storage_access_block = target.storage_access_block,
  967. .diagnose = target.diagnose});
  968. if (foundation_value_id == SemIR::ErrorInst::InstId) {
  969. return SemIR::ErrorInst::InstId;
  970. }
  971. }
  972. return AddInst<SemIR::AsCompatible>(
  973. context, loc_id,
  974. {.type_id = target.type_id, .source_id = foundation_value_id});
  975. }
  976. }
  977. // T implicitly converts to U if T and U are the same ignoring qualifiers, and
  978. // we're allowed to remove / add any qualifiers that differ. Similarly, T
  979. // explicitly converts to U if T is compatible with U, and we're allowed to
  980. // remove / add any qualifiers that differ.
  981. if (target.type_id != value_type_id) {
  982. auto [target_foundation_id, target_quals] =
  983. target.is_explicit_as()
  984. ? context.types().GetTransitiveUnqualifiedAdaptedType(
  985. target.type_id)
  986. : context.types().GetUnqualifiedTypeAndQualifiers(target.type_id);
  987. auto [value_foundation_id, value_quals] =
  988. target.is_explicit_as()
  989. ? context.types().GetTransitiveUnqualifiedAdaptedType(value_type_id)
  990. : context.types().GetUnqualifiedTypeAndQualifiers(value_type_id);
  991. if (target_foundation_id == value_foundation_id) {
  992. auto category = SemIR::GetExprCategory(context.sem_ir(), value_id);
  993. auto added_quals = target_quals & ~value_quals;
  994. auto removed_quals = value_quals & ~target_quals;
  995. if (CanAddQualifiers(added_quals, category) &&
  996. CanRemoveQualifiers(removed_quals, category, target.kind)) {
  997. // For a struct or tuple literal, perform a category conversion if
  998. // necessary.
  999. if (category == SemIR::ExprCategory::Mixed) {
  1000. value_id = PerformBuiltinConversion(context, loc_id, value_id,
  1001. {.kind = ConversionTarget::Value,
  1002. .type_id = value_type_id,
  1003. .diagnose = target.diagnose});
  1004. }
  1005. // `MaybeUnformed(T)` might have a pointer value representation when `T`
  1006. // does not, so convert as needed when removing `MaybeUnformed`.
  1007. bool need_value_binding = false;
  1008. if ((removed_quals & SemIR::TypeQualifiers::MaybeUnformed) !=
  1009. SemIR::TypeQualifiers::None &&
  1010. category == SemIR::ExprCategory::Value) {
  1011. auto value_rep =
  1012. SemIR::ValueRepr::ForType(context.sem_ir(), value_type_id);
  1013. auto unformed_value_rep =
  1014. SemIR::ValueRepr::ForType(context.sem_ir(), target.type_id);
  1015. if (value_rep.kind != unformed_value_rep.kind) {
  1016. CARBON_CHECK(unformed_value_rep.kind == SemIR::ValueRepr::Pointer);
  1017. value_id = AddInst<SemIR::ValueAsRef>(
  1018. context, loc_id,
  1019. {.type_id = value_type_id, .value_id = value_id});
  1020. need_value_binding = true;
  1021. }
  1022. }
  1023. value_id = AddInst<SemIR::AsCompatible>(
  1024. context, loc_id,
  1025. {.type_id = target.type_id, .source_id = value_id});
  1026. if (need_value_binding) {
  1027. value_id = AddInst<SemIR::AcquireValue>(
  1028. context, loc_id,
  1029. {.type_id = target.type_id, .value_id = value_id});
  1030. }
  1031. return value_id;
  1032. } else {
  1033. // TODO: Produce a custom diagnostic explaining that we can't perform
  1034. // this conversion due to the change in qualifiers and/or the expression
  1035. // category.
  1036. }
  1037. }
  1038. }
  1039. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  1040. // converts to Ui.
  1041. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  1042. if (auto src_tuple_type =
  1043. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  1044. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  1045. value_id, target);
  1046. }
  1047. }
  1048. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  1049. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  1050. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  1051. // to Ui.
  1052. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  1053. if (auto src_struct_type =
  1054. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1055. return ConvertStructToStruct(context, *src_struct_type,
  1056. *target_struct_type, value_id, target);
  1057. }
  1058. }
  1059. // No other conversions apply when the source and destination types are the
  1060. // same.
  1061. if (value_type_id == target.type_id) {
  1062. return value_id;
  1063. }
  1064. // A tuple (T1, T2, ..., Tn) converts to array(T, n) if each Ti converts to T.
  1065. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  1066. if (auto src_tuple_type =
  1067. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  1068. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  1069. value_id, target);
  1070. }
  1071. }
  1072. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  1073. // if it converts to the struct type that is the class's representation type
  1074. // (a struct with the same fields as the class, plus a base field where
  1075. // relevant).
  1076. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  1077. if (auto src_struct_type =
  1078. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1079. if (!context.classes()
  1080. .Get(target_class_type->class_id)
  1081. .adapt_id.has_value()) {
  1082. return ConvertStructToClass(context, *src_struct_type,
  1083. *target_class_type, value_id, target,
  1084. vtable_class_type);
  1085. }
  1086. }
  1087. // An expression of type T converts to U if T is a class derived from U.
  1088. //
  1089. // TODO: Combine this with the qualifiers and adapter conversion logic above
  1090. // to allow qualifiers and inheritance conversions to be performed together.
  1091. if (auto path = ComputeInheritancePath(context, loc_id, value_type_id,
  1092. target.type_id);
  1093. path && !path->empty()) {
  1094. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  1095. }
  1096. }
  1097. // A pointer T* converts to [qualified] U* if T is the same as U, or is a
  1098. // class derived from U.
  1099. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  1100. if (auto src_pointer_type =
  1101. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  1102. auto target_pointee_id = context.types().GetTypeIdForTypeInstId(
  1103. target_pointer_type->pointee_id);
  1104. auto src_pointee_id =
  1105. context.types().GetTypeIdForTypeInstId(src_pointer_type->pointee_id);
  1106. // Try to complete the pointee types so that we can walk through adapters
  1107. // to their adapted types.
  1108. TryToCompleteType(context, target_pointee_id, loc_id);
  1109. TryToCompleteType(context, src_pointee_id, loc_id);
  1110. auto [unqual_target_pointee_type_id, target_quals] =
  1111. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(target_pointee_id);
  1112. auto [unqual_src_pointee_type_id, src_quals] =
  1113. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(src_pointee_id);
  1114. // If the qualifiers are incompatible, we can't perform a conversion,
  1115. // except with `unsafe as`.
  1116. if ((src_quals & ~target_quals) != SemIR::TypeQualifiers::None &&
  1117. target.kind != ConversionTarget::ExplicitUnsafeAs) {
  1118. // TODO: Consider producing a custom diagnostic here for a cast that
  1119. // discards constness.
  1120. return value_id;
  1121. }
  1122. if (unqual_target_pointee_type_id != unqual_src_pointee_type_id) {
  1123. // If there's an inheritance path from target to source, this is a
  1124. // derived to base conversion.
  1125. if (auto path = ComputeInheritancePath(context, loc_id,
  1126. unqual_src_pointee_type_id,
  1127. unqual_target_pointee_type_id);
  1128. path && !path->empty()) {
  1129. value_id = ConvertDerivedPointerToBasePointer(
  1130. context, loc_id, *src_pointer_type, target.type_id, value_id,
  1131. *path);
  1132. } else {
  1133. // No conversion was possible.
  1134. return value_id;
  1135. }
  1136. }
  1137. // Perform a compatible conversion to add any new qualifiers.
  1138. if (src_quals != target_quals) {
  1139. return AddInst<SemIR::AsCompatible>(
  1140. context, loc_id,
  1141. {.type_id = target.type_id, .source_id = value_id});
  1142. }
  1143. return value_id;
  1144. }
  1145. }
  1146. if (sem_ir.types().IsFacetType(target.type_id)) {
  1147. auto type_value_id = SemIR::TypeInstId::None;
  1148. // A tuple of types converts to type `type`.
  1149. if (sem_ir.types().Is<SemIR::TupleType>(value_type_id)) {
  1150. type_value_id =
  1151. ConvertTupleToType(context, loc_id, value_id, value_type_id, target);
  1152. }
  1153. // `{}` converts to `{} as type`.
  1154. if (auto struct_type =
  1155. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1156. if (struct_type->fields_id == SemIR::StructTypeFieldsId::Empty) {
  1157. type_value_id = sem_ir.types().GetTypeInstId(value_type_id);
  1158. }
  1159. }
  1160. if (type_value_id != SemIR::InstId::None) {
  1161. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1162. // Use the converted `TypeType` value for converting to a facet.
  1163. value_id = type_value_id;
  1164. value_type_id = SemIR::TypeType::TypeId;
  1165. } else {
  1166. // We wanted a `TypeType`, and we've done that.
  1167. return type_value_id;
  1168. }
  1169. }
  1170. }
  1171. // FacetType converts to Type by wrapping the facet value in
  1172. // FacetAccessType.
  1173. if (target.type_id == SemIR::TypeType::TypeId &&
  1174. sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1175. return AddInst<SemIR::FacetAccessType>(
  1176. context, loc_id,
  1177. {.type_id = target.type_id, .facet_value_inst_id = value_id});
  1178. }
  1179. // Type values can convert to facet values, and facet values can convert to
  1180. // other facet values, as long as they satisfy the required interfaces of the
  1181. // target `FacetType`.
  1182. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id) &&
  1183. sem_ir.types().IsOneOf<SemIR::TypeType, SemIR::FacetType>(
  1184. value_type_id)) {
  1185. // TODO: Runtime facet values should be allowed to convert based on their
  1186. // FacetTypes, but we assume constant values for impl lookup at the moment.
  1187. if (!context.constant_values().Get(value_id).is_constant()) {
  1188. context.TODO(loc_id, "conversion of runtime facet value");
  1189. return SemIR::ErrorInst::InstId;
  1190. }
  1191. // Get the canonical type for which we want to attach a new set of witnesses
  1192. // to match the requirements of the target FacetType.
  1193. auto type_inst_id = SemIR::TypeInstId::None;
  1194. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1195. type_inst_id = AddTypeInst<SemIR::FacetAccessType>(
  1196. context, loc_id,
  1197. {.type_id = SemIR::TypeType::TypeId,
  1198. .facet_value_inst_id = value_id});
  1199. } else {
  1200. type_inst_id = context.types().GetAsTypeInstId(value_id);
  1201. // Shortcut for lossless round trips through a FacetAccessType (which
  1202. // evaluates to SymbolicBindingType when wrapping a symbolic binding) when
  1203. // converting back to the type of the original symbolic binding facet
  1204. // value.
  1205. //
  1206. // In the case where the FacetAccessType wraps a SymbolicBinding with the
  1207. // exact facet type that we are converting to, the resulting FacetValue
  1208. // would evaluate back to the original SymbolicBinding as its canonical
  1209. // form. We can skip past the whole impl lookup step then and do that
  1210. // here.
  1211. //
  1212. // TODO: This instruction is going to become a `SymbolicBindingType`, so
  1213. // we'll need to handle that instead.
  1214. auto facet_value_inst_id =
  1215. GetCanonicalFacetOrTypeValue(context, type_inst_id);
  1216. if (sem_ir.insts().Get(facet_value_inst_id).type_id() == target.type_id) {
  1217. return facet_value_inst_id;
  1218. }
  1219. }
  1220. // Conversion from a facet value (which has type `FacetType`) or a type
  1221. // value (which has type `TypeType`) to a facet value. We can do this if the
  1222. // type satisfies the requirements of the target `FacetType`, as determined
  1223. // by finding impl witnesses for the target FacetType.
  1224. auto lookup_result = LookupImplWitness(
  1225. context, loc_id, sem_ir.constant_values().Get(type_inst_id),
  1226. sem_ir.types().GetConstantId(target.type_id));
  1227. if (lookup_result.has_value()) {
  1228. if (lookup_result.has_error_value()) {
  1229. return SemIR::ErrorInst::InstId;
  1230. } else {
  1231. // Note that `FacetValue`'s type is the same `FacetType` that was used
  1232. // to construct the set of witnesses, ie. the query to
  1233. // `LookupImplWitness()`. This ensures that the witnesses are in the
  1234. // same order as the `required_impls()` in the `IdentifiedFacetType` of
  1235. // the `FacetValue`'s type.
  1236. return AddInst<SemIR::FacetValue>(
  1237. context, loc_id,
  1238. {.type_id = target.type_id,
  1239. .type_inst_id = type_inst_id,
  1240. .witnesses_block_id = lookup_result.inst_block_id()});
  1241. }
  1242. } else {
  1243. // If impl lookup fails, don't keep looking for another way to convert.
  1244. // See https://github.com/carbon-language/carbon-lang/issues/5122.
  1245. // TODO: Pass this function into `LookupImplWitness` so it can construct
  1246. // the error add notes explaining failure.
  1247. if (target.diagnose) {
  1248. DiagnoseConversionFailureToConstraintValue(context, loc_id, value_id,
  1249. target.type_id);
  1250. }
  1251. return SemIR::ErrorInst::InstId;
  1252. }
  1253. }
  1254. // No builtin conversion applies.
  1255. return value_id;
  1256. }
  1257. // Determine whether this is a C++ enum type.
  1258. // TODO: This should be removed once we can properly add a `Copy` impl for C++
  1259. // enum types.
  1260. static auto IsCppEnum(Context& context, SemIR::TypeId type_id) -> bool {
  1261. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  1262. if (!class_type) {
  1263. return false;
  1264. }
  1265. // A C++-imported class type that is an adapter is an enum.
  1266. auto& class_info = context.classes().Get(class_type->class_id);
  1267. return class_info.adapt_id.has_value() &&
  1268. context.name_scopes().Get(class_info.scope_id).is_cpp_scope();
  1269. }
  1270. // Given a value expression, form a corresponding initializer that copies from
  1271. // that value to the specified target, if it is possible to do so.
  1272. static auto PerformCopy(Context& context, SemIR::InstId expr_id,
  1273. const ConversionTarget& target) -> SemIR::InstId {
  1274. // TODO: We don't have a mechanism yet to generate `Copy` impls for each enum
  1275. // type imported from C++. For now we fake it by providing a direct copy.
  1276. auto type_id = context.insts().Get(expr_id).type_id();
  1277. if (IsCppEnum(context, type_id)) {
  1278. return expr_id;
  1279. }
  1280. auto copy_id = BuildUnaryOperator(
  1281. context, SemIR::LocId(expr_id), {.interface_name = CoreIdentifier::Copy},
  1282. expr_id, target.diagnose, [&](auto& builder) {
  1283. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Context,
  1284. "cannot copy value of type {0}", TypeOfInstId);
  1285. builder.Context(expr_id, CopyOfUncopyableType, expr_id);
  1286. });
  1287. return copy_id;
  1288. }
  1289. // Convert a value expression so that it can be used to initialize a C++ thunk
  1290. // parameter.
  1291. static auto ConvertValueForCppThunkRef(Context& context, SemIR::InstId expr_id)
  1292. -> SemIR::InstId {
  1293. auto expr = context.insts().Get(expr_id);
  1294. // If the expression has a pointer value representation, extract that and use
  1295. // it directly.
  1296. if (SemIR::ValueRepr::ForType(context.sem_ir(), expr.type_id()).kind ==
  1297. SemIR::ValueRepr::Pointer) {
  1298. return AddInst<SemIR::ValueAsRef>(
  1299. context, SemIR::LocId(expr_id),
  1300. {.type_id = expr.type_id(), .value_id = expr_id});
  1301. }
  1302. // Otherwise, we need a temporary to pass as the thunk argument. Create a copy
  1303. // and initialize a temporary from it.
  1304. auto temporary_id = AddInst<SemIR::TemporaryStorage>(
  1305. context, SemIR::LocId(expr_id), {.type_id = expr.type_id()});
  1306. expr_id = Initialize(context, SemIR::LocId(expr_id), temporary_id, expr_id);
  1307. return AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(expr_id),
  1308. {.type_id = expr.type_id(),
  1309. .storage_id = temporary_id,
  1310. .init_id = expr_id});
  1311. }
  1312. // Returns the Core interface name to use for a given kind of conversion.
  1313. static auto GetConversionInterfaceName(ConversionTarget::Kind kind)
  1314. -> CoreIdentifier {
  1315. switch (kind) {
  1316. case ConversionTarget::ExplicitAs:
  1317. return CoreIdentifier::As;
  1318. case ConversionTarget::ExplicitUnsafeAs:
  1319. return CoreIdentifier::UnsafeAs;
  1320. default:
  1321. return CoreIdentifier::ImplicitAs;
  1322. }
  1323. }
  1324. auto PerformAction(Context& context, SemIR::LocId loc_id,
  1325. SemIR::ConvertToValueAction action) -> SemIR::InstId {
  1326. return Convert(context, loc_id, action.inst_id,
  1327. {.kind = ConversionTarget::Value,
  1328. .type_id = context.types().GetTypeIdForTypeInstId(
  1329. action.target_type_inst_id)});
  1330. }
  1331. // State machine for performing category conversions.
  1332. class CategoryConverter {
  1333. public:
  1334. // Constructs a converter which converts an expression at the given location
  1335. // to the given conversion target.
  1336. CategoryConverter(Context& context, SemIR::LocId loc_id,
  1337. ConversionTarget& target)
  1338. : context_(context),
  1339. sem_ir_(context.sem_ir()),
  1340. loc_id_(loc_id),
  1341. target_(target) {}
  1342. // Converts expr_id to the target specified in the constructor, and returns
  1343. // the converted inst.
  1344. auto Convert(SemIR::InstId expr_id) && -> SemIR::InstId {
  1345. auto category = SemIR::GetExprCategory(sem_ir_, expr_id);
  1346. while (true) {
  1347. if (expr_id == SemIR::ErrorInst::InstId) {
  1348. return expr_id;
  1349. }
  1350. CARBON_KIND_SWITCH(DoStep(expr_id, category)) {
  1351. case CARBON_KIND(NextStep next_step): {
  1352. CARBON_CHECK(next_step.expr_id != SemIR::InstId::None);
  1353. expr_id = next_step.expr_id;
  1354. category = next_step.category;
  1355. break;
  1356. }
  1357. case CARBON_KIND(Done done): {
  1358. return done.expr_id;
  1359. }
  1360. }
  1361. }
  1362. }
  1363. private:
  1364. // State that indicates there's more work to be done. As a convenience,
  1365. // if expr_id is SemIR::ErrorInst::InstId, this is equivalent to
  1366. // Done{SemIR::ErrorInst::InstId}.
  1367. struct NextStep {
  1368. // The inst to convert.
  1369. SemIR::InstId expr_id;
  1370. // The category of expr_id.
  1371. SemIR::ExprCategory category;
  1372. };
  1373. // State that indicates we've finished category conversion.
  1374. struct Done {
  1375. // The result of the conversion.
  1376. SemIR::InstId expr_id;
  1377. };
  1378. using State = std::variant<NextStep, Done>;
  1379. // Performs the first step of converting `expr_id` with category `category`
  1380. // to the target specified in the constructor, and returns the state after
  1381. // that step.
  1382. auto DoStep(SemIR::InstId expr_id, SemIR::ExprCategory category) const
  1383. -> State;
  1384. Context& context_;
  1385. SemIR::File& sem_ir_;
  1386. SemIR::LocId loc_id_;
  1387. const ConversionTarget& target_;
  1388. };
  1389. auto CategoryConverter::DoStep(const SemIR::InstId expr_id,
  1390. const SemIR::ExprCategory category) const
  1391. -> State {
  1392. CARBON_DCHECK(SemIR::GetExprCategory(sem_ir_, expr_id) == category ||
  1393. // TODO: Drop this special case once PerformCopy on C++ enums
  1394. // produces an initializing expression.
  1395. IsCppEnum(context_, target_.type_id));
  1396. switch (category) {
  1397. case SemIR::ExprCategory::NotExpr:
  1398. case SemIR::ExprCategory::Mixed:
  1399. case SemIR::ExprCategory::Pattern:
  1400. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  1401. sem_ir_.insts().Get(expr_id));
  1402. case SemIR::ExprCategory::Error:
  1403. return Done{SemIR::ErrorInst::InstId};
  1404. case SemIR::ExprCategory::Dependent:
  1405. context_.TODO(expr_id, "Support symbolic expression forms");
  1406. return Done{SemIR::ErrorInst::InstId};
  1407. case SemIR::ExprCategory::InPlaceInitializing:
  1408. case SemIR::ExprCategory::ReprInitializing:
  1409. if (target_.is_initializer()) {
  1410. // Overwrite the initializer's storage argument with the inst currently
  1411. // at target_.storage_id, if both are present and the storage argument
  1412. // hasn't already been set. However, we skip this if the type is a C++
  1413. // enum: in that case, we don't actually have an initializing
  1414. // expression, we're just pretending we do.
  1415. auto new_storage_id = target_.storage_id;
  1416. if (!IsCppEnum(context_, target_.type_id)) {
  1417. new_storage_id =
  1418. OverwriteTemporaryStorageArg(sem_ir_, expr_id, target_);
  1419. }
  1420. // If in-place initialization was requested, and it hasn't already
  1421. // happened, ensure it happens now.
  1422. if (target_.kind == ConversionTarget::InPlaceInitializing &&
  1423. category != SemIR::ExprCategory::InPlaceInitializing &&
  1424. SemIR::InitRepr::ForType(sem_ir_, target_.type_id)
  1425. .MightBeByCopy()) {
  1426. target_.storage_access_block->InsertHere();
  1427. return Done{AddInst<SemIR::InPlaceInit>(context_, loc_id_,
  1428. {.type_id = target_.type_id,
  1429. .src_id = expr_id,
  1430. .dest_id = new_storage_id})};
  1431. }
  1432. return Done{expr_id};
  1433. }
  1434. // Commit to using a temporary for this initializing expression.
  1435. // TODO: Don't create a temporary if the initializing representation
  1436. // is already a value representation.
  1437. // TODO: If the target is DurableRef, materialize a VarStorage instead of
  1438. // a TemporaryStorage to lifetime-extend.
  1439. if (target_.kind == ConversionTarget::Discarded) {
  1440. DiscardInitializer(context_, expr_id);
  1441. return Done{SemIR::InstId::None};
  1442. } else {
  1443. return NextStep{.expr_id = MaterializeTemporary(context_, expr_id),
  1444. .category = SemIR::ExprCategory::EphemeralRef};
  1445. }
  1446. case SemIR::ExprCategory::RefTagged: {
  1447. auto tagged_expr_id =
  1448. sem_ir_.insts().GetAs<SemIR::RefTagExpr>(expr_id).expr_id;
  1449. auto tagged_expr_category =
  1450. SemIR::GetExprCategory(sem_ir_, tagged_expr_id);
  1451. if (target_.diagnose &&
  1452. tagged_expr_category != SemIR::ExprCategory::DurableRef) {
  1453. CARBON_DIAGNOSTIC(
  1454. RefTagNotDurableRef, Error,
  1455. "expression tagged with `ref` is not a durable reference");
  1456. context_.emitter().Emit(tagged_expr_id, RefTagNotDurableRef);
  1457. }
  1458. if (target_.kind == ConversionTarget::RefParam) {
  1459. return Done{expr_id};
  1460. }
  1461. // If the target isn't a reference parameter, ignore the `ref` tag.
  1462. // Unnecessary `ref` tags are diagnosed earlier.
  1463. return NextStep{.expr_id = tagged_expr_id,
  1464. .category = tagged_expr_category};
  1465. }
  1466. case SemIR::ExprCategory::DurableRef:
  1467. if (target_.kind == ConversionTarget::DurableRef ||
  1468. target_.kind == ConversionTarget::UnmarkedRefParam) {
  1469. return Done{expr_id};
  1470. }
  1471. if (target_.kind == ConversionTarget::RefParam) {
  1472. if (target_.diagnose) {
  1473. CARBON_DIAGNOSTIC(
  1474. RefParamNoRefTag, Error,
  1475. "argument to `ref` parameter not marked with `ref`");
  1476. context_.emitter().Emit(expr_id, RefParamNoRefTag);
  1477. }
  1478. return Done{expr_id};
  1479. }
  1480. [[fallthrough]];
  1481. case SemIR::ExprCategory::EphemeralRef:
  1482. // If a reference expression is an acceptable result, we're done.
  1483. if (target_.kind == ConversionTarget::ValueOrRef ||
  1484. target_.kind == ConversionTarget::Discarded ||
  1485. target_.kind == ConversionTarget::CppThunkRef ||
  1486. target_.kind == ConversionTarget::RefParam ||
  1487. target_.kind == ConversionTarget::UnmarkedRefParam) {
  1488. return Done{expr_id};
  1489. }
  1490. // If we have a reference and don't want one, form a value binding.
  1491. // TODO: Support types with custom value representations.
  1492. return NextStep{.expr_id = AddInst<SemIR::AcquireValue>(
  1493. context_, SemIR::LocId(expr_id),
  1494. {.type_id = target_.type_id, .value_id = expr_id}),
  1495. .category = SemIR::ExprCategory::Value};
  1496. case SemIR::ExprCategory::Value:
  1497. if (target_.kind == ConversionTarget::DurableRef) {
  1498. if (target_.diagnose) {
  1499. CARBON_DIAGNOSTIC(ConversionFailureNonRefToRef, Error,
  1500. "cannot bind durable reference to non-reference "
  1501. "value of type {0}",
  1502. SemIR::TypeId);
  1503. context_.emitter().Emit(loc_id_, ConversionFailureNonRefToRef,
  1504. target_.type_id);
  1505. }
  1506. return Done{SemIR::ErrorInst::InstId};
  1507. }
  1508. if (target_.kind == ConversionTarget::RefParam ||
  1509. target_.kind == ConversionTarget::UnmarkedRefParam) {
  1510. if (target_.diagnose) {
  1511. CARBON_DIAGNOSTIC(ValueForRefParam, Error,
  1512. "value expression passed to reference parameter");
  1513. context_.emitter().Emit(loc_id_, ValueForRefParam);
  1514. }
  1515. return Done{SemIR::ErrorInst::InstId};
  1516. }
  1517. // When initializing from a value, perform a copy.
  1518. if (target_.is_initializer()) {
  1519. auto copy_id = PerformCopy(context_, expr_id, target_);
  1520. if (copy_id == SemIR::ErrorInst::InstId) {
  1521. return Done{SemIR::ErrorInst::InstId};
  1522. }
  1523. // Deal with special-case category behavior of PerformCopy.
  1524. switch (SemIR::GetExprCategory(sem_ir_, copy_id)) {
  1525. case SemIR::ExprCategory::Value:
  1526. // As a temporary workaround, PerformCopy on a C++ enum currently
  1527. // returns the unchanged value, but we treat it as an initializing
  1528. // expression.
  1529. // TODO: Drop this case once it's no longer applicable.
  1530. CARBON_CHECK(IsCppEnum(context_, target_.type_id));
  1531. [[fallthrough]];
  1532. case SemIR::ExprCategory::ReprInitializing:
  1533. // The common case: PerformCopy produces an initializing expression.
  1534. return NextStep{.expr_id = copy_id,
  1535. .category = SemIR::ExprCategory::ReprInitializing};
  1536. case SemIR::ExprCategory::InPlaceInitializing:
  1537. // A C++ copy operation produces an ephemeral entire reference.
  1538. return NextStep{
  1539. .expr_id = copy_id,
  1540. .category = SemIR::ExprCategory::InPlaceInitializing};
  1541. default:
  1542. CARBON_FATAL("Unexpected category of copy operation {0}", category);
  1543. }
  1544. }
  1545. // When initializing a C++ thunk parameter, form a reference, creating a
  1546. // temporary if needed.
  1547. if (target_.kind == ConversionTarget::CppThunkRef) {
  1548. return Done{ConvertValueForCppThunkRef(context_, expr_id)};
  1549. }
  1550. return Done{expr_id};
  1551. }
  1552. }
  1553. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  1554. ConversionTarget target, SemIR::ClassType* vtable_class_type)
  1555. -> SemIR::InstId {
  1556. auto& sem_ir = context.sem_ir();
  1557. auto orig_expr_id = expr_id;
  1558. // Start by making sure both sides are non-errors. If any part is an error,
  1559. // the result is an error and we shouldn't diagnose.
  1560. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::ErrorInst::TypeId ||
  1561. target.type_id == SemIR::ErrorInst::TypeId) {
  1562. return SemIR::ErrorInst::InstId;
  1563. }
  1564. auto starting_category = SemIR::GetExprCategory(sem_ir, expr_id);
  1565. if (starting_category == SemIR::ExprCategory::NotExpr) {
  1566. // TODO: We currently encounter this for use of namespaces and functions.
  1567. // We should provide a better diagnostic for inappropriate use of
  1568. // namespace names, and allow use of functions as values.
  1569. if (target.diagnose) {
  1570. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  1571. "expression cannot be used as a value");
  1572. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  1573. }
  1574. return SemIR::ErrorInst::InstId;
  1575. }
  1576. // Diagnose unnecessary `ref` tags early, so that they're not obscured by
  1577. // conversions.
  1578. if (starting_category == SemIR::ExprCategory::RefTagged &&
  1579. target.kind != ConversionTarget::RefParam && target.diagnose) {
  1580. CARBON_DIAGNOSTIC(RefTagNoRefParam, Error,
  1581. "`ref` tag is not an argument to a `ref` parameter");
  1582. context.emitter().Emit(expr_id, RefTagNoRefParam);
  1583. }
  1584. // We can only perform initialization for complete, non-abstract types.
  1585. //
  1586. // TODO: Don't require a concrete type when `!target.is_initializer()`. We
  1587. // want to allow constructing a value of an abstract class type, but right now
  1588. // if we proceed into Convert with an abstract target type, we crash.
  1589. //
  1590. // Note that we allow conversion to incomplete to facet types, since their
  1591. // representation is fixed. This allows us to support using the `Self` of an
  1592. // interface inside its definition.
  1593. if (!context.types().IsFacetType(target.type_id)) {
  1594. if (target.diagnose) {
  1595. if (!RequireConcreteType(
  1596. context, target.type_id, loc_id,
  1597. [&](auto& builder) {
  1598. CARBON_CHECK(
  1599. !target.is_initializer(),
  1600. "Initialization of incomplete types is expected to be "
  1601. "caught elsewhere.");
  1602. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Context,
  1603. "forming value of incomplete type {0}",
  1604. SemIR::TypeId);
  1605. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Context,
  1606. "invalid use of incomplete type {0}",
  1607. SemIR::TypeId);
  1608. builder.Context(loc_id,
  1609. target.kind == ConversionTarget::Value
  1610. ? IncompleteTypeInValueConversion
  1611. : IncompleteTypeInConversion,
  1612. target.type_id);
  1613. },
  1614. [&](auto& builder) {
  1615. CARBON_DIAGNOSTIC(AbstractTypeInInit, Context,
  1616. "initialization of abstract type {0}",
  1617. SemIR::TypeId);
  1618. builder.Context(loc_id, AbstractTypeInInit, target.type_id);
  1619. })) {
  1620. return SemIR::ErrorInst::InstId;
  1621. }
  1622. } else {
  1623. if (!TryIsConcreteType(context, target.type_id, loc_id)) {
  1624. return SemIR::ErrorInst::InstId;
  1625. }
  1626. }
  1627. }
  1628. // Clear storage_id in cases where it's clearly meaningless, to avoid misuse
  1629. // and simplify the resulting SemIR.
  1630. if (!target.is_initializer() ||
  1631. SemIR::InitRepr::ForType(context.sem_ir(), target.type_id).kind ==
  1632. SemIR::InitRepr::None) {
  1633. target.storage_id = SemIR::InstId::None;
  1634. }
  1635. // The source type doesn't need to be complete, but its completeness can
  1636. // affect the result. For example, we don't know what type it adapts or
  1637. // derives from unless it's complete.
  1638. // TODO: Is there a risk of coherence problems if the source type is
  1639. // incomplete, but a conversion would have been possible or would have behaved
  1640. // differently if it were complete?
  1641. TryToCompleteType(context, context.insts().Get(expr_id).type_id(), loc_id);
  1642. // Check whether any builtin conversion applies.
  1643. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target,
  1644. vtable_class_type);
  1645. if (expr_id == SemIR::ErrorInst::InstId) {
  1646. return expr_id;
  1647. }
  1648. // Defer the action if it's dependent. We do this now rather than before
  1649. // attempting any conversion so that we can still perform builtin conversions
  1650. // on dependent arguments. This matters for things like converting a
  1651. // `template T:! SomeInterface` to `type`, where it's important to form a
  1652. // `FacetAccessType` when checking the template. But when running the action
  1653. // later, we need to try builtin conversions again, because one may apply that
  1654. // didn't apply in the template definition.
  1655. // TODO: Support this for targets other than `Value`.
  1656. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id &&
  1657. target.kind == ConversionTarget::Value &&
  1658. (OperandIsDependent(context, expr_id) ||
  1659. OperandIsDependent(context, target.type_id))) {
  1660. auto target_type_inst_id = context.types().GetTypeInstId(target.type_id);
  1661. return AddDependentActionSplice(
  1662. context, loc_id,
  1663. SemIR::ConvertToValueAction{
  1664. .type_id = GetSingletonType(context, SemIR::InstType::TypeInstId),
  1665. .inst_id = expr_id,
  1666. .target_type_inst_id = target_type_inst_id},
  1667. target_type_inst_id);
  1668. }
  1669. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  1670. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  1671. SemIR::InstId interface_args[] = {
  1672. context.types().GetTypeInstId(target.type_id)};
  1673. Operator op = {
  1674. .interface_name = GetConversionInterfaceName(target.kind),
  1675. .interface_args_ref = interface_args,
  1676. .op_name = CoreIdentifier::Convert,
  1677. };
  1678. expr_id = BuildUnaryOperator(
  1679. context, loc_id, op, expr_id, target.diagnose, [&](auto& builder) {
  1680. int target_kind_for_diag =
  1681. target.kind == ConversionTarget::ExplicitAs ? 1
  1682. : target.kind == ConversionTarget::ExplicitUnsafeAs ? 2
  1683. : 0;
  1684. if (target.type_id == SemIR::TypeType::TypeId ||
  1685. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1686. CARBON_DIAGNOSTIC(
  1687. ConversionFailureNonTypeToFacet, Context,
  1688. "cannot{0:=0: implicitly|:} convert non-type value of type {1} "
  1689. "{2:to|into type implementing} {3}"
  1690. "{0:=1: with `as`|=2: with `unsafe as`|:}",
  1691. Diagnostics::IntAsSelect, TypeOfInstId,
  1692. Diagnostics::BoolAsSelect, SemIR::TypeId);
  1693. builder.Context(loc_id, ConversionFailureNonTypeToFacet,
  1694. target_kind_for_diag, expr_id,
  1695. target.type_id == SemIR::TypeType::TypeId,
  1696. target.type_id);
  1697. } else {
  1698. CARBON_DIAGNOSTIC(
  1699. ConversionFailure, Context,
  1700. "cannot{0:=0: implicitly|:} convert expression of type "
  1701. "{1} to {2}{0:=1: with `as`|=2: with `unsafe as`|:}",
  1702. Diagnostics::IntAsSelect, TypeOfInstId, SemIR::TypeId);
  1703. builder.Context(loc_id, ConversionFailure, target_kind_for_diag,
  1704. expr_id, target.type_id);
  1705. }
  1706. });
  1707. // Pull a value directly out of the initializer if possible and wanted.
  1708. if (expr_id != SemIR::ErrorInst::InstId &&
  1709. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  1710. expr_id = AddInst<SemIR::ValueOfInitializer>(
  1711. context, loc_id, {.type_id = target.type_id, .init_id = expr_id});
  1712. }
  1713. }
  1714. // Track that we performed a type conversion, if we did so.
  1715. if (orig_expr_id != expr_id) {
  1716. expr_id = AddInst<SemIR::Converted>(context, loc_id,
  1717. {.type_id = target.type_id,
  1718. .original_id = orig_expr_id,
  1719. .result_id = expr_id});
  1720. }
  1721. // For `as`, don't perform any value category conversions. In particular, an
  1722. // identity conversion shouldn't change the expression category.
  1723. if (target.is_explicit_as()) {
  1724. return expr_id;
  1725. }
  1726. // Now perform any necessary value category conversions.
  1727. expr_id = CategoryConverter(context, loc_id, target).Convert(expr_id);
  1728. return expr_id;
  1729. }
  1730. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId storage_id,
  1731. SemIR::InstId value_id, bool for_return) -> SemIR::InstId {
  1732. auto type_id = context.insts().Get(storage_id).type_id();
  1733. if (for_return &&
  1734. !SemIR::InitRepr::ForType(context.sem_ir(), type_id).MightBeInPlace()) {
  1735. // TODO: is it safe to use storage_id when the init repr is dependent?
  1736. storage_id = SemIR::InstId::None;
  1737. }
  1738. // TODO: add CHECK that storage_id.index < value_id.index to enforce the
  1739. // precondition, once existing violations have been cleaned up.
  1740. PendingBlock target_block(&context);
  1741. return Convert(context, loc_id, value_id,
  1742. {.kind = ConversionTarget::Initializing,
  1743. .type_id = type_id,
  1744. .storage_id = storage_id,
  1745. .storage_access_block = &target_block});
  1746. }
  1747. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1748. -> SemIR::InstId {
  1749. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1750. {.kind = ConversionTarget::Value,
  1751. .type_id = context.insts().Get(expr_id).type_id()});
  1752. }
  1753. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1754. -> SemIR::InstId {
  1755. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1756. {.kind = ConversionTarget::ValueOrRef,
  1757. .type_id = context.insts().Get(expr_id).type_id()});
  1758. }
  1759. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1760. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1761. -> SemIR::InstId {
  1762. return Convert(context, loc_id, expr_id,
  1763. {.kind = ConversionTarget::Value, .type_id = type_id});
  1764. }
  1765. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1766. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1767. -> SemIR::InstId {
  1768. return Convert(context, loc_id, expr_id,
  1769. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1770. }
  1771. // Like ConvertToValueOfType but failure to convert does not result in
  1772. // diagnostics. An ErrorInst instruction is still returned on failure.
  1773. auto TryConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1774. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1775. -> SemIR::InstId {
  1776. return Convert(
  1777. context, loc_id, expr_id,
  1778. {.kind = ConversionTarget::Value, .type_id = type_id, .diagnose = false});
  1779. }
  1780. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1781. SemIR::InstId value_id) -> SemIR::InstId {
  1782. return ConvertToValueOfType(
  1783. context, loc_id, value_id,
  1784. GetSingletonType(context, SemIR::BoolType::TypeInstId));
  1785. }
  1786. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1787. SemIR::InstId value_id, SemIR::TypeId type_id,
  1788. bool unsafe) -> SemIR::InstId {
  1789. return Convert(context, as_node, value_id,
  1790. {.kind = unsafe ? ConversionTarget::ExplicitUnsafeAs
  1791. : ConversionTarget::ExplicitAs,
  1792. .type_id = type_id});
  1793. }
  1794. // TODO: Consider moving this to pattern_match.h.
  1795. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1796. SemIR::InstId self_id,
  1797. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1798. llvm::ArrayRef<SemIR::InstId> return_arg_ids,
  1799. const SemIR::Function& callee,
  1800. SemIR::SpecificId callee_specific_id,
  1801. bool is_operator_syntax) -> SemIR::InstBlockId {
  1802. auto param_patterns =
  1803. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1804. auto return_patterns_id = callee.return_patterns_id;
  1805. // The caller should have ensured this callee has the right arity.
  1806. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1807. if (callee.self_param_id.has_value() && !self_id.has_value()) {
  1808. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1809. "missing object argument in method call");
  1810. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1811. context.emitter()
  1812. .Build(call_loc_id, MissingObjectInMethodCall)
  1813. .Note(callee.latest_decl_id(), InCallToFunction)
  1814. .Emit();
  1815. self_id = SemIR::ErrorInst::InstId;
  1816. }
  1817. return CallerPatternMatch(context, callee_specific_id, callee.self_param_id,
  1818. callee.param_patterns_id, return_patterns_id,
  1819. self_id, arg_refs, return_arg_ids,
  1820. is_operator_syntax);
  1821. }
  1822. auto TypeExpr::ForUnsugared(Context& context, SemIR::TypeId type_id)
  1823. -> TypeExpr {
  1824. return {.inst_id = context.types().GetTypeInstId(type_id),
  1825. .type_id = type_id};
  1826. }
  1827. static auto DiagnoseTypeExprEvaluationFailure(Context& context,
  1828. SemIR::LocId loc_id) -> void {
  1829. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1830. "cannot evaluate type expression");
  1831. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1832. }
  1833. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  1834. bool diagnose) -> TypeExpr {
  1835. auto type_inst_id =
  1836. ConvertToValueOfType(context, loc_id, value_id, SemIR::TypeType::TypeId);
  1837. if (type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1838. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1839. .type_id = SemIR::ErrorInst::TypeId};
  1840. }
  1841. auto type_const_id = context.constant_values().Get(type_inst_id);
  1842. if (!type_const_id.is_constant()) {
  1843. if (diagnose) {
  1844. DiagnoseTypeExprEvaluationFailure(context, loc_id);
  1845. }
  1846. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1847. .type_id = SemIR::ErrorInst::TypeId};
  1848. }
  1849. return {.inst_id = context.types().GetAsTypeInstId(type_inst_id),
  1850. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1851. }
  1852. auto ExprAsReturnForm(Context& context, SemIR::LocId loc_id,
  1853. SemIR::InstId value_id) -> Context::FormExpr {
  1854. constexpr Context::FormExpr ErrorFormExpr = {
  1855. .form_inst_id = SemIR::ErrorInst::InstId,
  1856. .type_component_inst_id = SemIR::ErrorInst::TypeInstId,
  1857. .type_component_id = SemIR::ErrorInst::TypeId};
  1858. auto form_inst_id = SemIR::InstId::None;
  1859. auto type_inst_id = SemIR::InstId::None;
  1860. if (auto ref_tag = context.insts().TryGetAs<SemIR::RefTagExpr>(value_id)) {
  1861. type_inst_id = ConvertToValueOfType(context, loc_id, ref_tag->expr_id,
  1862. SemIR::TypeType::TypeId);
  1863. if (type_inst_id == SemIR::ErrorInst::InstId) {
  1864. return ErrorFormExpr;
  1865. }
  1866. if (!context.constant_values().Get(type_inst_id).is_constant()) {
  1867. DiagnoseTypeExprEvaluationFailure(context,
  1868. SemIR::LocId(ref_tag->expr_id));
  1869. return ErrorFormExpr;
  1870. }
  1871. form_inst_id = AddInst(
  1872. context,
  1873. SemIR::LocIdAndInst::UncheckedLoc(
  1874. loc_id,
  1875. SemIR::RefForm{.type_id = SemIR::FormType::TypeId,
  1876. .type_component_inst_id =
  1877. context.types().GetAsTypeInstId(type_inst_id)}));
  1878. } else {
  1879. type_inst_id = ConvertToValueOfType(context, loc_id, value_id,
  1880. SemIR::TypeType::TypeId);
  1881. if (type_inst_id == SemIR::ErrorInst::InstId) {
  1882. return ErrorFormExpr;
  1883. }
  1884. if (!context.constant_values().Get(type_inst_id).is_constant()) {
  1885. DiagnoseTypeExprEvaluationFailure(context, loc_id);
  1886. return ErrorFormExpr;
  1887. }
  1888. form_inst_id = AddInst(
  1889. context,
  1890. SemIR::LocIdAndInst::UncheckedLoc(
  1891. loc_id,
  1892. SemIR::InitForm{
  1893. .type_id = SemIR::FormType::TypeId,
  1894. .type_component_inst_id =
  1895. context.types().GetAsTypeInstId(type_inst_id),
  1896. .index = context.full_pattern_stack().NextCallParamIndex()}));
  1897. }
  1898. auto type_const_id = context.constant_values().Get(type_inst_id);
  1899. CARBON_CHECK(type_const_id.is_constant());
  1900. return {
  1901. .form_inst_id = form_inst_id,
  1902. .type_component_inst_id = context.types().GetAsTypeInstId(type_inst_id),
  1903. .type_component_id =
  1904. context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1905. }
  1906. auto DiscardExpr(Context& context, SemIR::InstId expr_id) -> void {
  1907. // If we discard an initializing expression, convert it to a value or
  1908. // reference so that it has something to initialize.
  1909. auto expr = context.insts().Get(expr_id);
  1910. Convert(context, SemIR::LocId(expr_id), expr_id,
  1911. {.kind = ConversionTarget::Discarded, .type_id = expr.type_id()});
  1912. // TODO: This will eventually need to do some "do not discard" analysis.
  1913. }
  1914. } // namespace Carbon::Check
  1915. // NOLINTEND(misc-no-recursion)