convert.cpp 54 KB

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