convert.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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 <string>
  6. #include <utility>
  7. #include "common/check.h"
  8. #include "common/map.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/check/context.h"
  12. #include "toolchain/check/operator.h"
  13. #include "toolchain/sem_ir/copy_on_write_block.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/generic.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/inst.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. // Given an initializing expression, find its return slot. Returns `Invalid` if
  21. // there is no return slot, because the initialization is not performed in
  22. // place.
  23. static auto FindReturnSlotForInitializer(SemIR::File& sem_ir,
  24. SemIR::InstId init_id)
  25. -> SemIR::InstId {
  26. while (true) {
  27. SemIR::Inst init_untyped = sem_ir.insts().Get(init_id);
  28. CARBON_KIND_SWITCH(init_untyped) {
  29. case CARBON_KIND(SemIR::AsCompatible init): {
  30. init_id = init.source_id;
  31. continue;
  32. }
  33. case CARBON_KIND(SemIR::Converted init): {
  34. init_id = init.result_id;
  35. continue;
  36. }
  37. case CARBON_KIND(SemIR::ArrayInit init): {
  38. return init.dest_id;
  39. }
  40. case CARBON_KIND(SemIR::ClassInit init): {
  41. return init.dest_id;
  42. }
  43. case CARBON_KIND(SemIR::StructInit init): {
  44. return init.dest_id;
  45. }
  46. case CARBON_KIND(SemIR::TupleInit init): {
  47. return init.dest_id;
  48. }
  49. case CARBON_KIND(SemIR::InitializeFrom init): {
  50. return init.dest_id;
  51. }
  52. case CARBON_KIND(SemIR::Call call): {
  53. if (!SemIR::ReturnTypeInfo::ForType(sem_ir, call.type_id)
  54. .has_return_slot()) {
  55. return SemIR::InstId::Invalid;
  56. }
  57. if (!call.args_id.is_valid()) {
  58. // Argument initialization failed, so we have no return slot.
  59. return SemIR::InstId::Invalid;
  60. }
  61. return sem_ir.inst_blocks().Get(call.args_id).back();
  62. }
  63. default:
  64. CARBON_FATAL("Initialization from unexpected inst {0}", init_untyped);
  65. }
  66. }
  67. }
  68. // Marks the initializer `init_id` as initializing `target_id`.
  69. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  70. SemIR::InstId target_id,
  71. PendingBlock& target_block) -> void {
  72. auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id);
  73. if (return_slot_id.is_valid()) {
  74. // Replace the temporary in the return slot with a reference to our target.
  75. CARBON_CHECK(sem_ir.insts().Get(return_slot_id).kind() ==
  76. SemIR::TemporaryStorage::Kind,
  77. "Return slot for initializer does not contain a temporary; "
  78. "initialized multiple times? Have {0}",
  79. sem_ir.insts().Get(return_slot_id));
  80. target_block.MergeReplacing(return_slot_id, target_id);
  81. }
  82. }
  83. // Commits to using a temporary to store the result of the initializing
  84. // expression described by `init_id`, and returns the location of the
  85. // temporary. If `discarded` is `true`, the result is discarded, and no
  86. // temporary will be created if possible; if no temporary is created, the
  87. // return value will be `SemIR::InstId::Invalid`.
  88. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  89. bool discarded) -> SemIR::InstId {
  90. auto& sem_ir = context.sem_ir();
  91. auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id);
  92. if (return_slot_id.is_valid()) {
  93. // The return slot should already have a materialized temporary in it.
  94. CARBON_CHECK(sem_ir.insts().Get(return_slot_id).kind() ==
  95. SemIR::TemporaryStorage::Kind,
  96. "Return slot for initializer does not contain a temporary; "
  97. "initialized multiple times? Have {0}",
  98. sem_ir.insts().Get(return_slot_id));
  99. auto init = sem_ir.insts().Get(init_id);
  100. return context.AddInst<SemIR::Temporary>(sem_ir.insts().GetLocId(init_id),
  101. {.type_id = init.type_id(),
  102. .storage_id = return_slot_id,
  103. .init_id = init_id});
  104. }
  105. if (discarded) {
  106. // Don't invent a temporary that we're going to discard.
  107. return SemIR::InstId::Invalid;
  108. }
  109. // The initializer has no return slot, but we want to produce a temporary
  110. // object. Materialize one now.
  111. // TODO: Consider using an invalid ID to mean that we immediately
  112. // materialize and initialize a temporary, rather than two separate
  113. // instructions.
  114. auto init = sem_ir.insts().Get(init_id);
  115. auto loc_id = sem_ir.insts().GetLocId(init_id);
  116. auto temporary_id = context.AddInst<SemIR::TemporaryStorage>(
  117. loc_id, {.type_id = init.type_id()});
  118. return context.AddInst<SemIR::Temporary>(loc_id, {.type_id = init.type_id(),
  119. .storage_id = temporary_id,
  120. .init_id = init_id});
  121. }
  122. // Materialize a temporary to hold the result of the given expression if it is
  123. // an initializing expression.
  124. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  125. -> SemIR::InstId {
  126. if (GetExprCategory(context.sem_ir(), expr_id) ==
  127. SemIR::ExprCategory::Initializing) {
  128. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  129. }
  130. return expr_id;
  131. }
  132. // Creates and adds an instruction to perform element access into an aggregate.
  133. template <typename AccessInstT, typename InstBlockT>
  134. static auto MakeElementAccessInst(Context& context, SemIR::LocId loc_id,
  135. SemIR::InstId aggregate_id,
  136. SemIR::TypeId elem_type_id, InstBlockT& block,
  137. std::size_t i) {
  138. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  139. // TODO: Add a new instruction kind for indexing an array at a constant
  140. // index so that we don't need an integer literal instruction here, and
  141. // remove this special case.
  142. auto index_id = block.template AddInst<SemIR::IntLiteral>(
  143. loc_id,
  144. {.type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::IntType),
  145. .int_id = context.ints().Add(llvm::APInt(32, i))});
  146. return block.template AddInst<AccessInstT>(
  147. loc_id, {elem_type_id, aggregate_id, index_id});
  148. } else {
  149. return block.template AddInst<AccessInstT>(
  150. loc_id, {elem_type_id, aggregate_id, SemIR::ElementIndex(i)});
  151. }
  152. }
  153. // Converts an element of one aggregate so that it can be used as an element of
  154. // another aggregate.
  155. //
  156. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  157. // element type, `i` is the index, and `SourceAccessInstT` is the kind of
  158. // instruction used to access the source element.
  159. //
  160. // For the target: `kind` is the kind of conversion or initialization,
  161. // `target_elem_type` is the element type. For initialization, `target_id` is
  162. // the destination, `target_block` is a pending block for target location
  163. // calculations that will be spliced as the return slot of the initializer if
  164. // necessary, `i` is the index, and `TargetAccessInstT` is the kind of
  165. // instruction used to access the destination element.
  166. template <typename SourceAccessInstT, typename TargetAccessInstT>
  167. static auto ConvertAggregateElement(
  168. Context& context, SemIR::LocId loc_id, SemIR::InstId src_id,
  169. SemIR::TypeId src_elem_type,
  170. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  171. ConversionTarget::Kind kind, SemIR::InstId target_id,
  172. SemIR::TypeId target_elem_type, PendingBlock* target_block, std::size_t i) {
  173. // Compute the location of the source element. This goes into the current code
  174. // block, not into the target block.
  175. // TODO: Ideally we would discard this instruction if it's unused.
  176. auto src_elem_id =
  177. !src_literal_elems.empty()
  178. ? src_literal_elems[i]
  179. : MakeElementAccessInst<SourceAccessInstT>(context, loc_id, src_id,
  180. src_elem_type, context, i);
  181. // If we're performing a conversion rather than an initialization, we won't
  182. // have or need a target.
  183. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  184. if (!target.is_initializer()) {
  185. return Convert(context, loc_id, src_elem_id, target);
  186. }
  187. // Compute the location of the target element and initialize it.
  188. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  189. target.init_block = target_block;
  190. target.init_id = MakeElementAccessInst<TargetAccessInstT>(
  191. context, loc_id, target_id, target_elem_type, *target_block, i);
  192. return Convert(context, loc_id, src_elem_id, target);
  193. }
  194. // Performs a conversion from a tuple to an array type. This function only
  195. // converts the type, and does not perform a final conversion to the requested
  196. // expression category.
  197. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  198. SemIR::ArrayType array_type,
  199. SemIR::InstId value_id, ConversionTarget target)
  200. -> SemIR::InstId {
  201. auto& sem_ir = context.sem_ir();
  202. auto tuple_elem_types = sem_ir.type_blocks().Get(tuple_type.elements_id);
  203. auto value = sem_ir.insts().Get(value_id);
  204. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  205. // If we're initializing from a tuple literal, we will use its elements
  206. // directly. Otherwise, materialize a temporary if needed and index into the
  207. // result.
  208. llvm::ArrayRef<SemIR::InstId> literal_elems;
  209. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  210. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  211. } else {
  212. value_id = MaterializeIfInitializing(context, value_id);
  213. }
  214. // Check that the tuple is the right size.
  215. uint64_t array_bound = sem_ir.GetArrayBoundValue(array_type.bound_id);
  216. if (tuple_elem_types.size() != array_bound) {
  217. CARBON_DIAGNOSTIC(
  218. ArrayInitFromLiteralArgCountMismatch, Error,
  219. "Cannot initialize array of {0} element(s) from {1} initializer(s).",
  220. uint64_t, size_t);
  221. CARBON_DIAGNOSTIC(ArrayInitFromExprArgCountMismatch, Error,
  222. "Cannot initialize array of {0} element(s) from tuple "
  223. "with {1} element(s).",
  224. uint64_t, size_t);
  225. context.emitter().Emit(value_loc_id,
  226. literal_elems.empty()
  227. ? ArrayInitFromExprArgCountMismatch
  228. : ArrayInitFromLiteralArgCountMismatch,
  229. array_bound, tuple_elem_types.size());
  230. return SemIR::InstId::BuiltinError;
  231. }
  232. PendingBlock target_block_storage(context);
  233. PendingBlock* target_block =
  234. target.init_block ? target.init_block : &target_block_storage;
  235. // Arrays are always initialized in-place. Allocate a temporary as the
  236. // destination for the array initialization if we weren't given one.
  237. SemIR::InstId return_slot_id = target.init_id;
  238. if (!target.init_id.is_valid()) {
  239. return_slot_id = target_block->AddInst<SemIR::TemporaryStorage>(
  240. value_loc_id, {.type_id = target.type_id});
  241. }
  242. // Initialize each element of the array from the corresponding element of the
  243. // tuple.
  244. // TODO: Annotate diagnostics coming from here with the array element index,
  245. // if initializing from a tuple literal.
  246. llvm::SmallVector<SemIR::InstId> inits;
  247. inits.reserve(array_bound + 1);
  248. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  249. // TODO: This call recurses back into conversion. Switch to an iterative
  250. // approach.
  251. auto init_id =
  252. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  253. context, value_loc_id, value_id, src_type_id, literal_elems,
  254. ConversionTarget::FullInitializer, return_slot_id,
  255. array_type.element_type_id, target_block, i);
  256. if (init_id == SemIR::InstId::BuiltinError) {
  257. return SemIR::InstId::BuiltinError;
  258. }
  259. inits.push_back(init_id);
  260. }
  261. // Flush the temporary here if we didn't insert it earlier, so we can add a
  262. // reference to the return slot.
  263. target_block->InsertHere();
  264. return context.AddInst<SemIR::ArrayInit>(
  265. value_loc_id, {.type_id = target.type_id,
  266. .inits_id = sem_ir.inst_blocks().Add(inits),
  267. .dest_id = return_slot_id});
  268. }
  269. // Performs a conversion from a tuple to a tuple type. This function only
  270. // converts the type, and does not perform a final conversion to the requested
  271. // expression category.
  272. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  273. SemIR::TupleType dest_type,
  274. SemIR::InstId value_id, ConversionTarget target)
  275. -> SemIR::InstId {
  276. auto& sem_ir = context.sem_ir();
  277. auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id);
  278. auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id);
  279. auto value = sem_ir.insts().Get(value_id);
  280. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  281. // If we're initializing from a tuple literal, we will use its elements
  282. // directly. Otherwise, materialize a temporary if needed and index into the
  283. // result.
  284. llvm::ArrayRef<SemIR::InstId> literal_elems;
  285. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  286. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  287. literal_elems_id = tuple_literal->elements_id;
  288. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  289. } else {
  290. value_id = MaterializeIfInitializing(context, value_id);
  291. }
  292. // Check that the tuples are the same size.
  293. if (src_elem_types.size() != dest_elem_types.size()) {
  294. CARBON_DIAGNOSTIC(TupleInitElementCountMismatch, Error,
  295. "Cannot initialize tuple of {0} element(s) from tuple "
  296. "with {1} element(s).",
  297. size_t, size_t);
  298. context.emitter().Emit(value_loc_id, TupleInitElementCountMismatch,
  299. dest_elem_types.size(), src_elem_types.size());
  300. return SemIR::InstId::BuiltinError;
  301. }
  302. // If we're forming an initializer, then we want an initializer for each
  303. // element. Otherwise, we want a value representation for each element.
  304. // Perform a final destination store if we're performing an in-place
  305. // initialization.
  306. bool is_init = target.is_initializer();
  307. ConversionTarget::Kind inner_kind =
  308. !is_init ? ConversionTarget::Value
  309. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  310. SemIR::InitRepr::InPlace
  311. ? ConversionTarget::FullInitializer
  312. : ConversionTarget::Initializer;
  313. // Initialize each element of the destination from the corresponding element
  314. // of the source.
  315. // TODO: Annotate diagnostics coming from here with the element index.
  316. auto new_block =
  317. literal_elems_id.is_valid()
  318. ? SemIR::CopyOnWriteInstBlock(sem_ir, literal_elems_id)
  319. : SemIR::CopyOnWriteInstBlock(
  320. sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  321. src_elem_types.size()});
  322. for (auto [i, src_type_id, dest_type_id] :
  323. llvm::enumerate(src_elem_types, dest_elem_types)) {
  324. // TODO: This call recurses back into conversion. Switch to an iterative
  325. // approach.
  326. auto init_id =
  327. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  328. context, value_loc_id, value_id, src_type_id, literal_elems,
  329. inner_kind, target.init_id, dest_type_id, target.init_block, i);
  330. if (init_id == SemIR::InstId::BuiltinError) {
  331. return SemIR::InstId::BuiltinError;
  332. }
  333. new_block.Set(i, init_id);
  334. }
  335. if (is_init) {
  336. target.init_block->InsertHere();
  337. return context.AddInst<SemIR::TupleInit>(value_loc_id,
  338. {.type_id = target.type_id,
  339. .elements_id = new_block.id(),
  340. .dest_id = target.init_id});
  341. } else {
  342. return context.AddInst<SemIR::TupleValue>(
  343. value_loc_id,
  344. {.type_id = target.type_id, .elements_id = new_block.id()});
  345. }
  346. }
  347. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  348. template <typename TargetAccessInstT>
  349. static auto ConvertStructToStructOrClass(Context& context,
  350. SemIR::StructType src_type,
  351. SemIR::StructType dest_type,
  352. SemIR::InstId value_id,
  353. ConversionTarget target, bool is_class)
  354. -> SemIR::InstId {
  355. auto& sem_ir = context.sem_ir();
  356. auto src_elem_fields = sem_ir.inst_blocks().Get(src_type.fields_id);
  357. auto dest_elem_fields = sem_ir.inst_blocks().Get(dest_type.fields_id);
  358. auto value = sem_ir.insts().Get(value_id);
  359. auto value_loc_id = sem_ir.insts().GetLocId(value_id);
  360. // If we're initializing from a struct literal, we will use its elements
  361. // directly. Otherwise, materialize a temporary if needed and index into the
  362. // result.
  363. llvm::ArrayRef<SemIR::InstId> literal_elems;
  364. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  365. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  366. literal_elems_id = struct_literal->elements_id;
  367. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  368. } else {
  369. value_id = MaterializeIfInitializing(context, value_id);
  370. }
  371. // Check that the structs are the same size.
  372. // TODO: If not, include the name of the first source field that doesn't
  373. // exist in the destination or vice versa in the diagnostic.
  374. if (src_elem_fields.size() != dest_elem_fields.size()) {
  375. CARBON_DIAGNOSTIC(StructInitElementCountMismatch, Error,
  376. "Cannot initialize {0} with {1} field(s) from struct "
  377. "with {2} field(s).",
  378. llvm::StringLiteral, size_t, size_t);
  379. context.emitter().Emit(
  380. value_loc_id, StructInitElementCountMismatch,
  381. is_class ? llvm::StringLiteral("class") : llvm::StringLiteral("struct"),
  382. dest_elem_fields.size(), src_elem_fields.size());
  383. return SemIR::InstId::BuiltinError;
  384. }
  385. // Prepare to look up fields in the source by index.
  386. Map<SemIR::NameId, int32_t> src_field_indexes;
  387. if (src_type.fields_id != dest_type.fields_id) {
  388. for (auto [i, field_id] : llvm::enumerate(src_elem_fields)) {
  389. auto result = src_field_indexes.Insert(
  390. context.insts().GetAs<SemIR::StructTypeField>(field_id).name_id, i);
  391. CARBON_CHECK(result.is_inserted(), "Duplicate field in source structure");
  392. }
  393. }
  394. // If we're forming an initializer, then we want an initializer for each
  395. // element. Otherwise, we want a value representation for each element.
  396. // Perform a final destination store if we're performing an in-place
  397. // initialization.
  398. bool is_init = target.is_initializer();
  399. ConversionTarget::Kind inner_kind =
  400. !is_init ? ConversionTarget::Value
  401. : SemIR::InitRepr::ForType(sem_ir, target.type_id).kind ==
  402. SemIR::InitRepr::InPlace
  403. ? ConversionTarget::FullInitializer
  404. : ConversionTarget::Initializer;
  405. // Initialize each element of the destination from the corresponding element
  406. // of the source.
  407. // TODO: Annotate diagnostics coming from here with the element index.
  408. auto new_block =
  409. literal_elems_id.is_valid()
  410. ? SemIR::CopyOnWriteInstBlock(sem_ir, literal_elems_id)
  411. : SemIR::CopyOnWriteInstBlock(
  412. sem_ir, SemIR::CopyOnWriteInstBlock::UninitializedBlock{
  413. src_elem_fields.size()});
  414. for (auto [i, dest_field_id] : llvm::enumerate(dest_elem_fields)) {
  415. auto dest_field =
  416. sem_ir.insts().GetAs<SemIR::StructTypeField>(dest_field_id);
  417. // Find the matching source field.
  418. auto src_field_index = i;
  419. if (src_type.fields_id != dest_type.fields_id) {
  420. if (auto lookup = src_field_indexes.Lookup(dest_field.name_id)) {
  421. src_field_index = lookup.value();
  422. } else {
  423. if (literal_elems_id.is_valid()) {
  424. CARBON_DIAGNOSTIC(
  425. StructInitMissingFieldInLiteral, Error,
  426. "Missing value for field `{0}` in struct initialization.",
  427. SemIR::NameId);
  428. context.emitter().Emit(value_loc_id, StructInitMissingFieldInLiteral,
  429. dest_field.name_id);
  430. } else {
  431. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  432. "Cannot convert from struct type `{0}` to `{1}`: "
  433. "missing field `{2}` in source type.",
  434. SemIR::TypeId, SemIR::TypeId, SemIR::NameId);
  435. context.emitter().Emit(
  436. value_loc_id, StructInitMissingFieldInConversion, value.type_id(),
  437. target.type_id, dest_field.name_id);
  438. }
  439. return SemIR::InstId::BuiltinError;
  440. }
  441. }
  442. auto src_field = sem_ir.insts().GetAs<SemIR::StructTypeField>(
  443. src_elem_fields[src_field_index]);
  444. // TODO: This call recurses back into conversion. Switch to an iterative
  445. // approach.
  446. auto init_id =
  447. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  448. context, value_loc_id, value_id, src_field.field_type_id,
  449. literal_elems, inner_kind, target.init_id, dest_field.field_type_id,
  450. target.init_block, src_field_index);
  451. if (init_id == SemIR::InstId::BuiltinError) {
  452. return SemIR::InstId::BuiltinError;
  453. }
  454. new_block.Set(i, init_id);
  455. }
  456. if (is_class) {
  457. target.init_block->InsertHere();
  458. CARBON_CHECK(is_init,
  459. "Converting directly to a class value is not supported");
  460. return context.AddInst<SemIR::ClassInit>(value_loc_id,
  461. {.type_id = target.type_id,
  462. .elements_id = new_block.id(),
  463. .dest_id = target.init_id});
  464. } else if (is_init) {
  465. target.init_block->InsertHere();
  466. return context.AddInst<SemIR::StructInit>(value_loc_id,
  467. {.type_id = target.type_id,
  468. .elements_id = new_block.id(),
  469. .dest_id = target.init_id});
  470. } else {
  471. return context.AddInst<SemIR::StructValue>(
  472. value_loc_id,
  473. {.type_id = target.type_id, .elements_id = new_block.id()});
  474. }
  475. }
  476. // Performs a conversion from a struct to a struct type. This function only
  477. // converts the type, and does not perform a final conversion to the requested
  478. // expression category.
  479. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  480. SemIR::StructType dest_type,
  481. SemIR::InstId value_id,
  482. ConversionTarget target) -> SemIR::InstId {
  483. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  484. context, src_type, dest_type, value_id, target, /*is_class=*/false);
  485. }
  486. // Performs a conversion from a struct to a class type. This function only
  487. // converts the type, and does not perform a final conversion to the requested
  488. // expression category.
  489. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  490. SemIR::ClassType dest_type,
  491. SemIR::InstId value_id,
  492. ConversionTarget target) -> SemIR::InstId {
  493. PendingBlock target_block(context);
  494. auto& class_info = context.classes().Get(dest_type.class_id);
  495. if (class_info.inheritance_kind == SemIR::Class::Abstract) {
  496. CARBON_DIAGNOSTIC(ConstructionOfAbstractClass, Error,
  497. "Cannot construct instance of abstract class. "
  498. "Consider using `partial {0}` instead.",
  499. SemIR::TypeId);
  500. context.emitter().Emit(value_id, ConstructionOfAbstractClass,
  501. target.type_id);
  502. return SemIR::InstId::BuiltinError;
  503. }
  504. if (class_info.object_repr_id == SemIR::TypeId::Error) {
  505. return SemIR::InstId::BuiltinError;
  506. }
  507. auto dest_struct_type =
  508. context.types().GetAs<SemIR::StructType>(class_info.object_repr_id);
  509. // If we're trying to create a class value, form a temporary for the value to
  510. // point to.
  511. bool need_temporary = !target.is_initializer();
  512. if (need_temporary) {
  513. target.kind = ConversionTarget::Initializer;
  514. target.init_block = &target_block;
  515. target.init_id = target_block.AddInst<SemIR::TemporaryStorage>(
  516. context.insts().GetLocId(value_id), {.type_id = target.type_id});
  517. }
  518. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  519. context, src_type, dest_struct_type, value_id, target, /*is_class=*/true);
  520. if (need_temporary) {
  521. target_block.InsertHere();
  522. result_id = context.AddInst<SemIR::Temporary>(
  523. context.insts().GetLocId(value_id), {.type_id = target.type_id,
  524. .storage_id = target.init_id,
  525. .init_id = result_id});
  526. }
  527. return result_id;
  528. }
  529. // An inheritance path is a sequence of `BaseDecl`s in order from derived to
  530. // base.
  531. using InheritancePath = llvm::SmallVector<SemIR::InstId>;
  532. // Computes the inheritance path from class `derived_id` to class `base_id`.
  533. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  534. static auto ComputeInheritancePath(Context& context, SemIR::TypeId derived_id,
  535. SemIR::TypeId base_id)
  536. -> std::optional<InheritancePath> {
  537. // We intend for NRVO to be applied to `result`. All `return` statements in
  538. // this function should `return result;`.
  539. std::optional<InheritancePath> result(std::in_place);
  540. if (!context.TryToCompleteType(derived_id)) {
  541. // TODO: Should we give an error here? If we don't, and there is an
  542. // inheritance path when the class is defined, we may have a coherence
  543. // problem.
  544. result = std::nullopt;
  545. return result;
  546. }
  547. while (derived_id != base_id) {
  548. auto derived_class_type =
  549. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  550. if (!derived_class_type) {
  551. result = std::nullopt;
  552. break;
  553. }
  554. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  555. if (!derived_class.base_id.is_valid()) {
  556. result = std::nullopt;
  557. break;
  558. }
  559. result->push_back(derived_class.base_id);
  560. derived_id = context.insts()
  561. .GetAs<SemIR::BaseDecl>(derived_class.base_id)
  562. .base_type_id;
  563. }
  564. return result;
  565. }
  566. // Performs a conversion from a derived class value or reference to a base class
  567. // value or reference.
  568. static auto ConvertDerivedToBase(Context& context, SemIR::LocId loc_id,
  569. SemIR::InstId value_id,
  570. const InheritancePath& path) -> SemIR::InstId {
  571. // Materialize a temporary if necessary.
  572. value_id = ConvertToValueOrRefExpr(context, value_id);
  573. // Add a series of `.base` accesses.
  574. for (auto base_id : path) {
  575. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  576. value_id = context.AddInst<SemIR::ClassElementAccess>(
  577. loc_id, {.type_id = base_decl.base_type_id,
  578. .base_id = value_id,
  579. .index = base_decl.index});
  580. }
  581. return value_id;
  582. }
  583. // Performs a conversion from a derived class pointer to a base class pointer.
  584. static auto ConvertDerivedPointerToBasePointer(
  585. Context& context, SemIR::LocId loc_id, SemIR::PointerType src_ptr_type,
  586. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  587. const InheritancePath& path) -> SemIR::InstId {
  588. // Form `*p`.
  589. ptr_id = ConvertToValueExpr(context, ptr_id);
  590. auto ref_id = context.AddInst<SemIR::Deref>(
  591. loc_id, {.type_id = src_ptr_type.pointee_id, .pointer_id = ptr_id});
  592. // Convert as a reference expression.
  593. ref_id = ConvertDerivedToBase(context, loc_id, ref_id, path);
  594. // Take the address.
  595. return context.AddInst<SemIR::AddrOf>(
  596. loc_id, {.type_id = dest_ptr_type_id, .lvalue_id = ref_id});
  597. }
  598. // Returns whether `category` is a valid expression category to produce as a
  599. // result of a conversion with kind `target_kind`, or at most needs a temporary
  600. // to be materialized.
  601. static auto IsValidExprCategoryForConversionTarget(
  602. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  603. switch (target_kind) {
  604. case ConversionTarget::Value:
  605. return category == SemIR::ExprCategory::Value;
  606. case ConversionTarget::ValueOrRef:
  607. case ConversionTarget::Discarded:
  608. return category == SemIR::ExprCategory::Value ||
  609. category == SemIR::ExprCategory::DurableRef ||
  610. category == SemIR::ExprCategory::EphemeralRef ||
  611. category == SemIR::ExprCategory::Initializing;
  612. case ConversionTarget::ExplicitAs:
  613. return true;
  614. case ConversionTarget::Initializer:
  615. case ConversionTarget::FullInitializer:
  616. return category == SemIR::ExprCategory::Initializing;
  617. }
  618. }
  619. // Returns the non-adapter type that is compatible with the specified type.
  620. static auto GetCompatibleBaseType(Context& context, SemIR::TypeId type_id)
  621. -> SemIR::TypeId {
  622. // If the type is an adapter, its object representation type is its compatible
  623. // non-adapter type.
  624. if (auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  625. auto& class_info = context.classes().Get(class_type->class_id);
  626. if (class_info.adapt_id.is_valid()) {
  627. return class_info.object_repr_id;
  628. }
  629. }
  630. // Otherwise, the type itself is a non-adapter type.
  631. return type_id;
  632. }
  633. static auto PerformBuiltinConversion(Context& context, SemIR::LocId loc_id,
  634. SemIR::InstId value_id,
  635. ConversionTarget target) -> SemIR::InstId {
  636. auto& sem_ir = context.sem_ir();
  637. auto value = sem_ir.insts().Get(value_id);
  638. auto value_type_id = value.type_id();
  639. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  640. // Various forms of implicit conversion are supported as builtin conversions,
  641. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  642. // prelude. There are a few reasons we need to perform some of these
  643. // conversions as builtins:
  644. //
  645. // 1) Conversions from struct and tuple *literals* have special rules that
  646. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  647. // recurse into the elements of the literal before performing
  648. // initialization in order to avoid unnecessary conversions between
  649. // expression categories that would be performed by `ImplicitAs.Convert`.
  650. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  651. // the value of the facet, not only its type, and therefore cannot be
  652. // modeled by `ImplicitAs`.
  653. // 3) Some of these conversions are used while checking the library
  654. // definition of `ImplicitAs` itself or implementations of it.
  655. //
  656. // We also expect to see better performance by avoiding an `impl` lookup for
  657. // common conversions.
  658. //
  659. // TODO: We should provide a debugging flag to turn off as many of these
  660. // builtin conversions as we can so that we can test that they do the same
  661. // thing as the library implementations.
  662. //
  663. // The builtin conversions that correspond to `impl`s in the library all
  664. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  665. // being specialized in any of these cases.
  666. // If the value is already of the right kind and expression category, there's
  667. // nothing to do. Performing a conversion would decompose and rebuild tuples
  668. // and structs, so it's important that we bail out early in this case.
  669. if (value_type_id == target.type_id) {
  670. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  671. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  672. return value_id;
  673. }
  674. // If the source is an initializing expression, we may be able to pull a
  675. // value right out of it.
  676. if (value_cat == SemIR::ExprCategory::Initializing &&
  677. IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  678. target.kind) &&
  679. SemIR::InitRepr::ForType(sem_ir, value_type_id).kind ==
  680. SemIR::InitRepr::ByCopy) {
  681. auto value_rep = SemIR::ValueRepr::ForType(sem_ir, value_type_id);
  682. if (value_rep.kind == SemIR::ValueRepr::Copy &&
  683. value_rep.type_id == value_type_id) {
  684. // The initializer produces an object representation by copy, and the
  685. // value representation is a copy of the object representation, so we
  686. // already have a value of the right form.
  687. return context.AddInst<SemIR::ValueOfInitializer>(
  688. loc_id, {.type_id = value_type_id, .init_id = value_id});
  689. }
  690. }
  691. }
  692. // T explicitly converts to U if T is compatible with U.
  693. if (target.kind == ConversionTarget::Kind::ExplicitAs &&
  694. target.type_id != value_type_id) {
  695. auto target_base_id = GetCompatibleBaseType(context, target.type_id);
  696. auto value_base_id = GetCompatibleBaseType(context, value_type_id);
  697. if (target_base_id == value_base_id) {
  698. // For a struct or tuple literal, perform a category conversion if
  699. // necessary.
  700. if (SemIR::GetExprCategory(context.sem_ir(), value_id) ==
  701. SemIR::ExprCategory::Mixed) {
  702. value_id = PerformBuiltinConversion(
  703. context, loc_id, value_id,
  704. ConversionTarget{.kind = ConversionTarget::Value,
  705. .type_id = value_type_id});
  706. }
  707. return context.AddInst<SemIR::AsCompatible>(
  708. loc_id, {.type_id = target.type_id, .source_id = value_id});
  709. }
  710. }
  711. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  712. // converts to Ui.
  713. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  714. if (auto src_tuple_type =
  715. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  716. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  717. value_id, target);
  718. }
  719. }
  720. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  721. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  722. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  723. // to Ui.
  724. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  725. if (auto src_struct_type =
  726. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  727. return ConvertStructToStruct(context, *src_struct_type,
  728. *target_struct_type, value_id, target);
  729. }
  730. }
  731. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  732. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  733. if (auto src_tuple_type =
  734. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  735. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  736. value_id, target);
  737. }
  738. }
  739. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  740. // if it converts to the struct type that is the class's representation type
  741. // (a struct with the same fields as the class, plus a base field where
  742. // relevant).
  743. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  744. if (auto src_struct_type =
  745. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  746. if (!context.classes()
  747. .Get(target_class_type->class_id)
  748. .adapt_id.is_valid()) {
  749. return ConvertStructToClass(context, *src_struct_type,
  750. *target_class_type, value_id, target);
  751. }
  752. }
  753. // An expression of type T converts to U if T is a class derived from U.
  754. if (auto path =
  755. ComputeInheritancePath(context, value_type_id, target.type_id);
  756. path && !path->empty()) {
  757. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  758. }
  759. }
  760. // A pointer T* converts to U* if T is a class derived from U.
  761. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  762. if (auto src_pointer_type =
  763. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  764. if (auto path =
  765. ComputeInheritancePath(context, src_pointer_type->pointee_id,
  766. target_pointer_type->pointee_id);
  767. path && !path->empty()) {
  768. return ConvertDerivedPointerToBasePointer(
  769. context, loc_id, *src_pointer_type, target.type_id, value_id,
  770. *path);
  771. }
  772. }
  773. }
  774. if (target.type_id == SemIR::TypeId::TypeType) {
  775. // A tuple of types converts to type `type`.
  776. // TODO: This should apply even for non-literal tuples.
  777. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  778. llvm::SmallVector<SemIR::TypeId> type_ids;
  779. for (auto tuple_inst_id :
  780. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  781. // TODO: This call recurses back into conversion. Switch to an
  782. // iterative approach.
  783. type_ids.push_back(ExprAsType(context, loc_id, tuple_inst_id));
  784. }
  785. auto tuple_type_id = context.GetTupleType(type_ids);
  786. return sem_ir.types().GetInstId(tuple_type_id);
  787. }
  788. // `{}` converts to `{} as type`.
  789. // TODO: This conversion should also be performed for a non-literal value
  790. // of type `{}`.
  791. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  792. struct_literal &&
  793. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  794. value_id = sem_ir.types().GetInstId(value_type_id);
  795. }
  796. // Facet type conversions: a value T of facet type F1 can be implicitly
  797. // converted to facet type F2 if T satisfies the requirements of F2.
  798. //
  799. // TODO: Support this conversion in general. For now we only support it in
  800. // the case where F1 is an interface type and F2 is `type`.
  801. // TODO: Support converting tuple and struct values to facet types,
  802. // combining the above conversions and this one in a single conversion.
  803. if (sem_ir.types().Is<SemIR::InterfaceType>(value_type_id)) {
  804. return context.AddInst<SemIR::FacetTypeAccess>(
  805. loc_id, {.type_id = target.type_id, .facet_id = value_id});
  806. }
  807. }
  808. // No builtin conversion applies.
  809. return value_id;
  810. }
  811. // Given a value expression, form a corresponding initializer that copies from
  812. // that value, if it is possible to do so.
  813. static auto PerformCopy(Context& context, SemIR::InstId expr_id)
  814. -> SemIR::InstId {
  815. auto expr = context.insts().Get(expr_id);
  816. auto type_id = expr.type_id();
  817. if (type_id == SemIR::TypeId::Error) {
  818. return SemIR::InstId::BuiltinError;
  819. }
  820. // TODO: Directly track on the value representation whether it's a copy of
  821. // the object representation.
  822. auto value_rep = SemIR::ValueRepr::ForType(context.sem_ir(), type_id);
  823. if (value_rep.kind == SemIR::ValueRepr::Copy &&
  824. value_rep.aggregate_kind == SemIR::ValueRepr::NotAggregate &&
  825. value_rep.type_id == type_id) {
  826. // For by-value scalar types, no explicit action is required. Initializing
  827. // from a value expression is treated as copying the value.
  828. return expr_id;
  829. }
  830. // TODO: We don't yet have rules for whether and when a class type is
  831. // copyable, or how to perform the copy.
  832. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  833. "Cannot copy value of type `{0}`.", SemIR::TypeId);
  834. context.emitter().Emit(expr_id, CopyOfUncopyableType, type_id);
  835. return SemIR::InstId::BuiltinError;
  836. }
  837. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  838. ConversionTarget target) -> SemIR::InstId {
  839. auto& sem_ir = context.sem_ir();
  840. auto orig_expr_id = expr_id;
  841. // Start by making sure both sides are valid. If any part is invalid, the
  842. // result is invalid and we shouldn't error.
  843. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::TypeId::Error ||
  844. target.type_id == SemIR::TypeId::Error) {
  845. return SemIR::InstId::BuiltinError;
  846. }
  847. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  848. // TODO: We currently encounter this for use of namespaces and functions.
  849. // We should provide a better diagnostic for inappropriate use of
  850. // namespace names, and allow use of functions as values.
  851. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  852. "Expression cannot be used as a value.");
  853. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  854. return SemIR::InstId::BuiltinError;
  855. }
  856. // We can only perform initialization for complete types.
  857. if (!context.TryToCompleteType(target.type_id, [&] {
  858. CARBON_DIAGNOSTIC(IncompleteTypeInInit, Error,
  859. "Initialization of incomplete type `{0}`.",
  860. SemIR::TypeId);
  861. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  862. "Forming value of incomplete type `{0}`.",
  863. SemIR::TypeId);
  864. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  865. "Invalid use of incomplete type `{0}`.",
  866. SemIR::TypeId);
  867. return context.emitter().Build(loc_id,
  868. target.is_initializer()
  869. ? IncompleteTypeInInit
  870. : target.kind == ConversionTarget::Value
  871. ? IncompleteTypeInValueConversion
  872. : IncompleteTypeInConversion,
  873. target.type_id);
  874. })) {
  875. return SemIR::InstId::BuiltinError;
  876. }
  877. // Check whether any builtin conversion applies.
  878. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target);
  879. if (expr_id == SemIR::InstId::BuiltinError) {
  880. return expr_id;
  881. }
  882. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  883. SemIR::Inst expr = sem_ir.insts().Get(expr_id);
  884. if (expr.type_id() != target.type_id) {
  885. SemIR::InstId interface_args[] = {
  886. context.types().GetInstId(target.type_id)};
  887. Operator op = {
  888. .interface_name = target.kind == ConversionTarget::ExplicitAs
  889. ? llvm::StringLiteral("As")
  890. : llvm::StringLiteral("ImplicitAs"),
  891. .interface_args_ref = interface_args,
  892. .op_name = "Convert",
  893. };
  894. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  895. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  896. "Cannot implicitly convert from `{0}` to `{1}`.",
  897. SemIR::TypeId, SemIR::TypeId);
  898. CARBON_DIAGNOSTIC(ExplicitAsConversionFailure, Error,
  899. "Cannot convert from `{0}` to `{1}` with `as`.",
  900. SemIR::TypeId, SemIR::TypeId);
  901. return context.emitter().Build(loc_id,
  902. target.kind == ConversionTarget::ExplicitAs
  903. ? ExplicitAsConversionFailure
  904. : ImplicitAsConversionFailure,
  905. expr.type_id(), target.type_id);
  906. });
  907. }
  908. // Track that we performed a type conversion, if we did so.
  909. if (orig_expr_id != expr_id) {
  910. expr_id =
  911. context.AddInst<SemIR::Converted>(loc_id, {.type_id = target.type_id,
  912. .original_id = orig_expr_id,
  913. .result_id = expr_id});
  914. }
  915. // For `as`, don't perform any value category conversions. In particular, an
  916. // identity conversion shouldn't change the expression category.
  917. if (target.kind == ConversionTarget::ExplicitAs) {
  918. return expr_id;
  919. }
  920. // Now perform any necessary value category conversions.
  921. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  922. case SemIR::ExprCategory::NotExpr:
  923. case SemIR::ExprCategory::Mixed:
  924. CARBON_FATAL("Unexpected expression {0} after builtin conversions", expr);
  925. case SemIR::ExprCategory::Error:
  926. return SemIR::InstId::BuiltinError;
  927. case SemIR::ExprCategory::Initializing:
  928. if (target.is_initializer()) {
  929. if (orig_expr_id == expr_id) {
  930. // Don't fill in the return slot if we created the expression through
  931. // a conversion. In that case, we will have created it with the
  932. // target already set.
  933. // TODO: Find a better way to track whether we need to do this.
  934. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  935. *target.init_block);
  936. }
  937. break;
  938. }
  939. // Commit to using a temporary for this initializing expression.
  940. // TODO: Don't create a temporary if the initializing representation
  941. // is already a value representation.
  942. expr_id = FinalizeTemporary(context, expr_id,
  943. target.kind == ConversionTarget::Discarded);
  944. // We now have an ephemeral reference.
  945. [[fallthrough]];
  946. case SemIR::ExprCategory::DurableRef:
  947. case SemIR::ExprCategory::EphemeralRef:
  948. // If a reference expression is an acceptable result, we're done.
  949. if (target.kind == ConversionTarget::ValueOrRef ||
  950. target.kind == ConversionTarget::Discarded) {
  951. break;
  952. }
  953. // If we have a reference and don't want one, form a value binding.
  954. // TODO: Support types with custom value representations.
  955. expr_id = context.AddInst<SemIR::BindValue>(
  956. context.insts().GetLocId(expr_id),
  957. {.type_id = expr.type_id(), .value_id = expr_id});
  958. // We now have a value expression.
  959. [[fallthrough]];
  960. case SemIR::ExprCategory::Value:
  961. // When initializing from a value, perform a copy.
  962. if (target.is_initializer()) {
  963. expr_id = PerformCopy(context, expr_id);
  964. }
  965. break;
  966. }
  967. // Perform a final destination store, if necessary.
  968. if (target.kind == ConversionTarget::FullInitializer) {
  969. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  970. init_rep.kind == SemIR::InitRepr::ByCopy) {
  971. target.init_block->InsertHere();
  972. expr_id = context.AddInst<SemIR::InitializeFrom>(
  973. loc_id, {.type_id = target.type_id,
  974. .src_id = expr_id,
  975. .dest_id = target.init_id});
  976. }
  977. }
  978. return expr_id;
  979. }
  980. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId target_id,
  981. SemIR::InstId value_id) -> SemIR::InstId {
  982. PendingBlock target_block(context);
  983. return Convert(context, loc_id, value_id,
  984. {.kind = ConversionTarget::Initializer,
  985. .type_id = context.insts().Get(target_id).type_id(),
  986. .init_id = target_id,
  987. .init_block = &target_block});
  988. }
  989. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  990. -> SemIR::InstId {
  991. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  992. {.kind = ConversionTarget::Value,
  993. .type_id = context.insts().Get(expr_id).type_id()});
  994. }
  995. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  996. -> SemIR::InstId {
  997. return Convert(context, context.insts().GetLocId(expr_id), expr_id,
  998. {.kind = ConversionTarget::ValueOrRef,
  999. .type_id = context.insts().Get(expr_id).type_id()});
  1000. }
  1001. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1002. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1003. -> SemIR::InstId {
  1004. return Convert(context, loc_id, expr_id,
  1005. {.kind = ConversionTarget::Value, .type_id = type_id});
  1006. }
  1007. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1008. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1009. -> SemIR::InstId {
  1010. return Convert(context, loc_id, expr_id,
  1011. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1012. }
  1013. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1014. SemIR::InstId value_id) -> SemIR::InstId {
  1015. return ConvertToValueOfType(
  1016. context, loc_id, value_id,
  1017. context.GetBuiltinType(SemIR::BuiltinInstKind::BoolType));
  1018. }
  1019. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1020. SemIR::InstId value_id, SemIR::TypeId type_id)
  1021. -> SemIR::InstId {
  1022. return Convert(context, as_node, value_id,
  1023. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  1024. }
  1025. CARBON_DIAGNOSTIC(InCallToFunction, Note, "Calling function declared here.");
  1026. // Convert the object argument in a method call to match the `self` parameter.
  1027. static auto ConvertSelf(Context& context, SemIR::LocId call_loc_id,
  1028. SemIRLoc callee_loc,
  1029. SemIR::SpecificId callee_specific_id,
  1030. std::optional<SemIR::AddrPattern> addr_pattern,
  1031. SemIR::InstId self_param_id, SemIR::Param self_param,
  1032. SemIR::InstId self_id) -> SemIR::InstId {
  1033. if (!self_id.is_valid()) {
  1034. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1035. "Missing object argument in method call.");
  1036. context.emitter()
  1037. .Build(call_loc_id, MissingObjectInMethodCall)
  1038. .Note(callee_loc, InCallToFunction)
  1039. .Emit();
  1040. return SemIR::InstId::BuiltinError;
  1041. }
  1042. DiagnosticAnnotationScope annotate_diagnostics(
  1043. &context.emitter(), [&](auto& builder) {
  1044. CARBON_DIAGNOSTIC(
  1045. InCallToFunctionSelf, Note,
  1046. "Initializing `{0}` parameter of method declared here.",
  1047. llvm::StringLiteral);
  1048. builder.Note(self_param_id, InCallToFunctionSelf,
  1049. addr_pattern ? llvm::StringLiteral("addr self")
  1050. : llvm::StringLiteral("self"));
  1051. });
  1052. // For `addr self`, take the address of the object argument.
  1053. auto self_or_addr_id = self_id;
  1054. if (addr_pattern) {
  1055. self_or_addr_id = ConvertToValueOrRefExpr(context, self_or_addr_id);
  1056. auto self = context.insts().Get(self_or_addr_id);
  1057. switch (SemIR::GetExprCategory(context.sem_ir(), self_id)) {
  1058. case SemIR::ExprCategory::Error:
  1059. case SemIR::ExprCategory::DurableRef:
  1060. case SemIR::ExprCategory::EphemeralRef:
  1061. break;
  1062. default:
  1063. CARBON_DIAGNOSTIC(AddrSelfIsNonRef, Error,
  1064. "`addr self` method cannot be invoked on a value.");
  1065. context.emitter().Emit(TokenOnly(call_loc_id), AddrSelfIsNonRef);
  1066. return SemIR::InstId::BuiltinError;
  1067. }
  1068. auto loc_id = context.insts().GetLocId(self_or_addr_id);
  1069. self_or_addr_id = context.AddInst<SemIR::AddrOf>(
  1070. loc_id, {.type_id = context.GetPointerType(self.type_id()),
  1071. .lvalue_id = self_or_addr_id});
  1072. }
  1073. return ConvertToValueOfType(
  1074. context, call_loc_id, self_or_addr_id,
  1075. SemIR::GetTypeInSpecific(context.sem_ir(), callee_specific_id,
  1076. self_param.type_id));
  1077. }
  1078. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1079. SemIR::InstId self_id,
  1080. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1081. SemIR::InstId return_storage_id,
  1082. const CalleeParamsInfo& callee,
  1083. SemIR::SpecificId callee_specific_id)
  1084. -> SemIR::InstBlockId {
  1085. auto implicit_param_refs =
  1086. context.inst_blocks().GetOrEmpty(callee.implicit_param_refs_id);
  1087. auto param_refs = context.inst_blocks().GetOrEmpty(callee.param_refs_id);
  1088. // If sizes mismatch, fail early.
  1089. if (arg_refs.size() != param_refs.size()) {
  1090. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  1091. "{0} argument(s) passed to function expecting "
  1092. "{1} argument(s).",
  1093. int, int);
  1094. context.emitter()
  1095. .Build(call_loc_id, CallArgCountMismatch, arg_refs.size(),
  1096. param_refs.size())
  1097. .Note(callee.callee_loc, InCallToFunction)
  1098. .Emit();
  1099. return SemIR::InstBlockId::Invalid;
  1100. }
  1101. // Start building a block to hold the converted arguments.
  1102. llvm::SmallVector<SemIR::InstId> args;
  1103. args.reserve(implicit_param_refs.size() + param_refs.size() +
  1104. return_storage_id.is_valid());
  1105. // Check implicit parameters.
  1106. for (auto implicit_param_id : implicit_param_refs) {
  1107. auto addr_pattern =
  1108. context.insts().TryGetAs<SemIR::AddrPattern>(implicit_param_id);
  1109. auto [param_id, param] = SemIR::Function::GetParamFromParamRefId(
  1110. context.sem_ir(), implicit_param_id);
  1111. if (param.name_id == SemIR::NameId::SelfValue) {
  1112. auto converted_self_id = ConvertSelf(
  1113. context, call_loc_id, callee.callee_loc, callee_specific_id,
  1114. addr_pattern, param_id, param, self_id);
  1115. if (converted_self_id == SemIR::InstId::BuiltinError) {
  1116. return SemIR::InstBlockId::Invalid;
  1117. }
  1118. args.push_back(converted_self_id);
  1119. } else {
  1120. // TODO: Form argument values for implicit parameters.
  1121. context.TODO(call_loc_id, "Call with implicit parameters");
  1122. return SemIR::InstBlockId::Invalid;
  1123. }
  1124. }
  1125. int diag_param_index;
  1126. DiagnosticAnnotationScope annotate_diagnostics(
  1127. &context.emitter(), [&](auto& builder) {
  1128. CARBON_DIAGNOSTIC(
  1129. InCallToFunctionParam, Note,
  1130. "Initializing parameter {0} of function declared here.", int);
  1131. builder.Note(callee.callee_loc, InCallToFunctionParam,
  1132. diag_param_index + 1);
  1133. });
  1134. // Check type conversions per-element.
  1135. for (auto [i, arg_id, param_id] : llvm::enumerate(arg_refs, param_refs)) {
  1136. diag_param_index = i;
  1137. auto param_type_id =
  1138. SemIR::GetTypeInSpecific(context.sem_ir(), callee_specific_id,
  1139. context.insts().Get(param_id).type_id());
  1140. // TODO: Convert to the proper expression category. For now, we assume
  1141. // parameters are all `let` bindings.
  1142. auto converted_arg_id =
  1143. ConvertToValueOfType(context, call_loc_id, arg_id, param_type_id);
  1144. if (converted_arg_id == SemIR::InstId::BuiltinError) {
  1145. return SemIR::InstBlockId::Invalid;
  1146. }
  1147. args.push_back(converted_arg_id);
  1148. }
  1149. // Track the return storage, if present.
  1150. if (return_storage_id.is_valid()) {
  1151. args.push_back(return_storage_id);
  1152. }
  1153. return context.inst_blocks().Add(args);
  1154. }
  1155. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id)
  1156. -> SemIR::TypeId {
  1157. auto type_inst_id =
  1158. ConvertToValueOfType(context, loc_id, value_id, SemIR::TypeId::TypeType);
  1159. if (type_inst_id == SemIR::InstId::BuiltinError) {
  1160. return SemIR::TypeId::Error;
  1161. }
  1162. auto type_const_id = context.constant_values().Get(type_inst_id);
  1163. if (!type_const_id.is_constant()) {
  1164. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1165. "Cannot evaluate type expression.");
  1166. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1167. return SemIR::TypeId::Error;
  1168. }
  1169. return context.GetTypeIdForTypeConstant(type_const_id);
  1170. }
  1171. } // namespace Carbon::Check