convert.cpp 66 KB

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