convert.cpp 76 KB

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