handle_aggregates.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 "llvm/ADT/STLExtras.h"
  5. #include "llvm/ADT/StringRef.h"
  6. #include "llvm/ADT/Twine.h"
  7. #include "llvm/IR/Constants.h"
  8. #include "llvm/IR/Value.h"
  9. #include "toolchain/lower/function_context.h"
  10. #include "toolchain/sem_ir/expr_info.h"
  11. #include "toolchain/sem_ir/file.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/inst.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Lower {
  16. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  17. SemIR::ClassDecl /*inst*/) -> void {
  18. // No action to perform.
  19. }
  20. static auto GetPointeeType(FunctionContext::TypeInFile type)
  21. -> FunctionContext::TypeInFile {
  22. return {.file = type.file,
  23. .type_id = type.file->GetPointeeType(type.type_id)};
  24. }
  25. // Given an index within a SemIR aggregate type, returns the corresponding index
  26. // of the element within the LLVM type suitable for use with the getelementptr
  27. // instruction.
  28. static auto GetElementIndex(FunctionContext::TypeInFile type,
  29. SemIR::ElementIndex idx) -> unsigned int {
  30. auto type_inst = type.file->types().GetAsInst(type.type_id);
  31. if (auto custom_layout_type = type_inst.TryAs<SemIR::CustomLayoutType>()) {
  32. // For custom layout types, we form an array of i8 as the LLVM type, so the
  33. // offset in the type is the getelementptr index.
  34. // TODO: This offset might not fit into an `unsigned int`.
  35. return type.file->custom_layouts().Get(
  36. custom_layout_type
  37. ->layout_id)[SemIR::CustomLayoutId::FirstFieldIndex + idx.index];
  38. }
  39. // For now, struct and tuple types map directly into LLVM struct types with
  40. // identical field numbering.
  41. CARBON_CHECK(
  42. type_inst.Is<SemIR::StructType>() || type_inst.Is<SemIR::TupleType>(),
  43. "Indexing unexpected aggregate type {0}", type_inst);
  44. return idx.index;
  45. }
  46. // Extracts an element of an aggregate, such as a struct, tuple, or class, by
  47. // index. Depending on the expression category and value representation of the
  48. // aggregate input, this will either produce a value or a reference.
  49. static auto GetAggregateElement(FunctionContext& context,
  50. SemIR::InstId aggr_inst_id,
  51. SemIR::ElementIndex idx,
  52. SemIR::InstId result_inst_id, llvm::Twine name)
  53. -> llvm::Value* {
  54. auto* aggr_value = context.GetValue(aggr_inst_id);
  55. switch (SemIR::GetExprCategory(context.sem_ir(), aggr_inst_id)) {
  56. case SemIR::ExprCategory::Error:
  57. case SemIR::ExprCategory::NotExpr:
  58. case SemIR::ExprCategory::Initializing:
  59. case SemIR::ExprCategory::Mixed:
  60. CARBON_FATAL(
  61. "Unexpected expression category for aggregate access into {0}",
  62. context.sem_ir().insts().Get(aggr_inst_id));
  63. case SemIR::ExprCategory::Value: {
  64. auto aggr_type = context.GetTypeIdOfInst(aggr_inst_id);
  65. auto value_repr = context.GetValueRepr(aggr_type);
  66. CARBON_CHECK(
  67. value_repr.repr.aggregate_kind != SemIR::ValueRepr::NotAggregate,
  68. "aggregate type should have aggregate value representation");
  69. switch (value_repr.repr.kind) {
  70. case SemIR::ValueRepr::Unknown:
  71. CARBON_FATAL("Lowering access to incomplete aggregate type");
  72. case SemIR::ValueRepr::Dependent:
  73. CARBON_FATAL("Lowering access to dependent aggregate type");
  74. case SemIR::ValueRepr::None:
  75. return aggr_value;
  76. case SemIR::ValueRepr::Copy:
  77. // We are holding the values of the aggregate directly, elementwise.
  78. return context.builder().CreateExtractValue(
  79. aggr_value, GetElementIndex(value_repr.type(), idx), name);
  80. case SemIR::ValueRepr::Pointer: {
  81. // The value representation is a pointer to an aggregate that we want
  82. // to index into.
  83. auto value_rep_type = GetPointeeType(value_repr.type());
  84. auto* value_type = context.GetType(value_rep_type);
  85. auto* elem_ptr = context.builder().CreateStructGEP(
  86. value_type, aggr_value, GetElementIndex(value_rep_type, idx),
  87. name);
  88. if (!value_repr.repr.elements_are_values()) {
  89. // `elem_ptr` points to an object representation, which is our
  90. // result.
  91. return elem_ptr;
  92. }
  93. // `elem_ptr` points to a value representation. Load it.
  94. auto result_type = context.GetTypeIdOfInst(result_inst_id);
  95. auto result_value_type = context.GetValueRepr(result_type).type();
  96. return context.LoadObject(result_value_type, elem_ptr,
  97. name + ".load");
  98. }
  99. case SemIR::ValueRepr::Custom:
  100. CARBON_FATAL(
  101. "Aggregate should never have custom value representation");
  102. }
  103. }
  104. case SemIR::ExprCategory::DurableRef:
  105. case SemIR::ExprCategory::EphemeralRef: {
  106. // Just locate the aggregate element.
  107. auto aggr_type = context.GetTypeIdOfInst(aggr_inst_id);
  108. auto object_repr = FunctionContext::TypeInFile{
  109. .file = aggr_type.file,
  110. .type_id = aggr_type.file->types().GetObjectRepr(aggr_type.type_id)};
  111. return context.builder().CreateStructGEP(
  112. context.GetType(object_repr), aggr_value,
  113. GetElementIndex(object_repr, idx), name);
  114. }
  115. }
  116. }
  117. static auto GetStructFieldName(FunctionContext::TypeInFile struct_type,
  118. SemIR::ElementIndex index) -> llvm::StringRef {
  119. auto struct_type_inst = struct_type.file->types().GetAs<SemIR::AnyStructType>(
  120. struct_type.type_id);
  121. auto fields =
  122. struct_type.file->struct_type_fields().Get(struct_type_inst.fields_id);
  123. // We intentionally don't add this to the fingerprint because it's only used
  124. // as an instruction name, and so doesn't affect the semantics of the IR.
  125. return struct_type.file->names().GetIRBaseName(fields[index.index].name_id);
  126. }
  127. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  128. SemIR::ClassElementAccess inst) -> void {
  129. // Find the class that we're performing access into.
  130. auto class_type = context.GetTypeIdOfInst(inst.base_id);
  131. auto object_repr = FunctionContext::TypeInFile{
  132. .file = class_type.file,
  133. .type_id = class_type.file->types().GetObjectRepr(class_type.type_id)};
  134. // Translate the class field access into a struct access on the object
  135. // representation.
  136. context.SetLocal(inst_id, GetAggregateElement(
  137. context, inst.base_id, inst.index, inst_id,
  138. GetStructFieldName(object_repr, inst.index)));
  139. }
  140. static auto EmitAggregateInitializer(FunctionContext& context,
  141. SemIR::InstId init_inst_id,
  142. SemIR::InstBlockId refs_id,
  143. llvm::Twine name) -> llvm::Value* {
  144. auto type = context.GetTypeIdOfInst(init_inst_id);
  145. auto* llvm_type = context.GetType(type);
  146. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  147. switch (context.GetInitRepr(type).kind) {
  148. case SemIR::InitRepr::None: {
  149. // TODO: Add a helper to poison a value slot.
  150. return llvm::PoisonValue::get(llvm_type);
  151. }
  152. case SemIR::InitRepr::InPlace: {
  153. // Finish initialization of constant fields. We will have skipped this
  154. // when emitting the initializers because they have constant values.
  155. //
  156. // TODO: This emits the initializers for constant fields after all
  157. // initialization of non-constant fields. This may be observable in some
  158. // ways such as under a debugger in a debug build. It would be preferable
  159. // to initialize the constant portions of the aggregate first, but this
  160. // will likely need a change to the SemIR representation.
  161. //
  162. // TODO: If most of the bytes of the result have known constant values,
  163. // it'd be nice to emit a memcpy from a constant followed by the
  164. // non-constant initialization.
  165. for (auto [i, ref_id] : llvm::enumerate(refs)) {
  166. if (context.sem_ir().constant_values().Get(ref_id).is_constant()) {
  167. auto dest_id =
  168. SemIR::FindReturnSlotArgForInitializer(context.sem_ir(), ref_id);
  169. auto src_id = ref_id;
  170. auto storage_type = context.GetTypeIdOfInst(dest_id);
  171. context.FinishInit(storage_type, dest_id, src_id);
  172. }
  173. }
  174. // TODO: Add a helper to poison a value slot.
  175. return llvm::PoisonValue::get(llvm_type);
  176. }
  177. case SemIR::InitRepr::ByCopy: {
  178. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  179. CARBON_CHECK(
  180. refs.size() == 1,
  181. "Unexpected size for aggregate with by-copy value representation");
  182. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  183. // need this `insert_value` wrapping.
  184. return context.builder().CreateInsertValue(
  185. llvm::PoisonValue::get(llvm_type), context.GetValue(refs[0]), {0},
  186. name);
  187. }
  188. case SemIR::InitRepr::Incomplete:
  189. CARBON_FATAL("Lowering aggregate initialization of incomplete type {0}",
  190. type.file->types().GetAsInst(type.type_id));
  191. case SemIR::InitRepr::Dependent:
  192. CARBON_FATAL("Lowering aggregate initialization of dependent type {0}",
  193. type.file->types().GetAsInst(type.type_id));
  194. }
  195. }
  196. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  197. SemIR::ClassInit inst) -> void {
  198. context.SetLocal(inst_id,
  199. EmitAggregateInitializer(context, inst_id, inst.elements_id,
  200. "class.init"));
  201. }
  202. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  203. SemIR::StructAccess inst) -> void {
  204. auto struct_type = context.GetTypeIdOfInst(inst.struct_id);
  205. context.SetLocal(inst_id, GetAggregateElement(
  206. context, inst.struct_id, inst.index, inst_id,
  207. GetStructFieldName(struct_type, inst.index)));
  208. }
  209. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  210. SemIR::StructLiteral /*inst*/) -> void {
  211. // A StructLiteral should always be converted to a StructInit or StructValue
  212. // if its value is needed.
  213. }
  214. // Emits the value representation for a struct or tuple whose elements are the
  215. // contents of `refs_id`.
  216. static auto EmitAggregateValueRepr(FunctionContext& context,
  217. SemIR::InstId value_inst_id,
  218. SemIR::InstBlockId refs_id) -> llvm::Value* {
  219. auto type = context.GetTypeIdOfInst(value_inst_id);
  220. auto value_repr = context.GetValueRepr(type);
  221. auto value_type = value_repr.type();
  222. switch (value_repr.repr.kind) {
  223. case SemIR::ValueRepr::Unknown:
  224. CARBON_FATAL("Lowering value of incomplete aggregate type");
  225. case SemIR::ValueRepr::Dependent:
  226. CARBON_FATAL("Lowering value of dependent aggregate type");
  227. case SemIR::ValueRepr::None:
  228. // TODO: Add a helper to get a "no value representation" value.
  229. return llvm::PoisonValue::get(context.GetType(value_type));
  230. case SemIR::ValueRepr::Copy: {
  231. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  232. CARBON_CHECK(
  233. refs.size() == 1,
  234. "Unexpected size for aggregate with by-copy value representation");
  235. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  236. // need this `insert_value` wrapping.
  237. return context.builder().CreateInsertValue(
  238. llvm::PoisonValue::get(context.GetType(value_type)),
  239. context.GetValue(refs[0]), {0});
  240. }
  241. case SemIR::ValueRepr::Pointer: {
  242. auto* llvm_value_rep_type = context.GetType(GetPointeeType(value_type));
  243. // Write the value representation to a local alloca so we can produce a
  244. // pointer to it as the value representation of the struct or tuple.
  245. auto* alloca = context.builder().CreateAlloca(llvm_value_rep_type);
  246. for (auto [i, ref_id] :
  247. llvm::enumerate(context.sem_ir().inst_blocks().Get(refs_id))) {
  248. context.StoreObject(
  249. context.GetValueRepr(context.GetTypeIdOfInst(ref_id)).type(),
  250. context.GetValue(ref_id),
  251. context.builder().CreateStructGEP(llvm_value_rep_type, alloca, i));
  252. }
  253. return alloca;
  254. }
  255. case SemIR::ValueRepr::Custom:
  256. CARBON_FATAL("Aggregate should never have custom value representation");
  257. }
  258. }
  259. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  260. SemIR::StructInit inst) -> void {
  261. context.SetLocal(inst_id,
  262. EmitAggregateInitializer(context, inst_id, inst.elements_id,
  263. "struct.init"));
  264. }
  265. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  266. SemIR::StructValue inst) -> void {
  267. auto type = context.GetTypeIdOfInst(inst_id);
  268. if (auto fn_type =
  269. type.file->types().TryGetAs<SemIR::FunctionType>(type.type_id)) {
  270. context.SetLocal(inst_id, context.GetFileContext(type.file).GetFunction(
  271. fn_type->function_id));
  272. return;
  273. }
  274. context.SetLocal(inst_id,
  275. EmitAggregateValueRepr(context, inst_id, inst.elements_id));
  276. }
  277. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  278. SemIR::TupleAccess inst) -> void {
  279. context.SetLocal(
  280. inst_id, GetAggregateElement(context, inst.tuple_id, inst.index, inst_id,
  281. "tuple.elem"));
  282. }
  283. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  284. SemIR::TupleLiteral /*inst*/) -> void {
  285. // A TupleLiteral should always be converted to a TupleInit or TupleValue if
  286. // its value is needed.
  287. }
  288. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  289. SemIR::TupleInit inst) -> void {
  290. context.SetLocal(inst_id,
  291. EmitAggregateInitializer(context, inst_id, inst.elements_id,
  292. "tuple.init"));
  293. }
  294. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  295. SemIR::TupleValue inst) -> void {
  296. context.SetLocal(inst_id,
  297. EmitAggregateValueRepr(context, inst_id, inst.elements_id));
  298. }
  299. } // namespace Carbon::Lower