convert.cpp 66 KB

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