convert.cpp 66 KB

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