convert.cpp 66 KB

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