convert.cpp 51 KB

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