handle_aggregates.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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/inst.h"
  11. #include "toolchain/sem_ir/typed_insts.h"
  12. namespace Carbon::Lower {
  13. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  14. SemIR::ClassDecl /*inst*/) -> void {
  15. // No action to perform.
  16. }
  17. // Extracts an element of an aggregate, such as a struct, tuple, or class, by
  18. // index. Depending on the expression category and value representation of the
  19. // aggregate input, this will either produce a value or a reference.
  20. static auto GetAggregateElement(FunctionContext& context,
  21. SemIR::InstId aggr_inst_id,
  22. SemIR::ElementIndex idx,
  23. SemIR::TypeId result_type_id, llvm::Twine name)
  24. -> llvm::Value* {
  25. auto aggr_inst = context.sem_ir().insts().Get(aggr_inst_id);
  26. auto* aggr_value = context.GetValue(aggr_inst_id);
  27. switch (SemIR::GetExprCategory(context.sem_ir(), aggr_inst_id)) {
  28. case SemIR::ExprCategory::Error:
  29. case SemIR::ExprCategory::NotExpr:
  30. case SemIR::ExprCategory::Initializing:
  31. case SemIR::ExprCategory::Mixed:
  32. CARBON_FATAL("Unexpected expression category for aggregate access");
  33. case SemIR::ExprCategory::Value: {
  34. auto value_rep =
  35. SemIR::ValueRepr::ForType(context.sem_ir(), aggr_inst.type_id());
  36. CARBON_CHECK(value_rep.aggregate_kind != SemIR::ValueRepr::NotAggregate,
  37. "aggregate type should have aggregate value representation");
  38. switch (value_rep.kind) {
  39. case SemIR::ValueRepr::Unknown:
  40. CARBON_FATAL("Lowering access to incomplete aggregate type");
  41. case SemIR::ValueRepr::None:
  42. return aggr_value;
  43. case SemIR::ValueRepr::Copy:
  44. // We are holding the values of the aggregate directly, elementwise.
  45. return context.builder().CreateExtractValue(aggr_value, idx.index,
  46. name);
  47. case SemIR::ValueRepr::Pointer: {
  48. // The value representation is a pointer to an aggregate that we want
  49. // to index into.
  50. auto pointee_type_id =
  51. context.sem_ir().GetPointeeType(value_rep.type_id);
  52. auto* value_type = context.GetType(pointee_type_id);
  53. auto* elem_ptr = context.builder().CreateStructGEP(
  54. value_type, aggr_value, idx.index, name);
  55. if (!value_rep.elements_are_values()) {
  56. // `elem_ptr` points to an object representation, which is our
  57. // result.
  58. return elem_ptr;
  59. }
  60. // `elem_ptr` points to a value representation. Load it.
  61. auto result_value_type_id =
  62. SemIR::ValueRepr::ForType(context.sem_ir(), result_type_id)
  63. .type_id;
  64. return context.builder().CreateLoad(
  65. context.GetType(result_value_type_id), elem_ptr, name + ".load");
  66. }
  67. case SemIR::ValueRepr::Custom:
  68. CARBON_FATAL(
  69. "Aggregate should never have custom value representation");
  70. }
  71. }
  72. case SemIR::ExprCategory::DurableRef:
  73. case SemIR::ExprCategory::EphemeralRef: {
  74. // Just locate the aggregate element.
  75. auto* aggr_type = context.GetType(aggr_inst.type_id());
  76. return context.builder().CreateStructGEP(aggr_type, aggr_value, idx.index,
  77. name);
  78. }
  79. }
  80. }
  81. static auto GetStructFieldName(FunctionContext& context,
  82. SemIR::TypeId struct_type_id,
  83. SemIR::ElementIndex index) -> llvm::StringRef {
  84. auto struct_type =
  85. context.sem_ir().types().GetAs<SemIR::StructType>(struct_type_id);
  86. auto fields =
  87. context.sem_ir().struct_type_fields().Get(struct_type.fields_id);
  88. return context.sem_ir().names().GetIRBaseName(fields[index.index].name_id);
  89. }
  90. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  91. SemIR::ClassElementAccess inst) -> void {
  92. // Find the class that we're performing access into.
  93. auto class_type_id = context.sem_ir().insts().Get(inst.base_id).type_id();
  94. SemIR::TypeId object_repr_id =
  95. context.sem_ir().types().GetObjectRepr(class_type_id);
  96. // Translate the class field access into a struct access on the object
  97. // representation.
  98. context.SetLocal(
  99. inst_id, GetAggregateElement(
  100. context, inst.base_id, inst.index, inst.type_id,
  101. GetStructFieldName(context, object_repr_id, inst.index)));
  102. }
  103. static auto EmitAggregateInitializer(FunctionContext& context,
  104. SemIR::TypeId type_id,
  105. SemIR::InstBlockId refs_id,
  106. llvm::Twine name) -> llvm::Value* {
  107. auto* llvm_type = context.GetType(type_id);
  108. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  109. switch (SemIR::InitRepr::ForType(context.sem_ir(), type_id).kind) {
  110. case SemIR::InitRepr::None: {
  111. // TODO: Add a helper to poison a value slot.
  112. return llvm::PoisonValue::get(llvm_type);
  113. }
  114. case SemIR::InitRepr::InPlace: {
  115. // Finish initialization of constant fields. We will have skipped this
  116. // when emitting the initializers because they have constant values.
  117. //
  118. // TODO: This emits the initializers for constant fields after all
  119. // initialization of non-constant fields. This may be observable in some
  120. // ways such as under a debugger in a debug build. It would be preferable
  121. // to initialize the constant portions of the aggregate first, but this
  122. // will likely need a change to the SemIR representation.
  123. //
  124. // TODO: If most of the bytes of the result have known constant values,
  125. // it'd be nice to emit a memcpy from a constant followed by the
  126. // non-constant initialization.
  127. for (auto [i, ref_id] : llvm::enumerate(refs)) {
  128. if (context.sem_ir().constant_values().Get(ref_id).is_constant()) {
  129. auto init =
  130. context.sem_ir().insts().GetAs<SemIR::InitializeFrom>(ref_id);
  131. HandleInst(context, ref_id, init);
  132. }
  133. }
  134. // TODO: Add a helper to poison a value slot.
  135. return llvm::PoisonValue::get(llvm_type);
  136. }
  137. case SemIR::InitRepr::ByCopy: {
  138. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  139. CARBON_CHECK(
  140. refs.size() == 1,
  141. "Unexpected size for aggregate with by-copy value representation");
  142. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  143. // need this `insert_value` wrapping.
  144. return context.builder().CreateInsertValue(
  145. llvm::PoisonValue::get(llvm_type), context.GetValue(refs[0]), {0},
  146. name);
  147. }
  148. case SemIR::InitRepr::Incomplete:
  149. CARBON_FATAL("Lowering aggregate initialization of incomplete type {0}",
  150. context.sem_ir().types().GetAsInst(type_id));
  151. }
  152. }
  153. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  154. SemIR::ClassInit inst) -> void {
  155. context.SetLocal(
  156. inst_id, EmitAggregateInitializer(context, inst.type_id, inst.elements_id,
  157. "class.init"));
  158. }
  159. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  160. SemIR::StructAccess inst) -> void {
  161. auto struct_type_id = context.sem_ir().insts().Get(inst.struct_id).type_id();
  162. context.SetLocal(
  163. inst_id, GetAggregateElement(
  164. context, inst.struct_id, inst.index, inst.type_id,
  165. GetStructFieldName(context, struct_type_id, inst.index)));
  166. }
  167. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  168. SemIR::StructLiteral /*inst*/) -> void {
  169. // A StructLiteral should always be converted to a StructInit or StructValue
  170. // if its value is needed.
  171. }
  172. // Emits the value representation for a struct or tuple whose elements are the
  173. // contents of `refs_id`.
  174. static auto EmitAggregateValueRepr(FunctionContext& context,
  175. SemIR::TypeId type_id,
  176. SemIR::InstBlockId refs_id) -> llvm::Value* {
  177. auto value_rep = SemIR::ValueRepr::ForType(context.sem_ir(), type_id);
  178. switch (value_rep.kind) {
  179. case SemIR::ValueRepr::Unknown:
  180. CARBON_FATAL("Incomplete aggregate type in lowering");
  181. case SemIR::ValueRepr::None:
  182. // TODO: Add a helper to get a "no value representation" value.
  183. return llvm::PoisonValue::get(context.GetType(value_rep.type_id));
  184. case SemIR::ValueRepr::Copy: {
  185. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  186. CARBON_CHECK(
  187. refs.size() == 1,
  188. "Unexpected size for aggregate with by-copy value representation");
  189. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  190. // need this `insert_value` wrapping.
  191. return context.builder().CreateInsertValue(
  192. llvm::PoisonValue::get(context.GetType(value_rep.type_id)),
  193. context.GetValue(refs[0]), {0});
  194. }
  195. case SemIR::ValueRepr::Pointer: {
  196. auto pointee_type_id = context.sem_ir().GetPointeeType(value_rep.type_id);
  197. auto* llvm_value_rep_type = context.GetType(pointee_type_id);
  198. // Write the value representation to a local alloca so we can produce a
  199. // pointer to it as the value representation of the struct or tuple.
  200. auto* alloca = context.builder().CreateAlloca(llvm_value_rep_type);
  201. for (auto [i, ref] :
  202. llvm::enumerate(context.sem_ir().inst_blocks().Get(refs_id))) {
  203. context.builder().CreateStore(
  204. context.GetValue(ref),
  205. context.builder().CreateStructGEP(llvm_value_rep_type, alloca, i));
  206. }
  207. return alloca;
  208. }
  209. case SemIR::ValueRepr::Custom:
  210. CARBON_FATAL("Aggregate should never have custom value representation");
  211. }
  212. }
  213. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  214. SemIR::StructInit inst) -> void {
  215. context.SetLocal(
  216. inst_id, EmitAggregateInitializer(context, inst.type_id, inst.elements_id,
  217. "struct.init"));
  218. }
  219. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  220. SemIR::StructValue inst) -> void {
  221. if (auto fn_type = context.sem_ir().types().TryGetAs<SemIR::FunctionType>(
  222. inst.type_id)) {
  223. context.SetLocal(inst_id, context.GetFunction(fn_type->function_id));
  224. return;
  225. }
  226. context.SetLocal(
  227. inst_id, EmitAggregateValueRepr(context, inst.type_id, inst.elements_id));
  228. }
  229. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  230. SemIR::TupleAccess inst) -> void {
  231. context.SetLocal(inst_id,
  232. GetAggregateElement(context, inst.tuple_id, inst.index,
  233. inst.type_id, "tuple.elem"));
  234. }
  235. auto HandleInst(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  236. SemIR::TupleLiteral /*inst*/) -> void {
  237. // A TupleLiteral should always be converted to a TupleInit or TupleValue if
  238. // its value is needed.
  239. }
  240. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  241. SemIR::TupleInit inst) -> void {
  242. context.SetLocal(
  243. inst_id, EmitAggregateInitializer(context, inst.type_id, inst.elements_id,
  244. "tuple.init"));
  245. }
  246. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  247. SemIR::TupleValue inst) -> void {
  248. context.SetLocal(
  249. inst_id, EmitAggregateValueRepr(context, inst.type_id, inst.elements_id));
  250. }
  251. } // namespace Carbon::Lower