convert.cpp 78 KB

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