convert.cpp 54 KB

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