convert.cpp 100 KB

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