convert.cpp 57 KB

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