convert.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875
  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. // Converts a tuple of elements that are convertible to `type` into a `type`
  371. // that is a tuple of types.
  372. static auto ConvertTupleToType(Context& context, SemIR::LocId loc_id,
  373. SemIR::InstId value_id,
  374. SemIR::TypeId value_type_id,
  375. ConversionTarget target) -> SemIR::TypeInstId {
  376. auto value_const_id = context.constant_values().Get(value_id);
  377. if (!value_const_id.is_constant()) {
  378. // Types are constants. The input value must have a constant value to
  379. // convert.
  380. return SemIR::TypeInstId::None;
  381. }
  382. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  383. auto value_const_inst_id =
  384. context.constant_values().GetInstId(value_const_id);
  385. if (auto tuple_value =
  386. context.insts().TryGetAs<SemIR::TupleValue>(value_const_inst_id)) {
  387. for (auto tuple_inst_id :
  388. context.inst_blocks().Get(tuple_value->elements_id)) {
  389. // TODO: This call recurses back into conversion. Switch to an
  390. // iterative approach.
  391. type_inst_ids.push_back(
  392. ExprAsType(context, loc_id, tuple_inst_id, target.diagnose).inst_id);
  393. }
  394. } else {
  395. // A value of type TupleType that isn't a TupleValue must be a symbolic
  396. // binding.
  397. CARBON_CHECK(
  398. context.insts().Is<SemIR::SymbolicBinding>(value_const_inst_id));
  399. // Form a TupleAccess for each element in the symbolic value, which is then
  400. // converted to a `type` or diagnosed as an error.
  401. auto tuple_type = context.types().GetAs<SemIR::TupleType>(value_type_id);
  402. auto type_elements = context.types().GetBlockAsTypeIds(
  403. context.inst_blocks().Get(tuple_type.type_elements_id));
  404. for (auto [i, type_id] : llvm::enumerate(type_elements)) {
  405. auto access_inst_id =
  406. GetOrAddInst<SemIR::TupleAccess>(context, loc_id,
  407. {.type_id = type_id,
  408. .tuple_id = value_id,
  409. .index = SemIR::ElementIndex(i)});
  410. // TODO: This call recurses back into conversion. Switch to an
  411. // iterative approach.
  412. type_inst_ids.push_back(
  413. ExprAsType(context, loc_id, access_inst_id, target.diagnose).inst_id);
  414. }
  415. }
  416. // TODO: Should we add this as an instruction? It will contain
  417. // references to local InstIds.
  418. auto tuple_type_id = GetTupleType(context, type_inst_ids);
  419. return context.types().GetInstId(tuple_type_id);
  420. }
  421. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  422. template <typename TargetAccessInstT>
  423. static auto ConvertStructToStructOrClass(
  424. Context& context, SemIR::StructType src_type, SemIR::StructType dest_type,
  425. SemIR::InstId value_id, ConversionTarget target,
  426. SemIR::ClassType* vtable_class_type = nullptr) -> SemIR::InstId {
  427. static_assert(std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT> ||
  428. std::is_same_v<SemIR::StructAccess, TargetAccessInstT>);
  429. constexpr bool ToClass =
  430. std::is_same_v<SemIR::ClassElementAccess, TargetAccessInstT>;
  431. auto& sem_ir = context.sem_ir();
  432. auto src_elem_fields = sem_ir.struct_type_fields().Get(src_type.fields_id);
  433. auto dest_elem_fields = sem_ir.struct_type_fields().Get(dest_type.fields_id);
  434. bool dest_has_vptr = !dest_elem_fields.empty() &&
  435. dest_elem_fields.front().name_id == SemIR::NameId::Vptr;
  436. int dest_vptr_offset = (dest_has_vptr ? 1 : 0);
  437. auto dest_elem_fields_size = dest_elem_fields.size() - dest_vptr_offset;
  438. auto value = sem_ir.insts().Get(value_id);
  439. SemIR::LocId value_loc_id(value_id);
  440. // If we're initializing from a struct literal, we will use its elements
  441. // directly. Otherwise, materialize a temporary if needed and index into the
  442. // result.
  443. llvm::ArrayRef<SemIR::InstId> literal_elems;
  444. auto literal_elems_id = SemIR::InstBlockId::None;
  445. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  446. literal_elems_id = struct_literal->elements_id;
  447. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  448. } else {
  449. value_id = MaterializeIfInitializing(context, value_id);
  450. }
  451. // Check that the structs are the same size.
  452. // TODO: If not, include the name of the first source field that doesn't
  453. // exist in the destination or vice versa in the diagnostic.
  454. if (src_elem_fields.size() != dest_elem_fields_size) {
  455. if (target.diagnose) {
  456. CARBON_DIAGNOSTIC(
  457. StructInitElementCountMismatch, Error,
  458. "cannot initialize {0:class|struct} with {1} field{1:s} from struct "
  459. "with {2} field{2:s}",
  460. Diagnostics::BoolAsSelect, Diagnostics::IntAsSelect,
  461. Diagnostics::IntAsSelect);
  462. context.emitter().Emit(value_loc_id, StructInitElementCountMismatch,
  463. ToClass, dest_elem_fields_size,
  464. src_elem_fields.size());
  465. }
  466. return SemIR::ErrorInst::InstId;
  467. }
  468. // Prepare to look up fields in the source by index.
  469. Map<SemIR::NameId, int32_t> src_field_indexes;
  470. if (src_type.fields_id != dest_type.fields_id) {
  471. for (auto [i, field] : llvm::enumerate(src_elem_fields)) {
  472. auto result = src_field_indexes.Insert(field.name_id, i);
  473. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  474. }
  475. }
  476. ConversionTarget::Kind inner_kind =
  477. GetAggregateElementConversionTargetKind(sem_ir, target);
  478. // Initialize each element of the destination from the corresponding element
  479. // of the source.
  480. // TODO: Annotate diagnostics coming from here with the element index.
  481. auto new_block =
  482. literal_elems_id.has_value() && !dest_has_vptr
  483. ? SemIR::CopyOnWriteInstBlock(&sem_ir, literal_elems_id)
  484. : SemIR::CopyOnWriteInstBlock(
  485. &sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  486. dest_elem_fields.size()});
  487. for (auto [i, dest_field] : llvm::enumerate(dest_elem_fields)) {
  488. if (dest_field.name_id == SemIR::NameId::Vptr) {
  489. if constexpr (!ToClass) {
  490. CARBON_FATAL("Only classes should have vptrs.");
  491. }
  492. target.init_block->InsertHere();
  493. auto vptr_type_id =
  494. context.types().GetTypeIdForTypeInstId(dest_field.type_inst_id);
  495. auto dest_id =
  496. AddInst<SemIR::ClassElementAccess>(context, value_loc_id,
  497. {.type_id = vptr_type_id,
  498. .base_id = target.init_id,
  499. .index = SemIR::ElementIndex(i)});
  500. auto vtable_decl_id =
  501. context.classes().Get(vtable_class_type->class_id).vtable_decl_id;
  502. LoadImportRef(context, vtable_decl_id);
  503. auto canonical_vtable_decl_id =
  504. context.constant_values().GetConstantInstId(vtable_decl_id);
  505. auto vtable_ptr_id = AddInst<SemIR::VtablePtr>(
  506. context, value_loc_id,
  507. {.type_id = GetPointerType(context, SemIR::VtableType::TypeInstId),
  508. .vtable_id = context.insts()
  509. .GetAs<SemIR::VtableDecl>(canonical_vtable_decl_id)
  510. .vtable_id,
  511. .specific_id = vtable_class_type->specific_id});
  512. auto init_id = AddInst<SemIR::InitializeFrom>(context, value_loc_id,
  513. {.type_id = vptr_type_id,
  514. .src_id = vtable_ptr_id,
  515. .dest_id = dest_id});
  516. new_block.Set(i, init_id);
  517. continue;
  518. }
  519. // Find the matching source field.
  520. auto src_field_index = i;
  521. if (src_type.fields_id != dest_type.fields_id) {
  522. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  523. src_field_index = lookup.value();
  524. } else {
  525. if (target.diagnose) {
  526. if (literal_elems_id.has_value()) {
  527. CARBON_DIAGNOSTIC(
  528. StructInitMissingFieldInLiteral, Error,
  529. "missing value for field `{0}` in struct initialization",
  530. SemIR::NameId);
  531. context.emitter().Emit(value_loc_id,
  532. StructInitMissingFieldInLiteral,
  533. dest_field.name_id);
  534. } else {
  535. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  536. "cannot convert from struct type {0} to {1}: "
  537. "missing field `{2}` in source type",
  538. TypeOfInstId, SemIR::TypeId, SemIR::NameId);
  539. context.emitter().Emit(value_loc_id,
  540. StructInitMissingFieldInConversion, value_id,
  541. target.type_id, dest_field.name_id);
  542. }
  543. }
  544. return SemIR::ErrorInst::InstId;
  545. }
  546. }
  547. auto src_field = src_elem_fields[src_field_index];
  548. // TODO: This call recurses back into conversion. Switch to an iterative
  549. // approach.
  550. auto init_id =
  551. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  552. context, value_loc_id, value_id, src_field.type_inst_id,
  553. literal_elems, inner_kind, target.init_id, dest_field.type_inst_id,
  554. target.init_block, src_field_index,
  555. src_field_index + dest_vptr_offset, vtable_class_type);
  556. if (init_id == SemIR::ErrorInst::InstId) {
  557. return SemIR::ErrorInst::InstId;
  558. }
  559. new_block.Set(i, init_id);
  560. }
  561. bool is_init = target.is_initializer();
  562. if (ToClass) {
  563. target.init_block->InsertHere();
  564. CARBON_CHECK(is_init,
  565. "Converting directly to a class value is not supported");
  566. return AddInst<SemIR::ClassInit>(context, value_loc_id,
  567. {.type_id = target.type_id,
  568. .elements_id = new_block.id(),
  569. .dest_id = target.init_id});
  570. } else if (is_init) {
  571. target.init_block->InsertHere();
  572. return AddInst<SemIR::StructInit>(context, value_loc_id,
  573. {.type_id = target.type_id,
  574. .elements_id = new_block.id(),
  575. .dest_id = target.init_id});
  576. } else {
  577. return AddInst<SemIR::StructValue>(
  578. context, value_loc_id,
  579. {.type_id = target.type_id, .elements_id = new_block.id()});
  580. }
  581. }
  582. // Performs a conversion from a struct to a struct type. This function only
  583. // converts the type, and does not perform a final conversion to the requested
  584. // expression category.
  585. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  586. SemIR::StructType dest_type,
  587. SemIR::InstId value_id,
  588. ConversionTarget target) -> SemIR::InstId {
  589. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  590. context, src_type, dest_type, value_id, target);
  591. }
  592. // Performs a conversion from a struct to a class type. This function only
  593. // converts the type, and does not perform a final conversion to the requested
  594. // expression category.
  595. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  596. SemIR::ClassType dest_type,
  597. SemIR::InstId value_id,
  598. ConversionTarget target,
  599. SemIR::ClassType* vtable_class_type)
  600. -> SemIR::InstId {
  601. PendingBlock target_block(&context);
  602. auto& dest_class_info = context.classes().Get(dest_type.class_id);
  603. CARBON_CHECK(dest_class_info.inheritance_kind != SemIR::Class::Abstract);
  604. auto object_repr_id =
  605. dest_class_info.GetObjectRepr(context.sem_ir(), dest_type.specific_id);
  606. if (object_repr_id == SemIR::ErrorInst::TypeId) {
  607. return SemIR::ErrorInst::InstId;
  608. }
  609. if (context.types().Is<SemIR::CustomLayoutType>(object_repr_id)) {
  610. // Builtin conversion does not apply.
  611. return value_id;
  612. }
  613. auto dest_struct_type =
  614. context.types().GetAs<SemIR::StructType>(object_repr_id);
  615. // If we're trying to create a class value, form a temporary for the value to
  616. // point to.
  617. bool need_temporary = !target.is_initializer();
  618. if (need_temporary) {
  619. target.kind = ConversionTarget::Initializer;
  620. target.init_block = &target_block;
  621. target.init_id = target_block.AddInst<SemIR::TemporaryStorage>(
  622. SemIR::LocId(value_id), {.type_id = target.type_id});
  623. }
  624. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  625. context, src_type, dest_struct_type, value_id, target,
  626. vtable_class_type ? vtable_class_type : &dest_type);
  627. if (need_temporary) {
  628. target_block.InsertHere();
  629. result_id =
  630. AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(value_id),
  631. {.type_id = target.type_id,
  632. .storage_id = target.init_id,
  633. .init_id = result_id});
  634. }
  635. return result_id;
  636. }
  637. // An inheritance path is a sequence of `BaseDecl`s and corresponding base types
  638. // in order from derived to base.
  639. using InheritancePath =
  640. llvm::SmallVector<std::pair<SemIR::InstId, SemIR::TypeId>>;
  641. // Computes the inheritance path from class `derived_id` to class `base_id`.
  642. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  643. static auto ComputeInheritancePath(Context& context, SemIR::LocId loc_id,
  644. SemIR::TypeId derived_id,
  645. SemIR::TypeId base_id)
  646. -> std::optional<InheritancePath> {
  647. // We intend for NRVO to be applied to `result`. All `return` statements in
  648. // this function should `return result;`.
  649. std::optional<InheritancePath> result(std::in_place);
  650. if (!TryToCompleteType(context, derived_id, loc_id)) {
  651. // TODO: Should we give an error here? If we don't, and there is an
  652. // inheritance path when the class is defined, we may have a coherence
  653. // problem.
  654. result = std::nullopt;
  655. return result;
  656. }
  657. while (derived_id != base_id) {
  658. auto derived_class_type =
  659. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  660. if (!derived_class_type) {
  661. result = std::nullopt;
  662. break;
  663. }
  664. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  665. auto base_type_id = derived_class.GetBaseType(
  666. context.sem_ir(), derived_class_type->specific_id);
  667. if (!base_type_id.has_value()) {
  668. result = std::nullopt;
  669. break;
  670. }
  671. result->push_back({derived_class.base_id, base_type_id});
  672. derived_id = base_type_id;
  673. }
  674. return result;
  675. }
  676. // Performs a conversion from a derived class value or reference to a base class
  677. // value or reference.
  678. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  679. SemIR::InstId value_id,
  680. const InheritancePath& path) -> SemIR::InstId {
  681. // Materialize a temporary if necessary.
  682. value_id = ConvertToValueOrRefExpr(context, value_id);
  683. // Preserve type qualifiers.
  684. auto quals = context.types()
  685. .GetUnqualifiedTypeAndQualifiers(
  686. context.insts().Get(value_id).type_id())
  687. .second;
  688. // Add a series of `.base` accesses.
  689. for (auto [base_id, base_type_id] : path) {
  690. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  691. value_id = AddInst<SemIR::ClassElementAccess>(
  692. context, loc_id,
  693. {.type_id = GetQualifiedType(context, base_type_id, quals),
  694. .base_id = value_id,
  695. .index = base_decl.index});
  696. }
  697. return value_id;
  698. }
  699. // Performs a conversion from a derived class pointer to a base class pointer.
  700. static auto ConvertDerivedPointerToBasePointer(
  701. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  702. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  703. const InheritancePath& path) -> SemIR::InstId {
  704. auto pointee_type_id =
  705. context.types().GetTypeIdForTypeInstId(src_ptr_type.pointee_id);
  706. // Form `*p`.
  707. ptr_id = ConvertToValueExpr(context, ptr_id);
  708. auto ref_id = AddInst<SemIR::Deref>(
  709. context, loc_id, {.type_id = pointee_type_id, .pointer_id = ptr_id});
  710. // Convert as a reference expression.
  711. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  712. // Take the address.
  713. return AddInst<SemIR::AddrOf>(
  714. context, loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  715. }
  716. // Returns whether `category` is a valid expression category to produce as a
  717. // result of a conversion with kind `target_kind`.
  718. static auto IsValidExprCategoryForConversionTarget(
  719. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  720. switch (target_kind) {
  721. case ConversionTarget::Value:
  722. return category == SemIR::ExprCategory::Value;
  723. case ConversionTarget::ValueOrRef:
  724. return category == SemIR::ExprCategory::Value ||
  725. category == SemIR::ExprCategory::DurableRef ||
  726. category == SemIR::ExprCategory::EphemeralRef;
  727. case ConversionTarget::Discarded:
  728. return category == SemIR::ExprCategory::Value ||
  729. category == SemIR::ExprCategory::DurableRef ||
  730. category == SemIR::ExprCategory::EphemeralRef ||
  731. category == SemIR::ExprCategory::Initializing;
  732. case ConversionTarget::RefParam:
  733. return category == SemIR::ExprCategory::DurableRef ||
  734. category == SemIR::ExprCategory::EphemeralRef ||
  735. category == SemIR::ExprCategory::Initializing;
  736. case ConversionTarget::DurableRef:
  737. return category == SemIR::ExprCategory::DurableRef;
  738. case ConversionTarget::CppThunkRef:
  739. return category == SemIR::ExprCategory::EphemeralRef;
  740. case ConversionTarget::ExplicitAs:
  741. case ConversionTarget::ExplicitUnsafeAs:
  742. return true;
  743. case ConversionTarget::Initializer:
  744. case ConversionTarget::FullInitializer:
  745. return category == SemIR::ExprCategory::Initializing;
  746. }
  747. }
  748. // Determines whether the initialization representation of the type is a copy of
  749. // the value representation.
  750. static auto InitReprIsCopyOfValueRepr(const SemIR::File& sem_ir,
  751. SemIR::TypeId type_id) -> bool {
  752. // The initializing representation is a copy of the value representation if
  753. // they're both copies of the object representation.
  754. return SemIR::InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  755. SemIR::ValueRepr::ForType(sem_ir, type_id)
  756. .IsCopyOfObjectRepr(sem_ir, type_id);
  757. }
  758. // Determines whether we can pull a value directly out of an initializing
  759. // expression of type `type_id` to initialize a target of type `type_id` and
  760. // kind `target_kind`.
  761. static auto CanUseValueOfInitializer(const SemIR::File& sem_ir,
  762. SemIR::TypeId type_id,
  763. ConversionTarget::Kind target_kind)
  764. -> bool {
  765. if (!IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  766. target_kind)) {
  767. // We don't want a value expression.
  768. return false;
  769. }
  770. // We can pull a value out of an initializing expression if it holds one.
  771. return InitReprIsCopyOfValueRepr(sem_ir, type_id);
  772. }
  773. // Determine whether the given set of qualifiers can be added by a conversion
  774. // of an expression of the given category.
  775. static auto CanAddQualifiers(SemIR::TypeQualifiers quals,
  776. SemIR::ExprCategory cat) -> bool {
  777. if (quals.HasAnyOf(SemIR::TypeQualifiers::MaybeUnformed) &&
  778. !SemIR::IsRefCategory(cat)) {
  779. // `MaybeUnformed(T)` may have a different value representation or
  780. // initializing representation from `T`, so only allow it to be added for a
  781. // reference expression.
  782. // TODO: We should allow converting an initializing expression of type `T`
  783. // to `MaybeUnformed(T)`. `PerformBuiltinConversion` will need to generate
  784. // an `InPlaceInit` instruction when needed.
  785. // NOLINTNEXTLINE(readability-simplify-boolean-expr)
  786. return false;
  787. }
  788. // `const` and `partial` can always be added.
  789. return true;
  790. }
  791. // Determine whether the given set of qualifiers can be removed by a conversion
  792. // of an expression of the given category.
  793. static auto CanRemoveQualifiers(SemIR::TypeQualifiers quals,
  794. SemIR::ExprCategory cat,
  795. ConversionTarget::Kind kind) -> bool {
  796. bool allow_unsafe = kind == ConversionTarget::ExplicitUnsafeAs;
  797. if (quals.HasAnyOf(SemIR::TypeQualifiers::Const) && !allow_unsafe &&
  798. SemIR::IsRefCategory(cat) &&
  799. IsValidExprCategoryForConversionTarget(cat, kind)) {
  800. // Removing `const` is an unsafe conversion for a reference expression. But
  801. // it's OK if we will be converting to a different category as part of this
  802. // overall conversion anyway.
  803. return false;
  804. }
  805. if (quals.HasAnyOf(SemIR::TypeQualifiers::Partial) &&
  806. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  807. // TODO: Allow removing `partial` for initializing expressions as a safe
  808. // conversion. `PerformBuiltinConversion` will need to initialize the vptr
  809. // as part of the conversion.
  810. return false;
  811. }
  812. if (quals.HasAnyOf(SemIR::TypeQualifiers::MaybeUnformed) &&
  813. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  814. // As an unsafe conversion, `MaybeUnformed` can be removed from a value or
  815. // reference expression.
  816. return false;
  817. }
  818. return true;
  819. }
  820. static auto DiagnoseConversionFailureToConstraintValue(
  821. Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  822. SemIR::TypeId target_type_id) -> void {
  823. CARBON_CHECK(context.types().IsFacetType(target_type_id));
  824. // If the source type is/has a facet value (converted with `as type` or
  825. // otherwise), then we can include its `FacetType` in the diagnostic to help
  826. // explain what interfaces the source type implements.
  827. auto const_expr_id = GetCanonicalFacetOrTypeValue(context, expr_id);
  828. auto const_expr_type_id = context.insts().Get(const_expr_id).type_id();
  829. if (context.types().Is<SemIR::FacetType>(const_expr_type_id)) {
  830. CARBON_DIAGNOSTIC(ConversionFailureFacetToFacet, Error,
  831. "cannot convert type {0} that implements {1} into type "
  832. "implementing {2}",
  833. InstIdAsType, SemIR::TypeId, SemIR::TypeId);
  834. context.emitter().Emit(loc_id, ConversionFailureFacetToFacet, expr_id,
  835. const_expr_type_id, target_type_id);
  836. } else {
  837. CARBON_DIAGNOSTIC(ConversionFailureTypeToFacet, Error,
  838. "cannot convert type {0} into type implementing {1}",
  839. InstIdAsType, SemIR::TypeId);
  840. context.emitter().Emit(loc_id, ConversionFailureTypeToFacet, expr_id,
  841. target_type_id);
  842. }
  843. }
  844. static auto PerformBuiltinConversion(
  845. Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  846. ConversionTarget target, SemIR::ClassType* vtable_class_type = nullptr)
  847. -> SemIR::InstId {
  848. auto& sem_ir = context.sem_ir();
  849. auto value = sem_ir.insts().Get(value_id);
  850. auto value_type_id = value.type_id();
  851. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  852. // Various forms of implicit conversion are supported as builtin conversions,
  853. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  854. // prelude. There are a few reasons we need to perform some of these
  855. // conversions as builtins:
  856. //
  857. // 1) Conversions from struct and tuple *literals* have special rules that
  858. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  859. // recurse into the elements of the literal before performing
  860. // initialization in order to avoid unnecessary conversions between
  861. // expression categories that would be performed by `ImplicitAs.Convert`.
  862. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  863. // the value of the facet, not only its type, and therefore cannot be
  864. // modeled by `ImplicitAs`.
  865. // 3) Some of these conversions are used while checking the library
  866. // definition of `ImplicitAs` itself or implementations of it.
  867. //
  868. // We also expect to see better performance by avoiding an `impl` lookup for
  869. // common conversions.
  870. //
  871. // TODO: We should provide a debugging flag to turn off as many of these
  872. // builtin conversions as we can so that we can test that they do the same
  873. // thing as the library implementations.
  874. //
  875. // The builtin conversions that correspond to `impl`s in the library all
  876. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  877. // being specialized in any of these cases.
  878. // If the value is already of the right kind and expression category, there's
  879. // nothing to do. Performing a conversion would decompose and rebuild tuples
  880. // and structs, so it's important that we bail out early in this case.
  881. if (value_type_id == target.type_id) {
  882. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  883. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  884. return value_id;
  885. }
  886. // If the source is an initializing expression, we may be able to pull a
  887. // value right out of it.
  888. if (value_cat == SemIR::ExprCategory::Initializing &&
  889. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  890. return AddInst<SemIR::ValueOfInitializer>(
  891. context, loc_id, {.type_id = value_type_id, .init_id = value_id});
  892. }
  893. // Materialization is handled as part of the enclosing conversion.
  894. if (value_cat == SemIR::ExprCategory::Initializing &&
  895. target.kind == ConversionTarget::ValueOrRef) {
  896. return value_id;
  897. }
  898. // PerformBuiltinConversion converts each part of a tuple or struct, even
  899. // when the types are the same. This is not done for classes since they have
  900. // to define their conversions as part of their api.
  901. //
  902. // If a class adapts a tuple or struct, we convert each of its parts when
  903. // there's no other conversion going on (the source and target types are the
  904. // same). To do so, we have to insert a conversion of the value up to the
  905. // foundation and back down, and a conversion of the initializing object if
  906. // there is one.
  907. //
  908. // Implementation note: We do the conversion through a call to
  909. // PerformBuiltinConversion() call rather than a Convert() call to avoid
  910. // extraneous `converted` semir instructions on the adapted types, and as a
  911. // shortcut to doing the explicit calls to walk the parts of the
  912. // tuple/struct which happens inside PerformBuiltinConversion().
  913. if (auto foundation_type_id =
  914. context.types().GetTransitiveAdaptedType(value_type_id);
  915. foundation_type_id != value_type_id &&
  916. (context.types().Is<SemIR::TupleType>(foundation_type_id) ||
  917. context.types().Is<SemIR::StructType>(foundation_type_id))) {
  918. auto foundation_value_id = AddInst<SemIR::AsCompatible>(
  919. context, loc_id,
  920. {.type_id = foundation_type_id, .source_id = value_id});
  921. auto foundation_init_id = target.init_id;
  922. if (foundation_init_id != SemIR::InstId::None) {
  923. foundation_init_id = target.init_block->AddInst<SemIR::AsCompatible>(
  924. loc_id,
  925. {.type_id = foundation_type_id, .source_id = target.init_id});
  926. }
  927. {
  928. // While the types are the same, the conversion can still fail if it
  929. // performs a copy while converting the value to another category, and
  930. // the type (or some part of it) is not copyable.
  931. Diagnostics::AnnotationScope annotate_diagnostics(
  932. &context.emitter(), [&](auto& builder) {
  933. CARBON_DIAGNOSTIC(InCopy, Note, "in copy of {0}", TypeOfInstId);
  934. builder.Note(value_id, InCopy, value_id);
  935. });
  936. foundation_value_id =
  937. PerformBuiltinConversion(context, loc_id, foundation_value_id,
  938. {.kind = target.kind,
  939. .type_id = foundation_type_id,
  940. .init_id = foundation_init_id,
  941. .init_block = target.init_block,
  942. .diagnose = target.diagnose});
  943. if (foundation_value_id == SemIR::ErrorInst::InstId) {
  944. return SemIR::ErrorInst::InstId;
  945. }
  946. }
  947. return AddInst<SemIR::AsCompatible>(
  948. context, loc_id,
  949. {.type_id = target.type_id, .source_id = foundation_value_id});
  950. }
  951. }
  952. // T implicitly converts to U if T and U are the same ignoring qualifiers, and
  953. // we're allowed to remove / add any qualifiers that differ. Similarly, T
  954. // explicitly converts to U if T is compatible with U, and we're allowed to
  955. // remove / add any qualifiers that differ.
  956. if (target.type_id != value_type_id) {
  957. auto [target_foundation_id, target_quals] =
  958. target.is_explicit_as()
  959. ? context.types().GetTransitiveUnqualifiedAdaptedType(
  960. target.type_id)
  961. : context.types().GetUnqualifiedTypeAndQualifiers(target.type_id);
  962. auto [value_foundation_id, value_quals] =
  963. target.is_explicit_as()
  964. ? context.types().GetTransitiveUnqualifiedAdaptedType(value_type_id)
  965. : context.types().GetUnqualifiedTypeAndQualifiers(value_type_id);
  966. if (target_foundation_id == value_foundation_id) {
  967. auto category = SemIR::GetExprCategory(context.sem_ir(), value_id);
  968. auto added_quals = target_quals & ~value_quals;
  969. auto removed_quals = value_quals & ~target_quals;
  970. if (CanAddQualifiers(added_quals, category) &&
  971. CanRemoveQualifiers(removed_quals, category, target.kind)) {
  972. // For a struct or tuple literal, perform a category conversion if
  973. // necessary.
  974. if (category == SemIR::ExprCategory::Mixed) {
  975. value_id = PerformBuiltinConversion(context, loc_id, value_id,
  976. {.kind = ConversionTarget::Value,
  977. .type_id = value_type_id,
  978. .diagnose = target.diagnose});
  979. }
  980. // `MaybeUnformed(T)` might have a pointer value representation when `T`
  981. // does not, so convert as needed when removing `MaybeUnformed`.
  982. bool need_value_binding = false;
  983. if ((removed_quals & SemIR::TypeQualifiers::MaybeUnformed) !=
  984. SemIR::TypeQualifiers::None &&
  985. category == SemIR::ExprCategory::Value) {
  986. auto value_rep =
  987. SemIR::ValueRepr::ForType(context.sem_ir(), value_type_id);
  988. auto unformed_value_rep =
  989. SemIR::ValueRepr::ForType(context.sem_ir(), target.type_id);
  990. if (value_rep.kind != unformed_value_rep.kind) {
  991. CARBON_CHECK(unformed_value_rep.kind == SemIR::ValueRepr::Pointer);
  992. value_id = AddInst<SemIR::ValueAsRef>(
  993. context, loc_id,
  994. {.type_id = value_type_id, .value_id = value_id});
  995. need_value_binding = true;
  996. }
  997. }
  998. value_id = AddInst<SemIR::AsCompatible>(
  999. context, loc_id,
  1000. {.type_id = target.type_id, .source_id = value_id});
  1001. if (need_value_binding) {
  1002. value_id = AddInst<SemIR::AcquireValue>(
  1003. context, loc_id,
  1004. {.type_id = target.type_id, .value_id = value_id});
  1005. }
  1006. return value_id;
  1007. } else {
  1008. // TODO: Produce a custom diagnostic explaining that we can't perform
  1009. // this conversion due to the change in qualifiers and/or the expression
  1010. // category.
  1011. }
  1012. }
  1013. }
  1014. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  1015. // converts to Ui.
  1016. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  1017. if (auto src_tuple_type =
  1018. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  1019. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  1020. value_id, target);
  1021. }
  1022. }
  1023. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  1024. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  1025. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  1026. // to Ui.
  1027. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  1028. if (auto src_struct_type =
  1029. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1030. return ConvertStructToStruct(context, *src_struct_type,
  1031. *target_struct_type, value_id, target);
  1032. }
  1033. }
  1034. // No other conversions apply when the source and destination types are the
  1035. // same.
  1036. if (value_type_id == target.type_id) {
  1037. return value_id;
  1038. }
  1039. // A tuple (T1, T2, ..., Tn) converts to array(T, n) if each Ti converts to T.
  1040. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  1041. if (auto src_tuple_type =
  1042. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  1043. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  1044. value_id, target);
  1045. }
  1046. }
  1047. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  1048. // if it converts to the struct type that is the class's representation type
  1049. // (a struct with the same fields as the class, plus a base field where
  1050. // relevant).
  1051. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  1052. if (auto src_struct_type =
  1053. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1054. if (!context.classes()
  1055. .Get(target_class_type->class_id)
  1056. .adapt_id.has_value()) {
  1057. return ConvertStructToClass(context, *src_struct_type,
  1058. *target_class_type, value_id, target,
  1059. vtable_class_type);
  1060. }
  1061. }
  1062. // An expression of type T converts to U if T is a class derived from U.
  1063. //
  1064. // TODO: Combine this with the qualifiers and adapter conversion logic above
  1065. // to allow qualifiers and inheritance conversions to be performed together.
  1066. if (auto path = ComputeInheritancePath(context, loc_id, value_type_id,
  1067. target.type_id);
  1068. path && !path->empty()) {
  1069. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  1070. }
  1071. }
  1072. // A pointer T* converts to [qualified] U* if T is the same as U, or is a
  1073. // class derived from U.
  1074. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  1075. if (auto src_pointer_type =
  1076. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  1077. auto target_pointee_id = context.types().GetTypeIdForTypeInstId(
  1078. target_pointer_type->pointee_id);
  1079. auto src_pointee_id =
  1080. context.types().GetTypeIdForTypeInstId(src_pointer_type->pointee_id);
  1081. // Try to complete the pointee types so that we can walk through adapters
  1082. // to their adapted types.
  1083. TryToCompleteType(context, target_pointee_id, loc_id);
  1084. TryToCompleteType(context, src_pointee_id, loc_id);
  1085. auto [unqual_target_pointee_type_id, target_quals] =
  1086. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(target_pointee_id);
  1087. auto [unqual_src_pointee_type_id, src_quals] =
  1088. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(src_pointee_id);
  1089. // If the qualifiers are incompatible, we can't perform a conversion,
  1090. // except with `unsafe as`.
  1091. if ((src_quals & ~target_quals) != SemIR::TypeQualifiers::None &&
  1092. target.kind != ConversionTarget::ExplicitUnsafeAs) {
  1093. // TODO: Consider producing a custom diagnostic here for a cast that
  1094. // discards constness.
  1095. return value_id;
  1096. }
  1097. if (unqual_target_pointee_type_id != unqual_src_pointee_type_id) {
  1098. // If there's an inheritance path from target to source, this is a
  1099. // derived to base conversion.
  1100. if (auto path = ComputeInheritancePath(context, loc_id,
  1101. unqual_src_pointee_type_id,
  1102. unqual_target_pointee_type_id);
  1103. path && !path->empty()) {
  1104. value_id = ConvertDerivedPointerToBasePointer(
  1105. context, loc_id, *src_pointer_type, target.type_id, value_id,
  1106. *path);
  1107. } else {
  1108. // No conversion was possible.
  1109. return value_id;
  1110. }
  1111. }
  1112. // Perform a compatible conversion to add any new qualifiers.
  1113. if (src_quals != target_quals) {
  1114. return AddInst<SemIR::AsCompatible>(
  1115. context, loc_id,
  1116. {.type_id = target.type_id, .source_id = value_id});
  1117. }
  1118. return value_id;
  1119. }
  1120. }
  1121. if (sem_ir.types().IsFacetType(target.type_id)) {
  1122. auto type_value_id = SemIR::TypeInstId::None;
  1123. // A tuple of types converts to type `type`.
  1124. if (sem_ir.types().Is<SemIR::TupleType>(value_type_id)) {
  1125. type_value_id =
  1126. ConvertTupleToType(context, loc_id, value_id, value_type_id, target);
  1127. }
  1128. // `{}` converts to `{} as type`.
  1129. if (auto struct_type =
  1130. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  1131. if (struct_type->fields_id == SemIR::StructTypeFieldsId::Empty) {
  1132. type_value_id = sem_ir.types().GetInstId(value_type_id);
  1133. }
  1134. }
  1135. if (type_value_id != SemIR::InstId::None) {
  1136. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1137. // Use the converted `TypeType` value for converting to a facet.
  1138. value_id = type_value_id;
  1139. value_type_id = SemIR::TypeType::TypeId;
  1140. } else {
  1141. // We wanted a `TypeType`, and we've done that.
  1142. return type_value_id;
  1143. }
  1144. }
  1145. }
  1146. // FacetType converts to Type by wrapping the facet value in
  1147. // FacetAccessType.
  1148. if (target.type_id == SemIR::TypeType::TypeId &&
  1149. sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1150. return AddInst<SemIR::FacetAccessType>(
  1151. context, loc_id,
  1152. {.type_id = target.type_id, .facet_value_inst_id = value_id});
  1153. }
  1154. // Type values can convert to facet values, and facet values can convert to
  1155. // other facet values, as long as they satisfy the required interfaces of the
  1156. // target `FacetType`.
  1157. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id) &&
  1158. (sem_ir.types().Is<SemIR::TypeType>(value_type_id) ||
  1159. sem_ir.types().Is<SemIR::FacetType>(value_type_id))) {
  1160. // TODO: Runtime facet values should be allowed to convert based on their
  1161. // FacetTypes, but we assume constant values for impl lookup at the moment.
  1162. if (!context.constant_values().Get(value_id).is_constant()) {
  1163. context.TODO(loc_id, "conversion of runtime facet value");
  1164. return SemIR::ErrorInst::InstId;
  1165. }
  1166. // Get the canonical type for which we want to attach a new set of witnesses
  1167. // to match the requirements of the target FacetType.
  1168. auto type_inst_id = SemIR::TypeInstId::None;
  1169. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1170. type_inst_id = AddTypeInst<SemIR::FacetAccessType>(
  1171. context, loc_id,
  1172. {.type_id = SemIR::TypeType::TypeId,
  1173. .facet_value_inst_id = value_id});
  1174. } else {
  1175. type_inst_id = context.types().GetAsTypeInstId(value_id);
  1176. // Shortcut for lossless round trips through a FacetAccessType (which
  1177. // evaluates to SymbolicBindingType when wrapping a symbolic binding) when
  1178. // converting back to the type of the original symbolic binding facet
  1179. // value.
  1180. //
  1181. // In the case where the FacetAccessType wraps a SymbolicBinding with the
  1182. // exact facet type that we are converting to, the resulting FacetValue
  1183. // would evaluate back to the original SymbolicBinding as its canonical
  1184. // form. We can skip past the whole impl lookup step then and do that
  1185. // here.
  1186. //
  1187. // TODO: This instruction is going to become a `SymbolicBindingType`, so
  1188. // we'll need to handle that instead.
  1189. auto facet_value_inst_id =
  1190. GetCanonicalFacetOrTypeValue(context, type_inst_id);
  1191. if (sem_ir.insts().Get(facet_value_inst_id).type_id() == target.type_id) {
  1192. return facet_value_inst_id;
  1193. }
  1194. }
  1195. // Conversion from a facet value (which has type `FacetType`) or a type
  1196. // value (which has type `TypeType`) to a facet value. We can do this if the
  1197. // type satisfies the requirements of the target `FacetType`, as determined
  1198. // by finding impl witnesses for the target FacetType.
  1199. auto lookup_result = LookupImplWitness(
  1200. context, loc_id, sem_ir.constant_values().Get(type_inst_id),
  1201. sem_ir.types().GetConstantId(target.type_id));
  1202. if (lookup_result.has_value()) {
  1203. if (lookup_result.has_error_value()) {
  1204. return SemIR::ErrorInst::InstId;
  1205. } else {
  1206. // Note that `FacetValue`'s type is the same `FacetType` that was used
  1207. // to construct the set of witnesses, ie. the query to
  1208. // `LookupImplWitness()`. This ensures that the witnesses are in the
  1209. // same order as the `required_interfaces()` in the `FacetValue`'s type.
  1210. return AddInst<SemIR::FacetValue>(
  1211. context, loc_id,
  1212. {.type_id = target.type_id,
  1213. .type_inst_id = type_inst_id,
  1214. .witnesses_block_id = lookup_result.inst_block_id()});
  1215. }
  1216. } else {
  1217. // If impl lookup fails, don't keep looking for another way to convert.
  1218. // See https://github.com/carbon-language/carbon-lang/issues/5122.
  1219. // TODO: Pass this function into `LookupImplWitness` so it can construct
  1220. // the error add notes explaining failure.
  1221. if (target.diagnose) {
  1222. DiagnoseConversionFailureToConstraintValue(context, loc_id, value_id,
  1223. target.type_id);
  1224. }
  1225. return SemIR::ErrorInst::InstId;
  1226. }
  1227. }
  1228. // No builtin conversion applies.
  1229. return value_id;
  1230. }
  1231. // Determine whether this is a C++ enum type.
  1232. // TODO: This should be removed once we can properly add a `Copy` impl for C++
  1233. // enum types.
  1234. static auto IsCppEnum(Context& context, SemIR::TypeId type_id) -> bool {
  1235. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  1236. if (!class_type) {
  1237. return false;
  1238. }
  1239. // A C++-imported class type that is an adapter is an enum.
  1240. auto& class_info = context.classes().Get(class_type->class_id);
  1241. return class_info.adapt_id.has_value() &&
  1242. context.name_scopes().Get(class_info.scope_id).is_cpp_scope();
  1243. }
  1244. // Given a value expression, form a corresponding initializer that copies from
  1245. // that value to the specified target, if it is possible to do so.
  1246. static auto PerformCopy(Context& context, SemIR::InstId expr_id,
  1247. ConversionTarget& target) -> SemIR::InstId {
  1248. // TODO: We don't have a mechanism yet to generate `Copy` impls for each enum
  1249. // type imported from C++. For now we fake it by providing a direct copy.
  1250. auto type_id = context.insts().Get(expr_id).type_id();
  1251. if (IsCppEnum(context, type_id)) {
  1252. return expr_id;
  1253. }
  1254. auto copy_id = BuildUnaryOperator(
  1255. context, SemIR::LocId(expr_id), {"Copy"}, expr_id, [&] {
  1256. if (!target.diagnose) {
  1257. return context.emitter().BuildSuppressed();
  1258. }
  1259. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  1260. "cannot copy value of type {0}", TypeOfInstId);
  1261. return context.emitter().Build(expr_id, CopyOfUncopyableType, expr_id);
  1262. });
  1263. MarkInitializerFor(context.sem_ir(), copy_id, target);
  1264. return copy_id;
  1265. }
  1266. // Convert a value expression so that it can be used to initialize a C++ thunk
  1267. // parameter.
  1268. static auto ConvertValueForCppThunkRef(Context& context, SemIR::InstId expr_id)
  1269. -> SemIR::InstId {
  1270. auto expr = context.insts().Get(expr_id);
  1271. // If the expression has a pointer value representation, extract that and use
  1272. // it directly.
  1273. if (SemIR::ValueRepr::ForType(context.sem_ir(), expr.type_id()).kind ==
  1274. SemIR::ValueRepr::Pointer) {
  1275. return AddInst<SemIR::ValueAsRef>(
  1276. context, SemIR::LocId(expr_id),
  1277. {.type_id = expr.type_id(), .value_id = expr_id});
  1278. }
  1279. // Otherwise, we need a temporary to pass as the thunk argument. Create a copy
  1280. // and initialize a temporary from it.
  1281. auto temporary_id = AddInst<SemIR::TemporaryStorage>(
  1282. context, SemIR::LocId(expr_id), {.type_id = expr.type_id()});
  1283. expr_id = Initialize(context, SemIR::LocId(expr_id), temporary_id, expr_id);
  1284. return AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(expr_id),
  1285. {.type_id = expr.type_id(),
  1286. .storage_id = temporary_id,
  1287. .init_id = expr_id});
  1288. }
  1289. // Returns the Core interface name to use for a given kind of conversion.
  1290. static auto GetConversionInterfaceName(ConversionTarget::Kind kind)
  1291. -> llvm::StringLiteral {
  1292. switch (kind) {
  1293. case ConversionTarget::ExplicitAs:
  1294. return "As";
  1295. case ConversionTarget::ExplicitUnsafeAs:
  1296. return "UnsafeAs";
  1297. default:
  1298. return "ImplicitAs";
  1299. }
  1300. }
  1301. auto PerformAction(Context& context, SemIR::LocId loc_id,
  1302. SemIR::ConvertToValueAction action) -> SemIR::InstId {
  1303. return Convert(context, loc_id, action.inst_id,
  1304. {.kind = ConversionTarget::Value,
  1305. .type_id = context.types().GetTypeIdForTypeInstId(
  1306. action.target_type_inst_id)});
  1307. }
  1308. // Diagnoses a missing or unnecessary `ref` tag when converting `expr_id` to
  1309. // `target`, and returns whether a `ref` tag is present.
  1310. static auto CheckRefTag(Context& context, SemIR::InstId expr_id,
  1311. ConversionTarget target) -> bool {
  1312. if (auto lookup_result = context.ref_tags().Lookup(expr_id)) {
  1313. if (lookup_result.value() == Context::RefTag::Present &&
  1314. target.kind != ConversionTarget::RefParam) {
  1315. CARBON_DIAGNOSTIC(RefTagNoRefParam, Error,
  1316. "`ref` tag is not an argument to a `ref` parameter");
  1317. context.emitter().Emit(expr_id, RefTagNoRefParam);
  1318. }
  1319. return true;
  1320. } else {
  1321. if (target.kind == ConversionTarget::RefParam) {
  1322. CARBON_DIAGNOSTIC(RefParamNoRefTag, Error,
  1323. "argument to `ref` parameter not marked with `ref`");
  1324. context.emitter().Emit(expr_id, RefParamNoRefTag);
  1325. }
  1326. return false;
  1327. }
  1328. }
  1329. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  1330. ConversionTarget target, SemIR::ClassType* vtable_class_type)
  1331. -> SemIR::InstId {
  1332. auto& sem_ir = context.sem_ir();
  1333. auto orig_expr_id = expr_id;
  1334. // Start by making sure both sides are non-errors. If any part is an error,
  1335. // the result is an error and we shouldn't diagnose.
  1336. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::ErrorInst::TypeId ||
  1337. target.type_id == SemIR::ErrorInst::TypeId) {
  1338. return SemIR::ErrorInst::InstId;
  1339. }
  1340. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  1341. // TODO: We currently encounter this for use of namespaces and functions.
  1342. // We should provide a better diagnostic for inappropriate use of
  1343. // namespace names, and allow use of functions as values.
  1344. if (target.diagnose) {
  1345. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  1346. "expression cannot be used as a value");
  1347. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  1348. }
  1349. return SemIR::ErrorInst::InstId;
  1350. }
  1351. bool has_ref_tag = CheckRefTag(context, expr_id, target);
  1352. // We can only perform initialization for complete, non-abstract types. Note
  1353. // that `RequireConcreteType` returns true for facet types, since their
  1354. // representation is fixed. This allows us to support using the `Self` of an
  1355. // interface inside its definition.
  1356. if (!RequireConcreteType(
  1357. context, target.type_id, loc_id,
  1358. [&] {
  1359. CARBON_CHECK(!target.is_initializer(),
  1360. "Initialization of incomplete types is expected to be "
  1361. "caught elsewhere.");
  1362. if (!target.diagnose) {
  1363. return context.emitter().BuildSuppressed();
  1364. }
  1365. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  1366. "forming value of incomplete type {0}",
  1367. SemIR::TypeId);
  1368. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  1369. "invalid use of incomplete type {0}",
  1370. SemIR::TypeId);
  1371. return context.emitter().Build(
  1372. loc_id,
  1373. target.kind == ConversionTarget::Value
  1374. ? IncompleteTypeInValueConversion
  1375. : IncompleteTypeInConversion,
  1376. target.type_id);
  1377. },
  1378. [&] {
  1379. if (!target.diagnose || !target.is_initializer()) {
  1380. return context.emitter().BuildSuppressed();
  1381. }
  1382. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  1383. "initialization of abstract type {0}",
  1384. SemIR::TypeId);
  1385. return context.emitter().Build(loc_id, AbstractTypeInInit,
  1386. target.type_id);
  1387. })) {
  1388. return SemIR::ErrorInst::InstId;
  1389. }
  1390. // The source type doesn't need to be complete, but its completeness can
  1391. // affect the result. For example, we don't know what type it adapts or
  1392. // derives from unless it's complete.
  1393. // TODO: Is there a risk of coherence problems if the source type is
  1394. // incomplete, but a conversion would have been possible or would have behaved
  1395. // differently if it were complete?
  1396. TryToCompleteType(context, context.insts().Get(expr_id).type_id(), loc_id);
  1397. // Check whether any builtin conversion applies.
  1398. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target,
  1399. vtable_class_type);
  1400. if (expr_id == SemIR::ErrorInst::InstId) {
  1401. return expr_id;
  1402. }
  1403. bool performed_builtin_conversion = expr_id != orig_expr_id;
  1404. // Defer the action if it's dependent. We do this now rather than before
  1405. // attempting any conversion so that we can still perform builtin conversions
  1406. // on dependent arguments. This matters for things like converting a
  1407. // `template T:! SomeInterface` to `type`, where it's important to form a
  1408. // `FacetAccessType` when checking the template. But when running the action
  1409. // later, we need to try builtin conversions again, because one may apply that
  1410. // didn't apply in the template definition.
  1411. // TODO: Support this for targets other than `Value`.
  1412. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id &&
  1413. target.kind == ConversionTarget::Value &&
  1414. (OperandIsDependent(context, expr_id) ||
  1415. OperandIsDependent(context, target.type_id))) {
  1416. auto target_type_inst_id = context.types().GetInstId(target.type_id);
  1417. return AddDependentActionSplice(
  1418. context, loc_id,
  1419. SemIR::ConvertToValueAction{
  1420. .type_id = GetSingletonType(context, SemIR::InstType::TypeInstId),
  1421. .inst_id = expr_id,
  1422. .target_type_inst_id = target_type_inst_id},
  1423. target_type_inst_id);
  1424. }
  1425. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  1426. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  1427. SemIR::InstId interface_args[] = {
  1428. context.types().GetInstId(target.type_id)};
  1429. Operator op = {
  1430. .interface_name = GetConversionInterfaceName(target.kind),
  1431. .interface_args_ref = interface_args,
  1432. .op_name = "Convert",
  1433. };
  1434. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  1435. if (!target.diagnose) {
  1436. return context.emitter().BuildSuppressed();
  1437. }
  1438. int target_kind_for_diag =
  1439. target.kind == ConversionTarget::ExplicitAs ? 1
  1440. : target.kind == ConversionTarget::ExplicitUnsafeAs ? 2
  1441. : 0;
  1442. if (target.type_id == SemIR::TypeType::TypeId ||
  1443. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1444. CARBON_DIAGNOSTIC(
  1445. ConversionFailureNonTypeToFacet, Error,
  1446. "cannot{0:=0: implicitly|:} convert non-type value of type {1} "
  1447. "{2:to|into type implementing} {3}"
  1448. "{0:=1: with `as`|=2: with `unsafe as`|:}",
  1449. Diagnostics::IntAsSelect, TypeOfInstId, Diagnostics::BoolAsSelect,
  1450. SemIR::TypeId);
  1451. return context.emitter().Build(
  1452. loc_id, ConversionFailureNonTypeToFacet, target_kind_for_diag,
  1453. expr_id, target.type_id == SemIR::TypeType::TypeId, target.type_id);
  1454. } else {
  1455. CARBON_DIAGNOSTIC(
  1456. ConversionFailure, Error,
  1457. "cannot{0:=0: implicitly|:} convert expression of type "
  1458. "{1} to {2}{0:=1: with `as`|=2: with `unsafe as`|:}",
  1459. Diagnostics::IntAsSelect, TypeOfInstId, SemIR::TypeId);
  1460. return context.emitter().Build(loc_id, ConversionFailure,
  1461. target_kind_for_diag, expr_id,
  1462. target.type_id);
  1463. }
  1464. });
  1465. // Pull a value directly out of the initializer if possible and wanted.
  1466. if (expr_id != SemIR::ErrorInst::InstId &&
  1467. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  1468. expr_id = AddInst<SemIR::ValueOfInitializer>(
  1469. context, loc_id, {.type_id = target.type_id, .init_id = expr_id});
  1470. }
  1471. }
  1472. // Track that we performed a type conversion, if we did so.
  1473. if (orig_expr_id != expr_id) {
  1474. expr_id = AddInst<SemIR::Converted>(context, loc_id,
  1475. {.type_id = target.type_id,
  1476. .original_id = orig_expr_id,
  1477. .result_id = expr_id});
  1478. if (has_ref_tag) {
  1479. context.ref_tags().Insert(expr_id, Context::RefTag::NotRequired);
  1480. }
  1481. }
  1482. // For `as`, don't perform any value category conversions. In particular, an
  1483. // identity conversion shouldn't change the expression category.
  1484. if (target.is_explicit_as()) {
  1485. return expr_id;
  1486. }
  1487. // Now perform any necessary value category conversions.
  1488. // This uses fallthrough to implement a very simple state machine over the
  1489. // category of expr_id, which is tracked by current_category.
  1490. switch (auto current_category = SemIR::GetExprCategory(sem_ir, expr_id);
  1491. current_category) {
  1492. case SemIR::ExprCategory::NotExpr:
  1493. case SemIR::ExprCategory::Mixed:
  1494. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  1495. sem_ir.insts().Get(expr_id));
  1496. case SemIR::ExprCategory::Error:
  1497. return SemIR::ErrorInst::InstId;
  1498. case SemIR::ExprCategory::Initializing:
  1499. if (target.is_initializer()) {
  1500. if (!performed_builtin_conversion) {
  1501. // Don't fill in the return slot if we created the expression through
  1502. // a builtin conversion. In that case, we will have created it with
  1503. // the target already set.
  1504. // TODO: Find a better way to track whether we need to do this.
  1505. MarkInitializerFor(sem_ir, expr_id, target);
  1506. }
  1507. break;
  1508. }
  1509. // Commit to using a temporary for this initializing expression.
  1510. // TODO: Don't create a temporary if the initializing representation
  1511. // is already a value representation.
  1512. // TODO: If the target is DurableRef, materialize a VarStorage instead of
  1513. // a TemporaryStorage to lifetime-extend.
  1514. expr_id = FinalizeTemporary(context, expr_id,
  1515. target.kind == ConversionTarget::Discarded);
  1516. // We now have an ephemeral reference.
  1517. current_category = SemIR::ExprCategory::EphemeralRef;
  1518. [[fallthrough]];
  1519. case SemIR::ExprCategory::DurableRef:
  1520. case SemIR::ExprCategory::EphemeralRef:
  1521. if (current_category == SemIR::ExprCategory::DurableRef &&
  1522. target.kind == ConversionTarget::DurableRef) {
  1523. break;
  1524. }
  1525. // If a reference expression is an acceptable result, we're done.
  1526. if (target.kind == ConversionTarget::ValueOrRef ||
  1527. target.kind == ConversionTarget::Discarded ||
  1528. target.kind == ConversionTarget::CppThunkRef ||
  1529. target.kind == ConversionTarget::RefParam) {
  1530. break;
  1531. }
  1532. // If we have a reference and don't want one, form a value binding.
  1533. // TODO: Support types with custom value representations.
  1534. expr_id = AddInst<SemIR::AcquireValue>(
  1535. context, SemIR::LocId(expr_id),
  1536. {.type_id = target.type_id, .value_id = expr_id});
  1537. // We now have a value expression.
  1538. current_category = SemIR::ExprCategory::Value;
  1539. [[fallthrough]];
  1540. case SemIR::ExprCategory::Value:
  1541. if (target.kind == ConversionTarget::DurableRef) {
  1542. if (target.diagnose) {
  1543. CARBON_DIAGNOSTIC(ConversionFailureNonRefToRef, Error,
  1544. "cannot bind durable reference to non-reference "
  1545. "value of type {0}",
  1546. SemIR::TypeId);
  1547. context.emitter().Emit(loc_id, ConversionFailureNonRefToRef,
  1548. target.type_id);
  1549. }
  1550. return SemIR::ErrorInst::InstId;
  1551. }
  1552. if (target.kind == ConversionTarget::RefParam) {
  1553. // Don't diagnose a non-reference scrutinee if it has a user-written
  1554. // `ref` tag, because that's diagnosed in `CheckRefTag`.
  1555. if (target.diagnose) {
  1556. if (auto lookup_result = context.ref_tags().Lookup(expr_id);
  1557. !lookup_result ||
  1558. lookup_result.value() != Context::RefTag::Present) {
  1559. CARBON_DIAGNOSTIC(ValueForRefParam, Error,
  1560. "value expression passed to reference parameter");
  1561. context.emitter().Emit(loc_id, ValueForRefParam);
  1562. }
  1563. }
  1564. return SemIR::ErrorInst::InstId;
  1565. }
  1566. // When initializing from a value, perform a copy.
  1567. if (target.is_initializer()) {
  1568. expr_id = PerformCopy(context, expr_id, target);
  1569. current_category = SemIR::ExprCategory::Initializing;
  1570. }
  1571. // When initializing a C++ thunk parameter, form a reference, creating a
  1572. // temporary if needed.
  1573. if (target.kind == ConversionTarget::CppThunkRef) {
  1574. expr_id = ConvertValueForCppThunkRef(context, expr_id);
  1575. current_category = SemIR::ExprCategory::EphemeralRef;
  1576. }
  1577. break;
  1578. }
  1579. // Perform a final destination store, if necessary.
  1580. if (target.kind == ConversionTarget::FullInitializer) {
  1581. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1582. init_rep.MightBeByCopy()) {
  1583. target.init_block->InsertHere();
  1584. expr_id = AddInst<SemIR::InitializeFrom>(context, loc_id,
  1585. {.type_id = target.type_id,
  1586. .src_id = expr_id,
  1587. .dest_id = target.init_id});
  1588. }
  1589. }
  1590. return expr_id;
  1591. }
  1592. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId target_id,
  1593. SemIR::InstId value_id) -> SemIR::InstId {
  1594. PendingBlock target_block(&context);
  1595. return Convert(context, loc_id, value_id,
  1596. {.kind = ConversionTarget::Initializer,
  1597. .type_id = context.insts().Get(target_id).type_id(),
  1598. .init_id = target_id,
  1599. .init_block = &target_block});
  1600. }
  1601. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1602. -> SemIR::InstId {
  1603. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1604. {.kind = ConversionTarget::Value,
  1605. .type_id = context.insts().Get(expr_id).type_id()});
  1606. }
  1607. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1608. -> SemIR::InstId {
  1609. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1610. {.kind = ConversionTarget::ValueOrRef,
  1611. .type_id = context.insts().Get(expr_id).type_id()});
  1612. }
  1613. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1614. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1615. -> SemIR::InstId {
  1616. return Convert(context, loc_id, expr_id,
  1617. {.kind = ConversionTarget::Value, .type_id = type_id});
  1618. }
  1619. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1620. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1621. -> SemIR::InstId {
  1622. return Convert(context, loc_id, expr_id,
  1623. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1624. }
  1625. // Like ConvertToValueOfType but failure to convert does not result in
  1626. // diagnostics. An ErrorInst instruction is still returned on failure.
  1627. auto TryConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1628. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1629. -> SemIR::InstId {
  1630. return Convert(
  1631. context, loc_id, expr_id,
  1632. {.kind = ConversionTarget::Value, .type_id = type_id, .diagnose = false});
  1633. }
  1634. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1635. SemIR::InstId value_id) -> SemIR::InstId {
  1636. return ConvertToValueOfType(
  1637. context, loc_id, value_id,
  1638. GetSingletonType(context, SemIR::BoolType::TypeInstId));
  1639. }
  1640. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1641. SemIR::InstId value_id, SemIR::TypeId type_id,
  1642. bool unsafe) -> SemIR::InstId {
  1643. return Convert(context, as_node, value_id,
  1644. {.kind = unsafe ? ConversionTarget::ExplicitUnsafeAs
  1645. : ConversionTarget::ExplicitAs,
  1646. .type_id = type_id});
  1647. }
  1648. // TODO: Consider moving this to pattern_match.h.
  1649. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1650. SemIR::InstId self_id,
  1651. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1652. SemIR::InstId return_slot_arg_id,
  1653. const SemIR::Function& callee,
  1654. SemIR::SpecificId callee_specific_id)
  1655. -> SemIR::InstBlockId {
  1656. auto param_patterns =
  1657. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1658. auto return_slot_pattern_id = callee.return_slot_pattern_id;
  1659. // The caller should have ensured this callee has the right arity.
  1660. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1661. if (callee.self_param_id.has_value() && !self_id.has_value()) {
  1662. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1663. "missing object argument in method call");
  1664. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1665. context.emitter()
  1666. .Build(call_loc_id, MissingObjectInMethodCall)
  1667. .Note(callee.latest_decl_id(), InCallToFunction)
  1668. .Emit();
  1669. self_id = SemIR::ErrorInst::InstId;
  1670. }
  1671. return CallerPatternMatch(context, callee_specific_id, callee.self_param_id,
  1672. callee.param_patterns_id, return_slot_pattern_id,
  1673. self_id, arg_refs, return_slot_arg_id);
  1674. }
  1675. auto TypeExpr::ForUnsugared(Context& context, SemIR::TypeId type_id)
  1676. -> TypeExpr {
  1677. return {.inst_id = context.types().GetInstId(type_id), .type_id = type_id};
  1678. }
  1679. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  1680. bool diagnose) -> TypeExpr {
  1681. auto type_inst_id =
  1682. ConvertToValueOfType(context, loc_id, value_id, SemIR::TypeType::TypeId);
  1683. if (type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1684. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1685. .type_id = SemIR::ErrorInst::TypeId};
  1686. }
  1687. auto type_const_id = context.constant_values().Get(type_inst_id);
  1688. if (!type_const_id.is_constant()) {
  1689. if (diagnose) {
  1690. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1691. "cannot evaluate type expression");
  1692. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1693. }
  1694. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1695. .type_id = SemIR::ErrorInst::TypeId};
  1696. }
  1697. return {.inst_id = context.types().GetAsTypeInstId(type_inst_id),
  1698. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1699. }
  1700. auto DiscardExpr(Context& context, SemIR::InstId expr_id) -> void {
  1701. // If we discard an initializing expression, convert it to a value or
  1702. // reference so that it has something to initialize.
  1703. auto expr = context.insts().Get(expr_id);
  1704. Convert(context, SemIR::LocId(expr_id), expr_id,
  1705. {.kind = ConversionTarget::Discarded, .type_id = expr.type_id()});
  1706. // TODO: This will eventually need to do some "do not discard" analysis.
  1707. }
  1708. } // namespace Carbon::Check
  1709. // NOLINTEND(misc-no-recursion)