convert.cpp 67 KB

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