convert.cpp 98 KB

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