convert.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045
  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/core_identifier.h"
  16. #include "toolchain/check/diagnostic_helpers.h"
  17. #include "toolchain/check/eval.h"
  18. #include "toolchain/check/impl_lookup.h"
  19. #include "toolchain/check/import_ref.h"
  20. #include "toolchain/check/inst.h"
  21. #include "toolchain/check/operator.h"
  22. #include "toolchain/check/pattern_match.h"
  23. #include "toolchain/check/type.h"
  24. #include "toolchain/check/type_completion.h"
  25. #include "toolchain/diagnostics/format_providers.h"
  26. #include "toolchain/sem_ir/copy_on_write_block.h"
  27. #include "toolchain/sem_ir/expr_info.h"
  28. #include "toolchain/sem_ir/file.h"
  29. #include "toolchain/sem_ir/generic.h"
  30. #include "toolchain/sem_ir/ids.h"
  31. #include "toolchain/sem_ir/inst.h"
  32. #include "toolchain/sem_ir/type.h"
  33. #include "toolchain/sem_ir/type_info.h"
  34. #include "toolchain/sem_ir/typed_insts.h"
  35. // TODO: This contains a lot of recursion. Consider removing it in order to
  36. // prevent accidents.
  37. // NOLINTBEGIN(misc-no-recursion)
  38. namespace Carbon::Check {
  39. // Marks the initializer `init_id` as initializing `target.storage_id`.
  40. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  41. ConversionTarget& target) -> void {
  42. if (!target.storage_id.has_value()) {
  43. return;
  44. }
  45. CARBON_CHECK(target.is_initializer());
  46. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  47. if (return_slot_arg_id.has_value()) {
  48. // Replace the temporary in the return slot with a reference to our target.
  49. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  50. SemIR::TemporaryStorage::Kind,
  51. "Return slot for initializer does not contain a temporary; "
  52. "initialized multiple times? Have {0}",
  53. sem_ir.insts().Get(return_slot_arg_id));
  54. target.storage_id = target.storage_access_block->MergeReplacing(
  55. return_slot_arg_id, target.storage_id);
  56. }
  57. }
  58. // For a value or initializing expression using a copy value representation,
  59. // copy the value into a temporary object.
  60. static auto CopyValueToTemporary(Context& context, SemIR::InstId init_id)
  61. -> SemIR::InstId {
  62. // TODO: Consider using `None` to mean that we immediately materialize and
  63. // initialize a temporary, rather than two separate instructions.
  64. auto init = context.insts().Get(init_id);
  65. auto temporary_id = AddInst<SemIR::TemporaryStorage>(
  66. context, SemIR::LocId(init_id), {.type_id = init.type_id()});
  67. return AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(init_id),
  68. {.type_id = init.type_id(),
  69. .storage_id = temporary_id,
  70. .init_id = init_id});
  71. }
  72. // Commits to using a temporary to store the result of the initializing
  73. // expression described by `init_id`, and returns the location of the
  74. // temporary. If `discarded` is `true`, the result is discarded, and no
  75. // temporary will be created if possible; if no temporary is created, the
  76. // return value will be `SemIR::InstId::None`.
  77. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  78. bool discarded) -> SemIR::InstId {
  79. auto& sem_ir = context.sem_ir();
  80. auto return_slot_arg_id = FindReturnSlotArgForInitializer(sem_ir, init_id);
  81. if (return_slot_arg_id.has_value()) {
  82. // The return slot should already have a materialized temporary in it.
  83. CARBON_CHECK(sem_ir.insts().Get(return_slot_arg_id).kind() ==
  84. SemIR::TemporaryStorage::Kind,
  85. "Return slot for initializer does not contain a temporary; "
  86. "initialized multiple times? Have {0}",
  87. sem_ir.insts().Get(return_slot_arg_id));
  88. auto init = sem_ir.insts().Get(init_id);
  89. return AddInstWithCleanup<SemIR::Temporary>(
  90. context, SemIR::LocId(init_id),
  91. {.type_id = init.type_id(),
  92. .storage_id = return_slot_arg_id,
  93. .init_id = init_id});
  94. }
  95. if (discarded) {
  96. // Don't invent a temporary that we're going to discard.
  97. return SemIR::InstId::None;
  98. }
  99. // The initializer has no return slot, but we want to produce a temporary
  100. // object. Materialize one now.
  101. return CopyValueToTemporary(context, init_id);
  102. }
  103. // Materialize a temporary to hold the result of the given expression if it is
  104. // an initializing expression.
  105. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  106. -> SemIR::InstId {
  107. if (GetExprCategory(context.sem_ir(), expr_id) ==
  108. SemIR::ExprCategory::Initializing) {
  109. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  110. }
  111. return expr_id;
  112. }
  113. // Helper to allow `MakeElementAccessInst` to call `AddInst` with either a
  114. // `PendingBlock` or `Context` (defined in `inst.h`).
  115. template <typename AccessInstT>
  116. static auto AddInst(PendingBlock& block, SemIR::LocId loc_id, AccessInstT inst)
  117. -> SemIR::InstId {
  118. return block.AddInst<AccessInstT>(loc_id, inst);
  119. }
  120. // Creates and adds an instruction to perform element access into an aggregate.
  121. template <typename AccessInstT, typename InstBlockT>
  122. static auto MakeElementAccessInst(Context& context, SemIR::LocId loc_id,
  123. SemIR::InstId aggregate_id,
  124. SemIR::TypeId elem_type_id, InstBlockT& block,
  125. size_t i) -> SemIR::InstId {
  126. if (!aggregate_id.has_value()) {
  127. return SemIR::InstId::None;
  128. }
  129. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  130. // TODO: Add a new instruction kind for indexing an array at a constant
  131. // index so that we don't need an integer literal instruction here, and
  132. // remove this special case.
  133. auto index_id = block.template AddInst<SemIR::IntValue>(
  134. loc_id, {.type_id = GetSingletonType(context,
  135. SemIR::IntLiteralType::TypeInstId),
  136. .int_id = context.ints().Add(static_cast<int64_t>(i))});
  137. return AddInst<AccessInstT>(block, loc_id,
  138. {elem_type_id, aggregate_id, index_id});
  139. } else {
  140. return AddInst<AccessInstT>(
  141. block, loc_id, {elem_type_id, aggregate_id, SemIR::ElementIndex(i)});
  142. }
  143. }
  144. // Get the conversion target kind to use when initializing an element of an
  145. // aggregate.
  146. static auto GetAggregateElementConversionTargetKind(SemIR::File& sem_ir,
  147. ConversionTarget target)
  148. -> ConversionTarget::Kind {
  149. // If we're forming an initializer, then we want an initializer for each
  150. // element.
  151. if (target.is_initializer()) {
  152. // Perform a final destination store if we're performing an in-place
  153. // initialization.
  154. auto init_repr = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  155. CARBON_CHECK(init_repr.kind != SemIR::InitRepr::Dependent,
  156. "Aggregate should not have dependent init kind");
  157. if (init_repr.kind == SemIR::InitRepr::InPlace) {
  158. return ConversionTarget::FullInitializer;
  159. }
  160. return ConversionTarget::Initializer;
  161. }
  162. // Otherwise, we want a value representation for each element.
  163. return ConversionTarget::Value;
  164. }
  165. // Converts an element of one aggregate so that it can be used as an element of
  166. // another aggregate.
  167. //
  168. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  169. // element type, `src_field_index` is the index, and `SourceAccessInstT` is the
  170. // kind of instruction used to access the source element.
  171. //
  172. // For the target: `kind` is the kind of conversion or initialization,
  173. // `target_elem_type` is the element type. For initialization, `target_id` is
  174. // the destination, `target_block` is a pending block for target location
  175. // calculations that will be spliced as the return slot of the initializer if
  176. // necessary, `target_field_index` is the index, and `TargetAccessInstT` is the
  177. // kind of instruction used to access the destination element.
  178. template <typename SourceAccessInstT, typename TargetAccessInstT>
  179. static auto ConvertAggregateElement(
  180. Context& context, SemIR::LocId loc_id, SemIR::InstId src_id,
  181. SemIR::TypeInstId src_elem_type_inst,
  182. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  183. ConversionTarget::Kind kind, SemIR::InstId target_id,
  184. SemIR::TypeInstId target_elem_type_inst, PendingBlock* target_block,
  185. size_t src_field_index, size_t target_field_index,
  186. SemIR::ClassType* vtable_class_type = nullptr) -> SemIR::InstId {
  187. auto src_elem_type =
  188. context.types().GetTypeIdForTypeInstId(src_elem_type_inst);
  189. auto target_elem_type =
  190. context.types().GetTypeIdForTypeInstId(target_elem_type_inst);
  191. // Compute the location of the source element. This goes into the current code
  192. // block, not into the target block.
  193. // TODO: Ideally we would discard this instruction if it's unused.
  194. auto src_elem_id = !src_literal_elems.empty()
  195. ? src_literal_elems[src_field_index]
  196. : MakeElementAccessInst<SourceAccessInstT>(
  197. context, loc_id, src_id, src_elem_type, context,
  198. src_field_index);
  199. // If we're performing a conversion rather than an initialization, we won't
  200. // have or need a target.
  201. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  202. if (!target.is_initializer()) {
  203. return Convert(context, loc_id, src_elem_id, target);
  204. }
  205. // Compute the location of the target element and initialize it.
  206. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  207. target.storage_access_block = target_block;
  208. target.storage_id = MakeElementAccessInst<TargetAccessInstT>(
  209. context, loc_id, target_id, target_elem_type, *target_block,
  210. target_field_index);
  211. return Convert(context, loc_id, src_elem_id, target, vtable_class_type);
  212. }
  213. // Performs a conversion from a tuple to an array type. This function only
  214. // converts the type, and does not perform a final conversion to the requested
  215. // expression category.
  216. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  217. SemIR::ArrayType array_type,
  218. SemIR::InstId value_id, ConversionTarget target)
  219. -> SemIR::InstId {
  220. auto& sem_ir = context.sem_ir();
  221. auto tuple_elem_types = sem_ir.inst_blocks().Get(tuple_type.type_elements_id);
  222. auto value = sem_ir.insts().Get(value_id);
  223. SemIR::LocId value_loc_id(value_id);
  224. // If we're initializing from a tuple literal, we will use its elements
  225. // directly. Otherwise, materialize a temporary if needed and index into the
  226. // result.
  227. llvm::ArrayRef<SemIR::InstId> literal_elems;
  228. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  229. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  230. } else {
  231. value_id = MaterializeIfInitializing(context, value_id);
  232. }
  233. // Check that the tuple is the right size.
  234. std::optional<uint64_t> array_bound =
  235. sem_ir.GetArrayBoundValue(array_type.bound_id);
  236. if (!array_bound) {
  237. // TODO: Should this fall back to using `ImplicitAs`?
  238. if (target.diagnose) {
  239. CARBON_DIAGNOSTIC(ArrayInitDependentBound, Error,
  240. "cannot initialize array with dependent bound from a "
  241. "list of initializers");
  242. context.emitter().Emit(value_loc_id, ArrayInitDependentBound);
  243. }
  244. return SemIR::ErrorInst::InstId;
  245. }
  246. if (tuple_elem_types.size() != array_bound) {
  247. if (target.diagnose) {
  248. CARBON_DIAGNOSTIC(ArrayInitFromLiteralArgCountMismatch, Error,
  249. "cannot initialize array of {0} element{0:s} from {1} "
  250. "initializer{1:s}",
  251. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  252. CARBON_DIAGNOSTIC(
  253. ArrayInitFromExprArgCountMismatch, Error,
  254. "cannot initialize array of {0} element{0:s} from tuple "
  255. "with {1} element{1:s}",
  256. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect);
  257. context.emitter().Emit(value_loc_id,
  258. literal_elems.empty()
  259. ? ArrayInitFromExprArgCountMismatch
  260. : ArrayInitFromLiteralArgCountMismatch,
  261. *array_bound, tuple_elem_types.size());
  262. }
  263. return SemIR::ErrorInst::InstId;
  264. }
  265. PendingBlock target_block_storage(&context);
  266. PendingBlock* target_block = target.storage_access_block
  267. ? target.storage_access_block
  268. : &target_block_storage;
  269. // Arrays are always initialized in-place. Allocate a temporary as the
  270. // destination for the array initialization if we weren't given one.
  271. SemIR::InstId return_slot_arg_id = target.storage_id;
  272. if (!target.storage_id.has_value()) {
  273. return_slot_arg_id = target_block->AddInst<SemIR::TemporaryStorage>(
  274. value_loc_id, {.type_id = target.type_id});
  275. }
  276. // Initialize each element of the array from the corresponding element of the
  277. // tuple.
  278. // TODO: Annotate diagnostics coming from here with the array element index,
  279. // if initializing from a tuple literal.
  280. llvm::SmallVector<SemIR::InstId> inits;
  281. inits.reserve(*array_bound + 1);
  282. for (auto [i, src_type_inst_id] : llvm::enumerate(
  283. context.types().GetBlockAsTypeInstIds(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_inst_id, literal_elems,
  289. ConversionTarget::FullInitializer, return_slot_arg_id,
  290. array_type.element_type_inst_id, target_block, i, i);
  291. if (init_id == SemIR::ErrorInst::InstId) {
  292. return SemIR::ErrorInst::InstId;
  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.inst_blocks().Get(src_type.type_elements_id);
  313. auto dest_elem_types = sem_ir.inst_blocks().Get(dest_type.type_elements_id);
  314. auto value = sem_ir.insts().Get(value_id);
  315. SemIR::LocId value_loc_id(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::InstId;
  339. }
  340. ConversionTarget::Kind inner_kind =
  341. GetAggregateElementConversionTargetKind(sem_ir, target);
  342. // Initialize each element of the destination from the corresponding element
  343. // of the source.
  344. // TODO: Annotate diagnostics coming from here with the element index.
  345. auto new_block =
  346. literal_elems_id.has_value()
  347. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  348. : SemIR::CopyOnWriteInstBlock(
  349. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  350. src_elem_types.size()});
  351. for (auto [i, src_type_inst_id, dest_type_inst_id] : llvm::enumerate(
  352. context.types().GetBlockAsTypeInstIds(src_elem_types),
  353. context.types().GetBlockAsTypeInstIds(dest_elem_types))) {
  354. // TODO: This call recurses back into conversion. Switch to an iterative
  355. // approach.
  356. auto init_id =
  357. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  358. context, value_loc_id, value_id, src_type_inst_id, literal_elems,
  359. inner_kind, target.storage_id, dest_type_inst_id,
  360. target.storage_access_block, i, i);
  361. if (init_id == SemIR::ErrorInst::InstId) {
  362. return SemIR::ErrorInst::InstId;
  363. }
  364. new_block.Set(i, init_id);
  365. }
  366. if (target.is_initializer()) {
  367. target.storage_access_block->InsertHere();
  368. return AddInst<SemIR::TupleInit>(context, value_loc_id,
  369. {.type_id = target.type_id,
  370. .elements_id = new_block.id(),
  371. .dest_id = target.storage_id});
  372. } else {
  373. return AddInst<SemIR::TupleValue>(
  374. context, value_loc_id,
  375. {.type_id = target.type_id, .elements_id = new_block.id()});
  376. }
  377. }
  378. // Converts a tuple of elements that are convertible to `type` into a `type`
  379. // that is a tuple of types.
  380. static auto ConvertTupleToType(Context& context, SemIR::LocId loc_id,
  381. SemIR::InstId value_id,
  382. SemIR::TypeId value_type_id,
  383. ConversionTarget target) -> SemIR::TypeInstId {
  384. auto value_const_id = context.constant_values().Get(value_id);
  385. if (!value_const_id.is_constant()) {
  386. // Types are constants. The input value must have a constant value to
  387. // convert.
  388. return SemIR::TypeInstId::None;
  389. }
  390. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  391. auto value_const_inst_id =
  392. context.constant_values().GetInstId(value_const_id);
  393. if (auto tuple_value =
  394. context.insts().TryGetAs<SemIR::TupleValue>(value_const_inst_id)) {
  395. for (auto tuple_inst_id :
  396. context.inst_blocks().Get(tuple_value->elements_id)) {
  397. // TODO: This call recurses back into conversion. Switch to an
  398. // iterative approach.
  399. type_inst_ids.push_back(
  400. ExprAsType(context, loc_id, tuple_inst_id, target.diagnose).inst_id);
  401. }
  402. } else {
  403. // A value of type TupleType that isn't a TupleValue must be a symbolic
  404. // binding.
  405. CARBON_CHECK(
  406. context.insts().Is<SemIR::SymbolicBinding>(value_const_inst_id));
  407. // Form a TupleAccess for each element in the symbolic value, which is then
  408. // converted to a `type` or diagnosed as an error.
  409. auto tuple_type = context.types().GetAs<SemIR::TupleType>(value_type_id);
  410. auto type_elements = context.types().GetBlockAsTypeIds(
  411. context.inst_blocks().Get(tuple_type.type_elements_id));
  412. for (auto [i, type_id] : llvm::enumerate(type_elements)) {
  413. auto access_inst_id =
  414. GetOrAddInst<SemIR::TupleAccess>(context, loc_id,
  415. {.type_id = type_id,
  416. .tuple_id = value_id,
  417. .index = SemIR::ElementIndex(i)});
  418. // TODO: This call recurses back into conversion. Switch to an
  419. // iterative approach.
  420. type_inst_ids.push_back(
  421. ExprAsType(context, loc_id, access_inst_id, target.diagnose).inst_id);
  422. }
  423. }
  424. // TODO: Should we add this as an instruction? It will contain
  425. // references to local InstIds.
  426. auto tuple_type_id = GetTupleType(context, type_inst_ids);
  427. return context.types().GetInstId(tuple_type_id);
  428. }
  429. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  430. template <typename TargetAccessInstT>
  431. static auto ConvertStructToStructOrClass(
  432. Context& context, SemIR::StructType src_type, SemIR::StructType dest_type,
  433. SemIR::InstId value_id, ConversionTarget target,
  434. SemIR::ClassType* vtable_class_type = nullptr) -> SemIR::InstId {
  435. static_assert(std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT> ||
  436. std::is_same_v<SemIR::StructAccess, TargetAccessInstT>);
  437. constexpr bool ToClass =
  438. std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT>;
  439. auto& sem_ir = context.sem_ir();
  440. auto src_elem_fields = sem_ir.struct_type_fields().Get(src_type.fields_id);
  441. auto dest_elem_fields = sem_ir.struct_type_fields().Get(dest_type.fields_id);
  442. bool dest_has_vptr = !dest_elem_fields.empty() &&
  443. dest_elem_fields.front().name_id == SemIR::NameId::Vptr;
  444. int dest_vptr_offset = (dest_has_vptr ? 1 : 0);
  445. auto dest_elem_fields_size = dest_elem_fields.size() - dest_vptr_offset;
  446. auto value = sem_ir.insts().Get(value_id);
  447. SemIR::LocId value_loc_id(value_id);
  448. // If we're initializing from a struct literal, we will use its elements
  449. // directly. Otherwise, materialize a temporary if needed and index into the
  450. // result.
  451. llvm::ArrayRef<SemIR::InstId> literal_elems;
  452. auto literal_elems_id = SemIR::InstBlockId::None;
  453. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  454. literal_elems_id = struct_literal->elements_id;
  455. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  456. } else {
  457. value_id = MaterializeIfInitializing(context, value_id);
  458. }
  459. // Check that the structs are the same size.
  460. // TODO: If not, include the name of the first source field that doesn't
  461. // exist in the destination or vice versa in the diagnostic.
  462. if (src_elem_fields.size() != dest_elem_fields_size) {
  463. if (target.diagnose) {
  464. CARBON_DIAGNOSTIC(
  465. StructInitElementCountMismatch, Error,
  466. "cannot initialize {0:class|struct} with {1} field{1:s} from struct "
  467. "with {2} field{2:s}",
  468. Diagnostics::BoolAsSelect, Diagnostics::IntAsSelect,
  469. Diagnostics::IntAsSelect);
  470. context.emitter().Emit(value_loc_id, StructInitElementCountMismatch,
  471. ToClass, dest_elem_fields_size,
  472. src_elem_fields.size());
  473. }
  474. return SemIR::ErrorInst::InstId;
  475. }
  476. // Prepare to look up fields in the source by index.
  477. Map<SemIR::NameId, int32_t> src_field_indexes;
  478. if (src_type.fields_id != dest_type.fields_id) {
  479. for (auto [i, field] : llvm::enumerate(src_elem_fields)) {
  480. auto result = src_field_indexes.Insert(field.name_id, i);
  481. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  482. }
  483. }
  484. ConversionTarget::Kind inner_kind =
  485. GetAggregateElementConversionTargetKind(sem_ir, target);
  486. // Initialize each element of the destination from the corresponding element
  487. // of the source.
  488. // TODO: Annotate diagnostics coming from here with the element index.
  489. auto new_block =
  490. literal_elems_id.has_value() && !dest_has_vptr
  491. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  492. : SemIR::CopyOnWriteInstBlock(
  493. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  494. dest_elem_fields.size()});
  495. for (auto [i, dest_field] : llvm::enumerate(dest_elem_fields)) {
  496. if (dest_field.name_id == SemIR::NameId::Vptr) {
  497. if constexpr (!ToClass) {
  498. CARBON_FATAL("Only classes should have vptrs.");
  499. }
  500. target.storage_access_block->InsertHere();
  501. auto vptr_type_id =
  502. context.types().GetTypeIdForTypeInstId(dest_field.type_inst_id);
  503. auto dest_id =
  504. AddInst<SemIR::ClassElementAccess>(context, value_loc_id,
  505. {.type_id = vptr_type_id,
  506. .base_id = target.storage_id,
  507. .index = SemIR::ElementIndex(i)});
  508. auto vtable_decl_id =
  509. context.classes().Get(vtable_class_type->class_id).vtable_decl_id;
  510. LoadImportRef(context, vtable_decl_id);
  511. auto canonical_vtable_decl_id =
  512. context.constant_values().GetConstantInstId(vtable_decl_id);
  513. auto vtable_ptr_id = AddInst<SemIR::VtablePtr>(
  514. context, value_loc_id,
  515. {.type_id = GetPointerType(context, SemIR::VtableType::TypeInstId),
  516. .vtable_id = context.insts()
  517. .GetAs<SemIR::VtableDecl>(canonical_vtable_decl_id)
  518. .vtable_id,
  519. .specific_id = vtable_class_type->specific_id});
  520. auto init_id = AddInst<SemIR::InitializeFrom>(context, value_loc_id,
  521. {.type_id = vptr_type_id,
  522. .src_id = vtable_ptr_id,
  523. .dest_id = dest_id});
  524. new_block.Set(i, init_id);
  525. continue;
  526. }
  527. // Find the matching source field.
  528. auto src_field_index = i;
  529. if (src_type.fields_id != dest_type.fields_id) {
  530. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  531. src_field_index = lookup.value();
  532. } else {
  533. if (target.diagnose) {
  534. if (literal_elems_id.has_value()) {
  535. CARBON_DIAGNOSTIC(
  536. StructInitMissingFieldInLiteral, Error,
  537. "missing value for field `{0}` in struct initialization",
  538. SemIR::NameId);
  539. context.emitter().Emit(value_loc_id,
  540. StructInitMissingFieldInLiteral,
  541. dest_field.name_id);
  542. } else {
  543. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  544. "cannot convert from struct type {0} to {1}: "
  545. "missing field `{2}` in source type",
  546. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  547. context.emitter().Emit(value_loc_id,
  548. StructInitMissingFieldInConversion, value_id,
  549. target.type_id, dest_field.name_id);
  550. }
  551. }
  552. return SemIR::ErrorInst::InstId;
  553. }
  554. }
  555. auto src_field = src_elem_fields[src_field_index];
  556. // TODO: This call recurses back into conversion. Switch to an iterative
  557. // approach.
  558. auto init_id =
  559. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  560. context, value_loc_id, value_id, src_field.type_inst_id,
  561. literal_elems, inner_kind, target.storage_id,
  562. dest_field.type_inst_id, target.storage_access_block,
  563. src_field_index, src_field_index + dest_vptr_offset,
  564. vtable_class_type);
  565. if (init_id == SemIR::ErrorInst::InstId) {
  566. return SemIR::ErrorInst::InstId;
  567. }
  568. new_block.Set(i, init_id);
  569. }
  570. bool is_init = target.is_initializer();
  571. if (ToClass) {
  572. target.storage_access_block->InsertHere();
  573. CARBON_CHECK(is_init,
  574. "Converting directly to a class value is not supported");
  575. return AddInst<SemIR::ClassInit>(context, value_loc_id,
  576. {.type_id = target.type_id,
  577. .elements_id = new_block.id(),
  578. .dest_id = target.storage_id});
  579. } else if (is_init) {
  580. target.storage_access_block->InsertHere();
  581. return AddInst<SemIR::StructInit>(context, value_loc_id,
  582. {.type_id = target.type_id,
  583. .elements_id = new_block.id(),
  584. .dest_id = target.storage_id});
  585. } else {
  586. return AddInst<SemIR::StructValue>(
  587. context, value_loc_id,
  588. {.type_id = target.type_id, .elements_id = new_block.id()});
  589. }
  590. }
  591. // Performs a conversion from a struct to a struct type. This function only
  592. // converts the type, and does not perform a final conversion to the requested
  593. // expression category.
  594. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  595. SemIR::StructType dest_type,
  596. SemIR::InstId value_id,
  597. ConversionTarget target) -> SemIR::InstId {
  598. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  599. context, src_type, dest_type, value_id, target);
  600. }
  601. // Performs a conversion from a struct to a class type. This function only
  602. // converts the type, and does not perform a final conversion to the requested
  603. // expression category.
  604. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  605. SemIR::ClassType dest_type,
  606. SemIR::InstId value_id,
  607. ConversionTarget target,
  608. SemIR::ClassType* vtable_class_type)
  609. -> SemIR::InstId {
  610. PendingBlock target_block(&context);
  611. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  612. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  613. auto object_repr_id =
  614. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  615. if (object_repr_id == SemIR::ErrorInst::TypeId) {
  616. return SemIR::ErrorInst::InstId;
  617. }
  618. if (context.types().Is<SemIR::CustomLayoutType>(object_repr_id)) {
  619. // Builtin conversion does not apply.
  620. return value_id;
  621. }
  622. auto dest_struct_type =
  623. context.types().GetAs<SemIR::StructType>(object_repr_id);
  624. // If we're trying to create a class value, form a temporary for the value to
  625. // point to.
  626. bool need_temporary = !target.is_initializer();
  627. if (need_temporary) {
  628. target.kind = ConversionTarget::Initializer;
  629. target.storage_access_block = &target_block;
  630. target.storage_id = target_block.AddInst<SemIR::TemporaryStorage>(
  631. SemIR::LocId(value_id), {.type_id = target.type_id});
  632. }
  633. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  634. context, src_type, dest_struct_type, value_id, target,
  635. vtable_class_type ? vtable_class_type : &dest_type);
  636. if (need_temporary) {
  637. target_block.InsertHere();
  638. result_id =
  639. AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(value_id),
  640. {.type_id = target.type_id,
  641. .storage_id = target.storage_id,
  642. .init_id = result_id});
  643. }
  644. return result_id;
  645. }
  646. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  647. // in order from derived to base.
  648. using InheritancePath =
  649. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  650. // Computes the inheritance path from class `derived_id` to class `base_id`.
  651. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  652. static auto ComputeInheritancePath(Context& context, SemIR::LocId loc_id,
  653. SemIR::TypeId derived_id,
  654. SemIR::TypeId base_id)
  655. -> std::optional<InheritancePath> {
  656. // We intend for NRVO to be applied to `result`. All `return` statements in
  657. // this function should `return result;`.
  658. std::optional<InheritancePath> result(std::in_place);
  659. if (!TryToCompleteType(context, derived_id, loc_id)) {
  660. // TODO: Should we give an error here? If we don't, and there is an
  661. // inheritance path when the class is defined, we may have a coherence
  662. // problem.
  663. result = std::nullopt;
  664. return result;
  665. }
  666. while (derived_id != base_id) {
  667. auto derived_class_type =
  668. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  669. if (!derived_class_type) {
  670. result = std::nullopt;
  671. break;
  672. }
  673. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  674. auto base_type_id = derived_class.GetBaseType(
  675. context.sem_ir(), derived_class_type->specific_id);
  676. if (!base_type_id.has_value()) {
  677. result = std::nullopt;
  678. break;
  679. }
  680. result->push_back({derived_class.base_id, base_type_id});
  681. derived_id = base_type_id;
  682. }
  683. return result;
  684. }
  685. // Performs a conversion from a derived class value or reference to a base class
  686. // value or reference.
  687. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  688. SemIR::InstId value_id,
  689. const InheritancePath& path) -> SemIR::InstId {
  690. // Materialize a temporary if necessary.
  691. value_id = ConvertToValueOrRefExpr(context, value_id);
  692. // Preserve type qualifiers.
  693. auto quals = context.types()
  694. .GetUnqualifiedTypeAndQualifiers(
  695. context.insts().Get(value_id).type_id())
  696. .second;
  697. // Add a series of `.base` accesses.
  698. for (auto [base_id, base_type_id] : path) {
  699. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  700. value_id = AddInst<SemIR::ClassElementAccess>(
  701. context, loc_id,
  702. {.type_id = GetQualifiedType(context, base_type_id, quals),
  703. .base_id = value_id,
  704. .index = base_decl.index});
  705. }
  706. return value_id;
  707. }
  708. // Performs a conversion from a derived class pointer to a base class pointer.
  709. static auto ConvertDerivedPointerToBasePointer(
  710. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  711. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  712. const InheritancePath& path) -> SemIR::InstId {
  713. auto pointee_type_id =
  714. context.types().GetTypeIdForTypeInstId(src_ptr_type.pointee_id);
  715. // Form `*p`.
  716. ptr_id = ConvertToValueExpr(context, ptr_id);
  717. auto ref_id = AddInst<SemIR::Deref>(
  718. context, loc_id, {.type_id = pointee_type_id, .pointer_id = ptr_id});
  719. // Convert as a reference expression.
  720. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  721. // Take the address.
  722. return AddInst<SemIR::AddrOf>(
  723. context, loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  724. }
  725. // Returns whether `category` is a valid expression category to produce as a
  726. // result of a conversion with kind `target_kind`.
  727. static auto IsValidExprCategoryForConversionTarget(
  728. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  729. switch (target_kind) {
  730. case ConversionTarget::Value:
  731. return category == SemIR::ExprCategory::Value;
  732. case ConversionTarget::ValueOrRef:
  733. return category == SemIR::ExprCategory::Value ||
  734. category == SemIR::ExprCategory::DurableRef ||
  735. category == SemIR::ExprCategory::EphemeralRef;
  736. case ConversionTarget::Discarded:
  737. return category == SemIR::ExprCategory::Value ||
  738. category == SemIR::ExprCategory::DurableRef ||
  739. category == SemIR::ExprCategory::EphemeralRef ||
  740. category == SemIR::ExprCategory::Initializing;
  741. case ConversionTarget::RefParam:
  742. case ConversionTarget::UnmarkedRefParam:
  743. return category == SemIR::ExprCategory::DurableRef ||
  744. category == SemIR::ExprCategory::EphemeralRef ||
  745. category == SemIR::ExprCategory::Initializing;
  746. case ConversionTarget::DurableRef:
  747. return category == SemIR::ExprCategory::DurableRef;
  748. case ConversionTarget::CppThunkRef:
  749. return category == SemIR::ExprCategory::EphemeralRef;
  750. case ConversionTarget::ExplicitAs:
  751. case ConversionTarget::ExplicitUnsafeAs:
  752. return true;
  753. case ConversionTarget::Initializer:
  754. case ConversionTarget::FullInitializer:
  755. return category == SemIR::ExprCategory::Initializing;
  756. }
  757. }
  758. // Determines whether the initialization representation of the type is a copy of
  759. // the value representation.
  760. static auto InitReprIsCopyOfValueRepr(const SemIR::File& sem_ir,
  761. SemIR::TypeId type_id) -> bool {
  762. // The initializing representation is a copy of the value representation if
  763. // they're both copies of the object representation.
  764. return SemIR::InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  765. SemIR::ValueRepr::ForType(sem_ir, type_id)
  766. .IsCopyOfObjectRepr(sem_ir, type_id);
  767. }
  768. // Determines whether we can pull a value directly out of an initializing
  769. // expression of type `type_id` to initialize a target of type `type_id` and
  770. // kind `target_kind`.
  771. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  772. SemIR::TypeId type_id,
  773. ConversionTarget::Kind target_kind)
  774. -> bool {
  775. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  776. target_kind)) {
  777. // We don't want a value expression.
  778. return false;
  779. }
  780. // We can pull a value out of an initializing expression if it holds one.
  781. return InitReprIsCopyOfValueRepr(sem_ir, type_id);
  782. }
  783. // Determine whether the given set of qualifiers can be added by a conversion
  784. // of an expression of the given category.
  785. static auto CanAddQualifiers(SemIR::TypeQualifiers quals,
  786. SemIR::ExprCategory cat) -> bool {
  787. if (quals.HasAnyOf(SemIR::TypeQualifiers::MaybeUnformed) &&
  788. !SemIR::IsRefCategory(cat)) {
  789. // `MaybeUnformed(T)` may have a different value representation or
  790. // initializing representation from `T`, so only allow it to be added for a
  791. // reference expression.
  792. // TODO: We should allow converting an initializing expression of type `T`
  793. // to `MaybeUnformed(T)`. `PerformBuiltinConversion` will need to generate
  794. // an `InPlaceInit` instruction when needed.
  795. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  796. return false;
  797. }
  798. // `const` and `partial` can always be added.
  799. return true;
  800. }
  801. // Determine whether the given set of qualifiers can be removed by a conversion
  802. // of an expression of the given category.
  803. static auto CanRemoveQualifiers(SemIR::TypeQualifiers quals,
  804. SemIR::ExprCategory cat,
  805. ConversionTarget::Kind kind) -> bool {
  806. bool allow_unsafe = kind == ConversionTarget::ExplicitUnsafeAs;
  807. if (quals.HasAnyOf(SemIR::TypeQualifiers::Const) && !allow_unsafe &&
  808. SemIR::IsRefCategory(cat) &&
  809. IsValidExprCategoryForConversionTarget(cat, kind)) {
  810. // Removing `const` is an unsafe conversion for a reference expression. But
  811. // it's OK if we will be converting to a different category as part of this
  812. // overall conversion anyway.
  813. return false;
  814. }
  815. if (quals.HasAnyOf(SemIR::TypeQualifiers::Partial) &&
  816. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  817. // TODO: Allow removing `partial` for initializing expressions as a safe
  818. // conversion. `PerformBuiltinConversion` will need to initialize the vptr
  819. // as part of the conversion.
  820. return false;
  821. }
  822. if (quals.HasAnyOf(SemIR::TypeQualifiers::MaybeUnformed) &&
  823. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  824. // As an unsafe conversion, `MaybeUnformed` can be removed from a value or
  825. // reference expression.
  826. return false;
  827. }
  828. return true;
  829. }
  830. static auto DiagnoseConversionFailureToConstraintValue(
  831. Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  832. SemIR::TypeId target_type_id) -> void {
  833. CARBON_CHECK(context.types().IsFacetType(target_type_id));
  834. // If the source type is/has a facet value (converted with `as type` or
  835. // otherwise), then we can include its `FacetType` in the diagnostic to help
  836. // explain what interfaces the source type implements.
  837. auto const_expr_id = GetCanonicalFacetOrTypeValue(context, expr_id);
  838. auto const_expr_type_id = context.insts().Get(const_expr_id).type_id();
  839. if (context.types().Is<SemIR::FacetType>(const_expr_type_id)) {
  840. CARBON_DIAGNOSTIC(ConversionFailureFacetToFacet, Error,
  841. "cannot convert type {0} that implements {1} into type "
  842. "implementing {2}",
  843. InstIdAsType, SemIR::TypeId, SemIR::TypeId);
  844. context.emitter().Emit(loc_id, ConversionFailureFacetToFacet, expr_id,
  845. const_expr_type_id, target_type_id);
  846. } else {
  847. CARBON_DIAGNOSTIC(ConversionFailureTypeToFacet, Error,
  848. "cannot convert type {0} into type implementing {1}",
  849. InstIdAsType, SemIR::TypeId);
  850. context.emitter().Emit(loc_id, ConversionFailureTypeToFacet, expr_id,
  851. target_type_id);
  852. }
  853. }
  854. static auto PerformBuiltinConversion(
  855. Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  856. ConversionTarget target, SemIR::ClassType* vtable_class_type = nullptr)
  857. -> SemIR::InstId {
  858. auto& sem_ir = context.sem_ir();
  859. auto value = sem_ir.insts().Get(value_id);
  860. auto value_type_id = value.type_id();
  861. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  862. // Various forms of implicit conversion are supported as builtin conversions,
  863. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  864. // prelude. There are a few reasons we need to perform some of these
  865. // conversions as builtins:
  866. //
  867. // 1) Conversions from struct and tuple *literals* have special rules that
  868. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  869. // recurse into the elements of the literal before performing
  870. // initialization in order to avoid unnecessary conversions between
  871. // expression categories that would be performed by `ImplicitAs.Convert`.
  872. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  873. // the value of the facet, not only its type, and therefore cannot be
  874. // modeled by `ImplicitAs`.
  875. // 3) Some of these conversions are used while checking the library
  876. // definition of `ImplicitAs` itself or implementations of it.
  877. //
  878. // We also expect to see better performance by avoiding an `impl` lookup for
  879. // common conversions.
  880. //
  881. // TODO: We should provide a debugging flag to turn off as many of these
  882. // builtin conversions as we can so that we can test that they do the same
  883. // thing as the library implementations.
  884. //
  885. // The builtin conversions that correspond to `impl`s in the library all
  886. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  887. // being specialized in any of these cases.
  888. // If the value is already of the right kind and expression category, there's
  889. // nothing to do. Performing a conversion would decompose and rebuild tuples
  890. // and structs, so it's important that we bail out early in this case.
  891. if (value_type_id == target.type_id) {
  892. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  893. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  894. return value_id;
  895. }
  896. // If the source is an initializing expression, we may be able to pull a
  897. // value right out of it.
  898. if (value_cat == SemIR::ExprCategory::Initializing &&
  899. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  900. return AddInst<SemIR::ValueOfInitializer>(
  901. context, loc_id, {.type_id = value_type_id, .init_id = value_id});
  902. }
  903. // Materialization is handled as part of the enclosing conversion.
  904. if (value_cat == SemIR::ExprCategory::Initializing &&
  905. target.kind == ConversionTarget::ValueOrRef) {
  906. return value_id;
  907. }
  908. // PerformBuiltinConversion converts each part of a tuple or struct, even
  909. // when the types are the same. This is not done for classes since they have
  910. // to define their conversions as part of their api.
  911. //
  912. // If a class adapts a tuple or struct, we convert each of its parts when
  913. // there's no other conversion going on (the source and target types are the
  914. // same). To do so, we have to insert a conversion of the value up to the
  915. // foundation and back down, and a conversion of the initializing object if
  916. // there is one.
  917. //
  918. // Implementation note: We do the conversion through a call to
  919. // PerformBuiltinConversion() call rather than a Convert() call to avoid
  920. // extraneous `converted` semir instructions on the adapted types, and as a
  921. // shortcut to doing the explicit calls to walk the parts of the
  922. // tuple/struct which happens inside PerformBuiltinConversion().
  923. if (auto foundation_type_id =
  924. context.types().GetTransitiveAdaptedType(value_type_id);
  925. foundation_type_id != value_type_id &&
  926. context.types().IsOneOf<SemIR::StructType, SemIR::TupleType>(
  927. foundation_type_id)) {
  928. auto foundation_value_id = AddInst<SemIR::AsCompatible>(
  929. context, loc_id,
  930. {.type_id = foundation_type_id, .source_id = value_id});
  931. auto foundation_init_id = target.storage_id;
  932. if (foundation_init_id != SemIR::InstId::None) {
  933. foundation_init_id =
  934. target.storage_access_block->AddInst<SemIR::AsCompatible>(
  935. loc_id, {.type_id = foundation_type_id,
  936. .source_id = target.storage_id});
  937. }
  938. {
  939. // While the types are the same, the conversion can still fail if it
  940. // performs a copy while converting the value to another category, and
  941. // the type (or some part of it) is not copyable.
  942. Diagnostics::AnnotationScope annotate_diagnostics(
  943. &context.emitter(), [&](auto& builder) {
  944. CARBON_DIAGNOSTIC(InCopy, Note, "in copy of {0}", TypeOfInstId);
  945. builder.Note(value_id, InCopy, value_id);
  946. });
  947. foundation_value_id = PerformBuiltinConversion(
  948. context, loc_id, foundation_value_id,
  949. {.kind = target.kind,
  950. .type_id = foundation_type_id,
  951. .storage_id = foundation_init_id,
  952. .storage_access_block = target.storage_access_block,
  953. .diagnose = target.diagnose});
  954. if (foundation_value_id == SemIR::ErrorInst::InstId) {
  955. return SemIR::ErrorInst::InstId;
  956. }
  957. }
  958. return AddInst<SemIR::AsCompatible>(
  959. context, loc_id,
  960. {.type_id = target.type_id, .source_id = foundation_value_id});
  961. }
  962. }
  963. // T implicitly converts to U if T and U are the same ignoring qualifiers, and
  964. // we're allowed to remove / add any qualifiers that differ. Similarly, T
  965. // explicitly converts to U if T is compatible with U, and we're allowed to
  966. // remove / add any qualifiers that differ.
  967. if (target.type_id != value_type_id) {
  968. auto [target_foundation_id, target_quals] =
  969. target.is_explicit_as()
  970. ? context.types().GetTransitiveUnqualifiedAdaptedType(
  971. target.type_id)
  972. : context.types().GetUnqualifiedTypeAndQualifiers(target.type_id);
  973. auto [value_foundation_id, value_quals] =
  974. target.is_explicit_as()
  975. ? context.types().GetTransitiveUnqualifiedAdaptedType(value_type_id)
  976. : context.types().GetUnqualifiedTypeAndQualifiers(value_type_id);
  977. if (target_foundation_id == value_foundation_id) {
  978. auto category = SemIR::GetExprCategory(context.sem_ir(), value_id);
  979. auto added_quals = target_quals & ~value_quals;
  980. auto removed_quals = value_quals & ~target_quals;
  981. if (CanAddQualifiers(added_quals, category) &&
  982. CanRemoveQualifiers(removed_quals, category, target.kind)) {
  983. // For a struct or tuple literal, perform a category conversion if
  984. // necessary.
  985. if (category == SemIR::ExprCategory::Mixed) {
  986. value_id = PerformBuiltinConversion(context, loc_id, value_id,
  987. {.kind = ConversionTarget::Value,
  988. .type_id = value_type_id,
  989. .diagnose = target.diagnose});
  990. }
  991. // `MaybeUnformed(T)` might have a pointer value representation when `T`
  992. // does not, so convert as needed when removing `MaybeUnformed`.
  993. bool need_value_binding = false;
  994. if ((removed_quals & SemIR::TypeQualifiers::MaybeUnformed) !=
  995. SemIR::TypeQualifiers::None &&
  996. category == SemIR::ExprCategory::Value) {
  997. auto value_rep =
  998. SemIR::ValueRepr::ForType(context.sem_ir(), value_type_id);
  999. auto unformed_value_rep =
  1000. SemIR::ValueRepr::ForType(context.sem_ir(), target.type_id);
  1001. if (value_rep.kind != unformed_value_rep.kind) {
  1002. CARBON_CHECK(unformed_value_rep.kind == SemIR::ValueRepr::Pointer);
  1003. value_id = AddInst<SemIR::ValueAsRef>(
  1004. context, loc_id,
  1005. {.type_id = value_type_id, .value_id = value_id});
  1006. need_value_binding = true;
  1007. }
  1008. }
  1009. value_id = AddInst<SemIR::AsCompatible>(
  1010. context, loc_id,
  1011. {.type_id = target.type_id, .source_id = value_id});
  1012. if (need_value_binding) {
  1013. value_id = AddInst<SemIR::AcquireValue>(
  1014. context, loc_id,
  1015. {.type_id = target.type_id, .value_id = value_id});
  1016. }
  1017. return value_id;
  1018. } else {
  1019. // TODO: Produce a custom diagnostic explaining that we can't perform
  1020. // this conversion due to the change in qualifiers and/or the expression
  1021. // category.
  1022. }
  1023. }
  1024. }
  1025. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  1026. // converts to Ui.
  1027. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  1028. if (auto src_tuple_type =
  1029. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  1030. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  1031. value_id, target);
  1032. }
  1033. }
  1034. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  1035. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  1036. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  1037. // to Ui.
  1038. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  1039. if (auto src_struct_type =
  1040. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1041. return ConvertStructToStruct(context, *src_struct_type,
  1042. *target_struct_type, value_id, target);
  1043. }
  1044. }
  1045. // No other conversions apply when the source and destination types are the
  1046. // same.
  1047. if (value_type_id == target.type_id) {
  1048. return value_id;
  1049. }
  1050. // A tuple (T1, T2, ..., Tn) converts to array(T, n) if each Ti converts to T.
  1051. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  1052. if (auto src_tuple_type =
  1053. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  1054. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  1055. value_id, target);
  1056. }
  1057. }
  1058. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  1059. // if it converts to the struct type that is the class's representation type
  1060. // (a struct with the same fields as the class, plus a base field where
  1061. // relevant).
  1062. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  1063. if (auto src_struct_type =
  1064. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1065. if (!context.classes()
  1066. .Get(target_class_type->class_id)
  1067. .adapt_id.has_value()) {
  1068. return ConvertStructToClass(context, *src_struct_type,
  1069. *target_class_type, value_id, target,
  1070. vtable_class_type);
  1071. }
  1072. }
  1073. // An expression of type T converts to U if T is a class derived from U.
  1074. //
  1075. // TODO: Combine this with the qualifiers and adapter conversion logic above
  1076. // to allow qualifiers and inheritance conversions to be performed together.
  1077. if (auto path = ComputeInheritancePath(context, loc_id, value_type_id,
  1078. target.type_id);
  1079. path && !path->empty()) {
  1080. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  1081. }
  1082. }
  1083. // A pointer T* converts to [qualified] U* if T is the same as U, or is a
  1084. // class derived from U.
  1085. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  1086. if (auto src_pointer_type =
  1087. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  1088. auto target_pointee_id = context.types().GetTypeIdForTypeInstId(
  1089. target_pointer_type->pointee_id);
  1090. auto src_pointee_id =
  1091. context.types().GetTypeIdForTypeInstId(src_pointer_type->pointee_id);
  1092. // Try to complete the pointee types so that we can walk through adapters
  1093. // to their adapted types.
  1094. TryToCompleteType(context, target_pointee_id, loc_id);
  1095. TryToCompleteType(context, src_pointee_id, loc_id);
  1096. auto [unqual_target_pointee_type_id, target_quals] =
  1097. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(target_pointee_id);
  1098. auto [unqual_src_pointee_type_id, src_quals] =
  1099. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(src_pointee_id);
  1100. // If the qualifiers are incompatible, we can't perform a conversion,
  1101. // except with `unsafe as`.
  1102. if ((src_quals & ~target_quals) != SemIR::TypeQualifiers::None &&
  1103. target.kind != ConversionTarget::ExplicitUnsafeAs) {
  1104. // TODO: Consider producing a custom diagnostic here for a cast that
  1105. // discards constness.
  1106. return value_id;
  1107. }
  1108. if (unqual_target_pointee_type_id != unqual_src_pointee_type_id) {
  1109. // If there's an inheritance path from target to source, this is a
  1110. // derived to base conversion.
  1111. if (auto path = ComputeInheritancePath(context, loc_id,
  1112. unqual_src_pointee_type_id,
  1113. unqual_target_pointee_type_id);
  1114. path && !path->empty()) {
  1115. value_id = ConvertDerivedPointerToBasePointer(
  1116. context, loc_id, *src_pointer_type, target.type_id, value_id,
  1117. *path);
  1118. } else {
  1119. // No conversion was possible.
  1120. return value_id;
  1121. }
  1122. }
  1123. // Perform a compatible conversion to add any new qualifiers.
  1124. if (src_quals != target_quals) {
  1125. return AddInst<SemIR::AsCompatible>(
  1126. context, loc_id,
  1127. {.type_id = target.type_id, .source_id = value_id});
  1128. }
  1129. return value_id;
  1130. }
  1131. }
  1132. if (sem_ir.types().IsFacetType(target.type_id)) {
  1133. auto type_value_id = SemIR::TypeInstId::None;
  1134. // A tuple of types converts to type `type`.
  1135. if (sem_ir.types().Is<SemIR::TupleType>(value_type_id)) {
  1136. type_value_id =
  1137. ConvertTupleToType(context, loc_id, value_id, value_type_id, target);
  1138. }
  1139. // `{}` converts to `{} as type`.
  1140. if (auto struct_type =
  1141. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1142. if (struct_type->fields_id == SemIR::StructTypeFieldsId::Empty) {
  1143. type_value_id = sem_ir.types().GetInstId(value_type_id);
  1144. }
  1145. }
  1146. if (type_value_id != SemIR::InstId::None) {
  1147. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1148. // Use the converted `TypeType` value for converting to a facet.
  1149. value_id = type_value_id;
  1150. value_type_id = SemIR::TypeType::TypeId;
  1151. } else {
  1152. // We wanted a `TypeType`, and we've done that.
  1153. return type_value_id;
  1154. }
  1155. }
  1156. }
  1157. // FacetType converts to Type by wrapping the facet value in
  1158. // FacetAccessType.
  1159. if (target.type_id == SemIR::TypeType::TypeId &&
  1160. sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1161. return AddInst<SemIR::FacetAccessType>(
  1162. context, loc_id,
  1163. {.type_id = target.type_id, .facet_value_inst_id = value_id});
  1164. }
  1165. // Type values can convert to facet values, and facet values can convert to
  1166. // other facet values, as long as they satisfy the required interfaces of the
  1167. // target `FacetType`.
  1168. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id) &&
  1169. sem_ir.types().IsOneOf<SemIR::TypeType, SemIR::FacetType>(
  1170. value_type_id)) {
  1171. // TODO: Runtime facet values should be allowed to convert based on their
  1172. // FacetTypes, but we assume constant values for impl lookup at the moment.
  1173. if (!context.constant_values().Get(value_id).is_constant()) {
  1174. context.TODO(loc_id, "conversion of runtime facet value");
  1175. return SemIR::ErrorInst::InstId;
  1176. }
  1177. // Get the canonical type for which we want to attach a new set of witnesses
  1178. // to match the requirements of the target FacetType.
  1179. auto type_inst_id = SemIR::TypeInstId::None;
  1180. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1181. type_inst_id = AddTypeInst<SemIR::FacetAccessType>(
  1182. context, loc_id,
  1183. {.type_id = SemIR::TypeType::TypeId,
  1184. .facet_value_inst_id = value_id});
  1185. } else {
  1186. type_inst_id = context.types().GetAsTypeInstId(value_id);
  1187. // Shortcut for lossless round trips through a FacetAccessType (which
  1188. // evaluates to SymbolicBindingType when wrapping a symbolic binding) when
  1189. // converting back to the type of the original symbolic binding facet
  1190. // value.
  1191. //
  1192. // In the case where the FacetAccessType wraps a SymbolicBinding with the
  1193. // exact facet type that we are converting to, the resulting FacetValue
  1194. // would evaluate back to the original SymbolicBinding as its canonical
  1195. // form. We can skip past the whole impl lookup step then and do that
  1196. // here.
  1197. //
  1198. // TODO: This instruction is going to become a `SymbolicBindingType`, so
  1199. // we'll need to handle that instead.
  1200. auto facet_value_inst_id =
  1201. GetCanonicalFacetOrTypeValue(context, type_inst_id);
  1202. if (sem_ir.insts().Get(facet_value_inst_id).type_id() == target.type_id) {
  1203. return facet_value_inst_id;
  1204. }
  1205. }
  1206. // Conversion from a facet value (which has type `FacetType`) or a type
  1207. // value (which has type `TypeType`) to a facet value. We can do this if the
  1208. // type satisfies the requirements of the target `FacetType`, as determined
  1209. // by finding impl witnesses for the target FacetType.
  1210. auto lookup_result = LookupImplWitness(
  1211. context, loc_id, sem_ir.constant_values().Get(type_inst_id),
  1212. sem_ir.types().GetConstantId(target.type_id));
  1213. if (lookup_result.has_value()) {
  1214. if (lookup_result.has_error_value()) {
  1215. return SemIR::ErrorInst::InstId;
  1216. } else {
  1217. // Note that `FacetValue`'s type is the same `FacetType` that was used
  1218. // to construct the set of witnesses, ie. the query to
  1219. // `LookupImplWitness()`. This ensures that the witnesses are in the
  1220. // same order as the `required_impls()` in the `IdentifiedFacetType` of
  1221. // the `FacetValue`'s type.
  1222. return AddInst<SemIR::FacetValue>(
  1223. context, loc_id,
  1224. {.type_id = target.type_id,
  1225. .type_inst_id = type_inst_id,
  1226. .witnesses_block_id = lookup_result.inst_block_id()});
  1227. }
  1228. } else {
  1229. // If impl lookup fails, don't keep looking for another way to convert.
  1230. // See https://github.com/carbon-language/carbon-lang/issues/5122.
  1231. // TODO: Pass this function into `LookupImplWitness` so it can construct
  1232. // the error add notes explaining failure.
  1233. if (target.diagnose) {
  1234. DiagnoseConversionFailureToConstraintValue(context, loc_id, value_id,
  1235. target.type_id);
  1236. }
  1237. return SemIR::ErrorInst::InstId;
  1238. }
  1239. }
  1240. // No builtin conversion applies.
  1241. return value_id;
  1242. }
  1243. // Determine whether this is a C++ enum type.
  1244. // TODO: This should be removed once we can properly add a `Copy` impl for C++
  1245. // enum types.
  1246. static auto IsCppEnum(Context& context, SemIR::TypeId type_id) -> bool {
  1247. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  1248. if (!class_type) {
  1249. return false;
  1250. }
  1251. // A C++-imported class type that is an adapter is an enum.
  1252. auto& class_info = context.classes().Get(class_type->class_id);
  1253. return class_info.adapt_id.has_value() &&
  1254. context.name_scopes().Get(class_info.scope_id).is_cpp_scope();
  1255. }
  1256. // Given a value expression, form a corresponding initializer that copies from
  1257. // that value to the specified target, if it is possible to do so.
  1258. static auto PerformCopy(Context& context, SemIR::InstId expr_id,
  1259. ConversionTarget& target) -> SemIR::InstId {
  1260. // TODO: We don't have a mechanism yet to generate `Copy` impls for each enum
  1261. // type imported from C++. For now we fake it by providing a direct copy.
  1262. auto type_id = context.insts().Get(expr_id).type_id();
  1263. if (IsCppEnum(context, type_id)) {
  1264. return expr_id;
  1265. }
  1266. auto copy_id = BuildUnaryOperator(
  1267. context, SemIR::LocId(expr_id), {.interface_name = CoreIdentifier::Copy},
  1268. expr_id, [&] {
  1269. if (!target.diagnose) {
  1270. return context.emitter().BuildSuppressed();
  1271. }
  1272. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  1273. "cannot copy value of type {0}", TypeOfInstId);
  1274. return context.emitter().Build(expr_id, CopyOfUncopyableType, expr_id);
  1275. });
  1276. MarkInitializerFor(context.sem_ir(), copy_id, target);
  1277. return copy_id;
  1278. }
  1279. // Convert a value expression so that it can be used to initialize a C++ thunk
  1280. // parameter.
  1281. static auto ConvertValueForCppThunkRef(Context& context, SemIR::InstId expr_id)
  1282. -> SemIR::InstId {
  1283. auto expr = context.insts().Get(expr_id);
  1284. // If the expression has a pointer value representation, extract that and use
  1285. // it directly.
  1286. if (SemIR::ValueRepr::ForType(context.sem_ir(), expr.type_id()).kind ==
  1287. SemIR::ValueRepr::Pointer) {
  1288. return AddInst<SemIR::ValueAsRef>(
  1289. context, SemIR::LocId(expr_id),
  1290. {.type_id = expr.type_id(), .value_id = expr_id});
  1291. }
  1292. // Otherwise, we need a temporary to pass as the thunk argument. Create a copy
  1293. // and initialize a temporary from it.
  1294. auto temporary_id = AddInst<SemIR::TemporaryStorage>(
  1295. context, SemIR::LocId(expr_id), {.type_id = expr.type_id()});
  1296. expr_id = Initialize(context, SemIR::LocId(expr_id), temporary_id, expr_id);
  1297. return AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(expr_id),
  1298. {.type_id = expr.type_id(),
  1299. .storage_id = temporary_id,
  1300. .init_id = expr_id});
  1301. }
  1302. // Returns the Core interface name to use for a given kind of conversion.
  1303. static auto GetConversionInterfaceName(ConversionTarget::Kind kind)
  1304. -> CoreIdentifier {
  1305. switch (kind) {
  1306. case ConversionTarget::ExplicitAs:
  1307. return CoreIdentifier::As;
  1308. case ConversionTarget::ExplicitUnsafeAs:
  1309. return CoreIdentifier::UnsafeAs;
  1310. default:
  1311. return CoreIdentifier::ImplicitAs;
  1312. }
  1313. }
  1314. auto PerformAction(Context& context, SemIR::LocId loc_id,
  1315. SemIR::ConvertToValueAction action) -> SemIR::InstId {
  1316. return Convert(context, loc_id, action.inst_id,
  1317. {.kind = ConversionTarget::Value,
  1318. .type_id = context.types().GetTypeIdForTypeInstId(
  1319. action.target_type_inst_id)});
  1320. }
  1321. // State machine for performing category conversions.
  1322. class CategoryConverter {
  1323. public:
  1324. // Constructs a converter which converts an expression at the given location
  1325. // to the given conversion target. performed_builtin_conversion indicates
  1326. // whether builtin conversions were performed prior to this.
  1327. CategoryConverter(Context& context, SemIR::LocId loc_id,
  1328. ConversionTarget& target, bool performed_builtin_conversion)
  1329. : context_(context),
  1330. sem_ir_(context.sem_ir()),
  1331. loc_id_(loc_id),
  1332. target_(target),
  1333. performed_builtin_conversion_(performed_builtin_conversion) {}
  1334. // Converts expr_id to the target specified in the constructor, and returns
  1335. // the converted inst.
  1336. auto Convert(SemIR::InstId expr_id) && -> SemIR::InstId {
  1337. auto category = SemIR::GetExprCategory(sem_ir_, expr_id);
  1338. while (true) {
  1339. if (expr_id == SemIR::ErrorInst::InstId) {
  1340. return expr_id;
  1341. }
  1342. CARBON_KIND_SWITCH(DoStep(expr_id, category)) {
  1343. case CARBON_KIND(NextStep next_step): {
  1344. CARBON_CHECK(next_step.expr_id != SemIR::InstId::None);
  1345. expr_id = next_step.expr_id;
  1346. category = next_step.category;
  1347. break;
  1348. }
  1349. case CARBON_KIND(Done done): {
  1350. return done.expr_id;
  1351. }
  1352. }
  1353. }
  1354. }
  1355. private:
  1356. // State that indicates there's more work to be done. As a convenience,
  1357. // if expr_id is SemIR::ErrorInst::InstId, this is equivalent to
  1358. // Done{SemIR::ErrorInst::InstId}.
  1359. struct NextStep {
  1360. // The inst to convert.
  1361. SemIR::InstId expr_id;
  1362. // The category of expr_id.
  1363. SemIR::ExprCategory category;
  1364. };
  1365. // State that indicates we've finished category conversion.
  1366. struct Done {
  1367. // The result of the conversion.
  1368. SemIR::InstId expr_id;
  1369. };
  1370. using State = std::variant<NextStep, Done>;
  1371. // Performs the first step of converting `expr_id` with category `category`
  1372. // to the target specified in the constructor, and returns the state after
  1373. // that step.
  1374. auto DoStep(SemIR::InstId expr_id, SemIR::ExprCategory category) const
  1375. -> State;
  1376. Context& context_;
  1377. SemIR::File& sem_ir_;
  1378. SemIR::LocId loc_id_;
  1379. ConversionTarget& target_;
  1380. bool performed_builtin_conversion_;
  1381. };
  1382. auto CategoryConverter::DoStep(const SemIR::InstId expr_id,
  1383. const SemIR::ExprCategory category) const
  1384. -> State {
  1385. CARBON_DCHECK(SemIR::GetExprCategory(sem_ir_, expr_id) == category);
  1386. switch (category) {
  1387. case SemIR::ExprCategory::NotExpr:
  1388. case SemIR::ExprCategory::Mixed:
  1389. case SemIR::ExprCategory::Pattern:
  1390. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  1391. sem_ir_.insts().Get(expr_id));
  1392. case SemIR::ExprCategory::Error:
  1393. return Done{SemIR::ErrorInst::InstId};
  1394. case SemIR::ExprCategory::Initializing:
  1395. if (target_.is_initializer()) {
  1396. if (!performed_builtin_conversion_) {
  1397. // Don't fill in the return slot if we created the expression through
  1398. // a builtin conversion. In that case, we will have created it with
  1399. // the target already set.
  1400. // TODO: Find a better way to track whether we need to do this,
  1401. // and then make target_ immutable if possible.
  1402. MarkInitializerFor(sem_ir_, expr_id, target_);
  1403. }
  1404. return Done{expr_id};
  1405. }
  1406. // Commit to using a temporary for this initializing expression.
  1407. // TODO: Don't create a temporary if the initializing representation
  1408. // is already a value representation.
  1409. // TODO: If the target is DurableRef, materialize a VarStorage instead of
  1410. // a TemporaryStorage to lifetime-extend.
  1411. if (target_.kind == ConversionTarget::Discarded) {
  1412. return Done{FinalizeTemporary(context_, expr_id, /*discarded=*/true)};
  1413. } else {
  1414. return NextStep{.expr_id = FinalizeTemporary(context_, expr_id,
  1415. /*discarded=*/false),
  1416. .category = SemIR::ExprCategory::EphemeralRef};
  1417. }
  1418. case SemIR::ExprCategory::RefTagged: {
  1419. auto tagged_expr_id =
  1420. sem_ir_.insts().GetAs<SemIR::RefTagExpr>(expr_id).expr_id;
  1421. auto tagged_expr_category =
  1422. SemIR::GetExprCategory(sem_ir_, tagged_expr_id);
  1423. if (target_.diagnose &&
  1424. tagged_expr_category != SemIR::ExprCategory::DurableRef) {
  1425. CARBON_DIAGNOSTIC(
  1426. RefTagNotDurableRef, Error,
  1427. "expression tagged with `ref` is not a durable reference");
  1428. context_.emitter().Emit(tagged_expr_id, RefTagNotDurableRef);
  1429. }
  1430. if (target_.kind == ConversionTarget::RefParam) {
  1431. return Done{expr_id};
  1432. }
  1433. // If the target isn't a reference parameter, ignore the `ref` tag.
  1434. // Unnecessary `ref` tags are diagnosed earlier.
  1435. return NextStep{.expr_id = tagged_expr_id,
  1436. .category = tagged_expr_category};
  1437. }
  1438. case SemIR::ExprCategory::DurableRef:
  1439. if (target_.kind == ConversionTarget::DurableRef ||
  1440. target_.kind == ConversionTarget::UnmarkedRefParam) {
  1441. return Done{expr_id};
  1442. }
  1443. if (target_.kind == ConversionTarget::RefParam) {
  1444. if (target_.diagnose) {
  1445. CARBON_DIAGNOSTIC(
  1446. RefParamNoRefTag, Error,
  1447. "argument to `ref` parameter not marked with `ref`");
  1448. context_.emitter().Emit(expr_id, RefParamNoRefTag);
  1449. }
  1450. return Done{expr_id};
  1451. }
  1452. [[fallthrough]];
  1453. case SemIR::ExprCategory::EphemeralRef:
  1454. // If a reference expression is an acceptable result, we're done.
  1455. if (target_.kind == ConversionTarget::ValueOrRef ||
  1456. target_.kind == ConversionTarget::Discarded ||
  1457. target_.kind == ConversionTarget::CppThunkRef ||
  1458. target_.kind == ConversionTarget::RefParam ||
  1459. target_.kind == ConversionTarget::UnmarkedRefParam) {
  1460. return Done{expr_id};
  1461. }
  1462. // If we have a reference and don't want one, form a value binding.
  1463. // TODO: Support types with custom value representations.
  1464. return NextStep{.expr_id = AddInst<SemIR::AcquireValue>(
  1465. context_, SemIR::LocId(expr_id),
  1466. {.type_id = target_.type_id, .value_id = expr_id}),
  1467. .category = SemIR::ExprCategory::Value};
  1468. case SemIR::ExprCategory::Value:
  1469. if (target_.kind == ConversionTarget::DurableRef) {
  1470. if (target_.diagnose) {
  1471. CARBON_DIAGNOSTIC(ConversionFailureNonRefToRef, Error,
  1472. "cannot bind durable reference to non-reference "
  1473. "value of type {0}",
  1474. SemIR::TypeId);
  1475. context_.emitter().Emit(loc_id_, ConversionFailureNonRefToRef,
  1476. target_.type_id);
  1477. }
  1478. return Done{SemIR::ErrorInst::InstId};
  1479. }
  1480. if (target_.kind == ConversionTarget::RefParam ||
  1481. target_.kind == ConversionTarget::UnmarkedRefParam) {
  1482. if (target_.diagnose) {
  1483. CARBON_DIAGNOSTIC(ValueForRefParam, Error,
  1484. "value expression passed to reference parameter");
  1485. context_.emitter().Emit(loc_id_, ValueForRefParam);
  1486. }
  1487. return Done{SemIR::ErrorInst::InstId};
  1488. }
  1489. // When initializing from a value, perform a copy.
  1490. if (target_.is_initializer()) {
  1491. return Done{PerformCopy(context_, expr_id, target_)};
  1492. }
  1493. // When initializing a C++ thunk parameter, form a reference, creating a
  1494. // temporary if needed.
  1495. if (target_.kind == ConversionTarget::CppThunkRef) {
  1496. return Done{ConvertValueForCppThunkRef(context_, expr_id)};
  1497. }
  1498. return Done{expr_id};
  1499. }
  1500. }
  1501. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  1502. ConversionTarget target, SemIR::ClassType* vtable_class_type)
  1503. -> SemIR::InstId {
  1504. auto& sem_ir = context.sem_ir();
  1505. auto orig_expr_id = expr_id;
  1506. // Start by making sure both sides are non-errors. If any part is an error,
  1507. // the result is an error and we shouldn't diagnose.
  1508. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::ErrorInst::TypeId ||
  1509. target.type_id == SemIR::ErrorInst::TypeId) {
  1510. return SemIR::ErrorInst::InstId;
  1511. }
  1512. auto starting_category = SemIR::GetExprCategory(sem_ir, expr_id);
  1513. if (starting_category == SemIR::ExprCategory::NotExpr) {
  1514. // TODO: We currently encounter this for use of namespaces and functions.
  1515. // We should provide a better diagnostic for inappropriate use of
  1516. // namespace names, and allow use of functions as values.
  1517. if (target.diagnose) {
  1518. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  1519. "expression cannot be used as a value");
  1520. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  1521. }
  1522. return SemIR::ErrorInst::InstId;
  1523. }
  1524. // Diagnose unnecessary `ref` tags early, so that they're not obscured by
  1525. // conversions.
  1526. if (starting_category == SemIR::ExprCategory::RefTagged &&
  1527. target.kind != ConversionTarget::RefParam && target.diagnose) {
  1528. CARBON_DIAGNOSTIC(RefTagNoRefParam, Error,
  1529. "`ref` tag is not an argument to a `ref` parameter");
  1530. context.emitter().Emit(expr_id, RefTagNoRefParam);
  1531. }
  1532. // We can only perform initialization for complete, non-abstract types. Note
  1533. // that `RequireConcreteType` returns true for facet types, since their
  1534. // representation is fixed. This allows us to support using the `Self` of an
  1535. // interface inside its definition.
  1536. if (!RequireConcreteType(
  1537. context, target.type_id, loc_id,
  1538. [&] {
  1539. CARBON_CHECK(!target.is_initializer(),
  1540. "Initialization of incomplete types is expected to be "
  1541. "caught elsewhere.");
  1542. if (!target.diagnose) {
  1543. return context.emitter().BuildSuppressed();
  1544. }
  1545. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  1546. "forming value of incomplete type {0}",
  1547. SemIR::TypeId);
  1548. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  1549. "invalid use of incomplete type {0}",
  1550. SemIR::TypeId);
  1551. return context.emitter().Build(
  1552. loc_id,
  1553. target.kind == ConversionTarget::Value
  1554. ? IncompleteTypeInValueConversion
  1555. : IncompleteTypeInConversion,
  1556. target.type_id);
  1557. },
  1558. [&] {
  1559. if (!target.diagnose || !target.is_initializer()) {
  1560. return context.emitter().BuildSuppressed();
  1561. }
  1562. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  1563. "initialization of abstract type {0}",
  1564. SemIR::TypeId);
  1565. return context.emitter().Build(loc_id, AbstractTypeInInit,
  1566. target.type_id);
  1567. })) {
  1568. return SemIR::ErrorInst::InstId;
  1569. }
  1570. if (target.kind != ConversionTarget::FullInitializer &&
  1571. (target.kind != ConversionTarget::Initializer ||
  1572. !SemIR::InitRepr::ForType(context.sem_ir(), target.type_id)
  1573. .MightBeInPlace())) {
  1574. // storage_id should only be used for a FullInitializer, or an Initializer
  1575. // if the type has an in-place init representation. This ensures we don't
  1576. // accidentally use it for anything else.
  1577. target.storage_id = SemIR::InstId::None;
  1578. }
  1579. // The source type doesn't need to be complete, but its completeness can
  1580. // affect the result. For example, we don't know what type it adapts or
  1581. // derives from unless it's complete.
  1582. // TODO: Is there a risk of coherence problems if the source type is
  1583. // incomplete, but a conversion would have been possible or would have behaved
  1584. // differently if it were complete?
  1585. TryToCompleteType(context, context.insts().Get(expr_id).type_id(), loc_id);
  1586. // Check whether any builtin conversion applies.
  1587. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target,
  1588. vtable_class_type);
  1589. if (expr_id == SemIR::ErrorInst::InstId) {
  1590. return expr_id;
  1591. }
  1592. bool performed_builtin_conversion = expr_id != orig_expr_id;
  1593. // Defer the action if it's dependent. We do this now rather than before
  1594. // attempting any conversion so that we can still perform builtin conversions
  1595. // on dependent arguments. This matters for things like converting a
  1596. // `template T:! SomeInterface` to `type`, where it's important to form a
  1597. // `FacetAccessType` when checking the template. But when running the action
  1598. // later, we need to try builtin conversions again, because one may apply that
  1599. // didn't apply in the template definition.
  1600. // TODO: Support this for targets other than `Value`.
  1601. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id &&
  1602. target.kind == ConversionTarget::Value &&
  1603. (OperandIsDependent(context, expr_id) ||
  1604. OperandIsDependent(context, target.type_id))) {
  1605. auto target_type_inst_id = context.types().GetInstId(target.type_id);
  1606. return AddDependentActionSplice(
  1607. context, loc_id,
  1608. SemIR::ConvertToValueAction{
  1609. .type_id = GetSingletonType(context, SemIR::InstType::TypeInstId),
  1610. .inst_id = expr_id,
  1611. .target_type_inst_id = target_type_inst_id},
  1612. target_type_inst_id);
  1613. }
  1614. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  1615. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  1616. SemIR::InstId interface_args[] = {
  1617. context.types().GetInstId(target.type_id)};
  1618. Operator op = {
  1619. .interface_name = GetConversionInterfaceName(target.kind),
  1620. .interface_args_ref = interface_args,
  1621. .op_name = CoreIdentifier::Convert,
  1622. };
  1623. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  1624. if (!target.diagnose) {
  1625. return context.emitter().BuildSuppressed();
  1626. }
  1627. int target_kind_for_diag =
  1628. target.kind == ConversionTarget::ExplicitAs ? 1
  1629. : target.kind == ConversionTarget::ExplicitUnsafeAs ? 2
  1630. : 0;
  1631. if (target.type_id == SemIR::TypeType::TypeId ||
  1632. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1633. CARBON_DIAGNOSTIC(
  1634. ConversionFailureNonTypeToFacet, Error,
  1635. "cannot{0:=0: implicitly|:} convert non-type value of type {1} "
  1636. "{2:to|into type implementing} {3}"
  1637. "{0:=1: with `as`|=2: with `unsafe as`|:}",
  1638. Diagnostics::IntAsSelect, TypeOfInstId, Diagnostics::BoolAsSelect,
  1639. SemIR::TypeId);
  1640. return context.emitter().Build(
  1641. loc_id, ConversionFailureNonTypeToFacet, target_kind_for_diag,
  1642. expr_id, target.type_id == SemIR::TypeType::TypeId, target.type_id);
  1643. } else {
  1644. CARBON_DIAGNOSTIC(
  1645. ConversionFailure, Error,
  1646. "cannot{0:=0: implicitly|:} convert expression of type "
  1647. "{1} to {2}{0:=1: with `as`|=2: with `unsafe as`|:}",
  1648. Diagnostics::IntAsSelect, TypeOfInstId, SemIR::TypeId);
  1649. return context.emitter().Build(loc_id, ConversionFailure,
  1650. target_kind_for_diag, expr_id,
  1651. target.type_id);
  1652. }
  1653. });
  1654. // Pull a value directly out of the initializer if possible and wanted.
  1655. if (expr_id != SemIR::ErrorInst::InstId &&
  1656. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  1657. expr_id = AddInst<SemIR::ValueOfInitializer>(
  1658. context, loc_id, {.type_id = target.type_id, .init_id = expr_id});
  1659. }
  1660. }
  1661. // Track that we performed a type conversion, if we did so.
  1662. if (orig_expr_id != expr_id) {
  1663. expr_id = AddInst<SemIR::Converted>(context, loc_id,
  1664. {.type_id = target.type_id,
  1665. .original_id = orig_expr_id,
  1666. .result_id = expr_id});
  1667. }
  1668. // For `as`, don't perform any value category conversions. In particular, an
  1669. // identity conversion shouldn't change the expression category.
  1670. if (target.is_explicit_as()) {
  1671. return expr_id;
  1672. }
  1673. // Now perform any necessary value category conversions.
  1674. expr_id =
  1675. CategoryConverter(context, loc_id, target, performed_builtin_conversion)
  1676. .Convert(expr_id);
  1677. // Perform a final destination store, if necessary.
  1678. if (target.kind == ConversionTarget::FullInitializer) {
  1679. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1680. init_rep.MightBeByCopy()) {
  1681. target.storage_access_block->InsertHere();
  1682. expr_id = AddInst<SemIR::InitializeFrom>(context, loc_id,
  1683. {.type_id = target.type_id,
  1684. .src_id = expr_id,
  1685. .dest_id = target.storage_id});
  1686. }
  1687. }
  1688. return expr_id;
  1689. }
  1690. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId storage_id,
  1691. SemIR::InstId value_id) -> SemIR::InstId {
  1692. PendingBlock target_block(&context);
  1693. return Convert(context, loc_id, value_id,
  1694. {.kind = ConversionTarget::Initializer,
  1695. .type_id = context.insts().Get(storage_id).type_id(),
  1696. .storage_id = storage_id,
  1697. .storage_access_block = &target_block});
  1698. }
  1699. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1700. -> SemIR::InstId {
  1701. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1702. {.kind = ConversionTarget::Value,
  1703. .type_id = context.insts().Get(expr_id).type_id()});
  1704. }
  1705. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1706. -> SemIR::InstId {
  1707. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1708. {.kind = ConversionTarget::ValueOrRef,
  1709. .type_id = context.insts().Get(expr_id).type_id()});
  1710. }
  1711. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1712. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1713. -> SemIR::InstId {
  1714. return Convert(context, loc_id, expr_id,
  1715. {.kind = ConversionTarget::Value, .type_id = type_id});
  1716. }
  1717. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1718. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1719. -> SemIR::InstId {
  1720. return Convert(context, loc_id, expr_id,
  1721. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1722. }
  1723. // Like ConvertToValueOfType but failure to convert does not result in
  1724. // diagnostics. An ErrorInst instruction is still returned on failure.
  1725. auto TryConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1726. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1727. -> SemIR::InstId {
  1728. return Convert(
  1729. context, loc_id, expr_id,
  1730. {.kind = ConversionTarget::Value, .type_id = type_id, .diagnose = false});
  1731. }
  1732. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1733. SemIR::InstId value_id) -> SemIR::InstId {
  1734. return ConvertToValueOfType(
  1735. context, loc_id, value_id,
  1736. GetSingletonType(context, SemIR::BoolType::TypeInstId));
  1737. }
  1738. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1739. SemIR::InstId value_id, SemIR::TypeId type_id,
  1740. bool unsafe) -> SemIR::InstId {
  1741. return Convert(context, as_node, value_id,
  1742. {.kind = unsafe ? ConversionTarget::ExplicitUnsafeAs
  1743. : ConversionTarget::ExplicitAs,
  1744. .type_id = type_id});
  1745. }
  1746. // TODO: Consider moving this to pattern_match.h.
  1747. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1748. SemIR::InstId self_id,
  1749. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1750. llvm::ArrayRef<SemIR::InstId> return_arg_ids,
  1751. const SemIR::Function& callee,
  1752. SemIR::SpecificId callee_specific_id,
  1753. bool is_operator_syntax) -> SemIR::InstBlockId {
  1754. auto param_patterns =
  1755. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1756. auto return_patterns_id = callee.return_patterns_id;
  1757. // The caller should have ensured this callee has the right arity.
  1758. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1759. if (callee.self_param_id.has_value() && !self_id.has_value()) {
  1760. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1761. "missing object argument in method call");
  1762. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1763. context.emitter()
  1764. .Build(call_loc_id, MissingObjectInMethodCall)
  1765. .Note(callee.latest_decl_id(), InCallToFunction)
  1766. .Emit();
  1767. self_id = SemIR::ErrorInst::InstId;
  1768. }
  1769. return CallerPatternMatch(context, callee_specific_id, callee.self_param_id,
  1770. callee.param_patterns_id, return_patterns_id,
  1771. self_id, arg_refs, return_arg_ids,
  1772. is_operator_syntax);
  1773. }
  1774. auto TypeExpr::ForUnsugared(Context& context, SemIR::TypeId type_id)
  1775. -> TypeExpr {
  1776. return {.inst_id = context.types().GetInstId(type_id), .type_id = type_id};
  1777. }
  1778. static auto DiagnoseTypeExprEvaluationFailure(Context& context,
  1779. SemIR::LocId loc_id) -> void {
  1780. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1781. "cannot evaluate type expression");
  1782. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1783. }
  1784. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  1785. bool diagnose) -> TypeExpr {
  1786. auto type_inst_id =
  1787. ConvertToValueOfType(context, loc_id, value_id, SemIR::TypeType::TypeId);
  1788. if (type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1789. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1790. .type_id = SemIR::ErrorInst::TypeId};
  1791. }
  1792. auto type_const_id = context.constant_values().Get(type_inst_id);
  1793. if (!type_const_id.is_constant()) {
  1794. if (diagnose) {
  1795. DiagnoseTypeExprEvaluationFailure(context, loc_id);
  1796. }
  1797. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1798. .type_id = SemIR::ErrorInst::TypeId};
  1799. }
  1800. return {.inst_id = context.types().GetAsTypeInstId(type_inst_id),
  1801. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1802. }
  1803. auto ExprAsReturnForm(Context& context, SemIR::LocId loc_id,
  1804. SemIR::InstId value_id) -> Context::FormExpr {
  1805. constexpr Context::FormExpr ErrorFormExpr = {
  1806. .form_inst_id = SemIR::ErrorInst::InstId,
  1807. .type_component_id = SemIR::ErrorInst::TypeInstId,
  1808. .type_id = SemIR::ErrorInst::TypeId};
  1809. auto form_inst_id = SemIR::InstId::None;
  1810. auto type_inst_id = SemIR::InstId::None;
  1811. if (auto ref_tag = context.insts().TryGetAs<SemIR::RefTagExpr>(value_id)) {
  1812. type_inst_id = ConvertToValueOfType(context, loc_id, ref_tag->expr_id,
  1813. SemIR::TypeType::TypeId);
  1814. if (type_inst_id == SemIR::ErrorInst::InstId) {
  1815. return ErrorFormExpr;
  1816. }
  1817. if (!context.constant_values().Get(type_inst_id).is_constant()) {
  1818. DiagnoseTypeExprEvaluationFailure(context,
  1819. SemIR::LocId(ref_tag->expr_id));
  1820. return ErrorFormExpr;
  1821. }
  1822. form_inst_id = AddInst(
  1823. context,
  1824. SemIR::LocIdAndInst::UncheckedLoc(
  1825. loc_id,
  1826. SemIR::RefForm{.type_id = SemIR::FormType::TypeId,
  1827. .type_component_inst_id =
  1828. context.types().GetAsTypeInstId(type_inst_id)}));
  1829. } else {
  1830. type_inst_id = ConvertToValueOfType(context, loc_id, value_id,
  1831. SemIR::TypeType::TypeId);
  1832. if (type_inst_id == SemIR::ErrorInst::InstId) {
  1833. return ErrorFormExpr;
  1834. }
  1835. if (!context.constant_values().Get(type_inst_id).is_constant()) {
  1836. DiagnoseTypeExprEvaluationFailure(context, loc_id);
  1837. return ErrorFormExpr;
  1838. }
  1839. form_inst_id = AddInst(
  1840. context,
  1841. SemIR::LocIdAndInst::UncheckedLoc(
  1842. loc_id,
  1843. SemIR::InitForm{
  1844. .type_id = SemIR::FormType::TypeId,
  1845. .type_component_inst_id =
  1846. context.types().GetAsTypeInstId(type_inst_id),
  1847. .index = context.full_pattern_stack().NextCallParamIndex()}));
  1848. }
  1849. auto type_const_id = context.constant_values().Get(type_inst_id);
  1850. CARBON_CHECK(type_const_id.is_constant());
  1851. return {.form_inst_id = form_inst_id,
  1852. .type_component_id = context.types().GetAsTypeInstId(type_inst_id),
  1853. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1854. }
  1855. auto DiscardExpr(Context& context, SemIR::InstId expr_id) -> void {
  1856. // If we discard an initializing expression, convert it to a value or
  1857. // reference so that it has something to initialize.
  1858. auto expr = context.insts().Get(expr_id);
  1859. Convert(context, SemIR::LocId(expr_id), expr_id,
  1860. {.kind = ConversionTarget::Discarded, .type_id = expr.type_id()});
  1861. // TODO: This will eventually need to do some "do not discard" analysis.
  1862. }
  1863. } // namespace Carbon::Check
  1864. // NOLINTEND(misc-no-recursion)