convert.cpp 70 KB

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