handle_aggregates.cpp 14 KB

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