convert.cpp 100 KB

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