aggregate.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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/lower/aggregate.h"
  5. #include "llvm/ADT/STLExtras.h"
  6. #include "toolchain/sem_ir/expr_info.h"
  7. #include "toolchain/sem_ir/inst.h"
  8. #include "toolchain/sem_ir/inst_kind.h"
  9. #include "toolchain/sem_ir/type_info.h"
  10. #include "toolchain/sem_ir/typed_insts.h"
  11. namespace Carbon::Lower {
  12. static auto GetPointeeType(FunctionContext::TypeInFile type)
  13. -> FunctionContext::TypeInFile {
  14. return {.file = type.file,
  15. .type_id = type.file->GetPointeeType(type.type_id)};
  16. }
  17. // Given an index within a SemIR aggregate type, returns the corresponding index
  18. // of the element within the LLVM type suitable for use with the getelementptr
  19. // instruction.
  20. static auto GetElementIndex(FunctionContext::TypeInFile type,
  21. SemIR::ElementIndex idx) -> unsigned int {
  22. auto type_inst = type.file->types().GetAsInst(type.type_id);
  23. if (auto custom_layout_type = type_inst.TryAs<SemIR::CustomLayoutType>()) {
  24. // For custom layout types, we form an array of i8 as the LLVM type, so the
  25. // offset in the type is the getelementptr index.
  26. // TODO: This offset might not fit into an `unsigned int`.
  27. auto offset = type.file->custom_layouts().Get(
  28. custom_layout_type
  29. ->layout_id)[SemIR::CustomLayoutId::FirstFieldIndex + idx.index];
  30. CARBON_CHECK(offset == offset.AlignedTo(SemIR::ObjectSize::Bytes(1)),
  31. "Element offset not byte-aligned: {0}", offset);
  32. return offset.bytes();
  33. }
  34. // For now, struct and tuple types map directly into LLVM struct types with
  35. // identical field numbering.
  36. CARBON_CHECK((type_inst.IsOneOf<SemIR::StructType, SemIR::TupleType>()),
  37. "Indexing unexpected aggregate type {0}", type_inst);
  38. return idx.index;
  39. }
  40. // Extracts an element of an aggregate, such as a struct, tuple, or class, by
  41. // index. Depending on the expression category and value representation of the
  42. // aggregate input, this will either produce a value or a reference.
  43. auto GetAggregateElement(FunctionContext& context, SemIR::InstId aggr_inst_id,
  44. SemIR::ElementIndex idx, SemIR::InstId result_inst_id,
  45. llvm::Twine name) -> llvm::Value* {
  46. auto* aggr_value = context.GetValue(aggr_inst_id);
  47. switch (SemIR::GetExprCategory(context.sem_ir(), aggr_inst_id)) {
  48. case SemIR::ExprCategory::RefTagged:
  49. case SemIR::ExprCategory::Error:
  50. case SemIR::ExprCategory::NotExpr:
  51. case SemIR::ExprCategory::Pattern:
  52. case SemIR::ExprCategory::ReprInitializing:
  53. case SemIR::ExprCategory::InPlaceInitializing:
  54. case SemIR::ExprCategory::Mixed:
  55. case SemIR::ExprCategory::Dependent:
  56. CARBON_FATAL(
  57. "Unexpected expression category for aggregate access into {0}",
  58. context.sem_ir().insts().Get(aggr_inst_id));
  59. case SemIR::ExprCategory::Value: {
  60. auto aggr_type = context.GetTypeIdOfInst(aggr_inst_id);
  61. auto value_repr = context.GetValueRepr(aggr_type);
  62. CARBON_CHECK(
  63. value_repr.repr.aggregate_kind != SemIR::ValueRepr::NotAggregate,
  64. "aggregate type should have aggregate value representation");
  65. switch (value_repr.repr.kind) {
  66. case SemIR::ValueRepr::Unknown:
  67. CARBON_FATAL("Lowering access to incomplete aggregate type");
  68. case SemIR::ValueRepr::Dependent:
  69. CARBON_FATAL("Lowering access to dependent aggregate type");
  70. case SemIR::ValueRepr::None:
  71. return aggr_value;
  72. case SemIR::ValueRepr::Copy:
  73. // We are holding the values of the aggregate directly, elementwise.
  74. return context.builder().CreateExtractValue(
  75. aggr_value, GetElementIndex(value_repr.type(), idx), name);
  76. case SemIR::ValueRepr::Pointer: {
  77. // The value representation is a pointer to an aggregate that we want
  78. // to index into.
  79. auto value_rep_type = GetPointeeType(value_repr.type());
  80. auto* value_type = context.GetType(value_rep_type);
  81. auto* elem_ptr = context.builder().CreateStructGEP(
  82. value_type, aggr_value, GetElementIndex(value_rep_type, idx),
  83. name);
  84. if (!value_repr.repr.elements_are_values()) {
  85. // `elem_ptr` points to an object representation, which is our
  86. // result.
  87. return elem_ptr;
  88. }
  89. // `elem_ptr` points to a value representation. Load it.
  90. auto result_type = context.GetTypeIdOfInst(result_inst_id);
  91. auto result_value_type = context.GetValueRepr(result_type).type();
  92. return context.LoadObject(result_value_type, elem_ptr,
  93. name + ".load");
  94. }
  95. case SemIR::ValueRepr::Custom:
  96. CARBON_FATAL(
  97. "Aggregate should never have custom value representation");
  98. }
  99. }
  100. case SemIR::ExprCategory::DurableRef:
  101. case SemIR::ExprCategory::EphemeralRef: {
  102. // Just locate the aggregate element.
  103. auto aggr_type = context.GetTypeIdOfInst(aggr_inst_id);
  104. auto object_repr = FunctionContext::TypeInFile{
  105. .file = aggr_type.file,
  106. .type_id = aggr_type.file->types().GetObjectRepr(aggr_type.type_id)};
  107. return context.builder().CreateStructGEP(
  108. context.GetType(object_repr), aggr_value,
  109. GetElementIndex(object_repr, idx), name);
  110. }
  111. }
  112. }
  113. auto EmitAggregateValueRepr(FunctionContext& context,
  114. SemIR::InstId value_inst_id,
  115. SemIR::InstBlockId refs_id) -> llvm::Value* {
  116. auto type = context.GetTypeIdOfInst(value_inst_id);
  117. auto value_repr = context.GetValueRepr(type);
  118. auto value_type = value_repr.type();
  119. switch (value_repr.repr.kind) {
  120. case SemIR::ValueRepr::Unknown:
  121. CARBON_FATAL("Lowering value of incomplete aggregate type");
  122. case SemIR::ValueRepr::Dependent:
  123. CARBON_FATAL("Lowering value of dependent aggregate type");
  124. case SemIR::ValueRepr::None:
  125. // TODO: Add a helper to get a "no value representation" value.
  126. return llvm::PoisonValue::get(context.GetType(value_type));
  127. case SemIR::ValueRepr::Copy: {
  128. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  129. CARBON_CHECK(
  130. refs.size() == 1,
  131. "Unexpected size for aggregate with by-copy value representation");
  132. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  133. // need this `insert_value` wrapping.
  134. return context.builder().CreateInsertValue(
  135. llvm::PoisonValue::get(context.GetType(value_type)),
  136. context.GetValue(refs[0]), {0});
  137. }
  138. case SemIR::ValueRepr::Pointer: {
  139. auto* llvm_value_rep_type = context.GetType(GetPointeeType(value_type));
  140. // Write the value representation to a local alloca so we can produce a
  141. // pointer to it as the value representation of the struct or tuple.
  142. auto* alloca = context.builder().CreateAlloca(llvm_value_rep_type);
  143. for (auto [i, ref_id] :
  144. llvm::enumerate(context.sem_ir().inst_blocks().Get(refs_id))) {
  145. context.StoreObject(
  146. context.GetValueRepr(context.GetTypeIdOfInst(ref_id)).type(),
  147. context.GetValue(ref_id),
  148. context.builder().CreateStructGEP(llvm_value_rep_type, alloca, i));
  149. }
  150. return alloca;
  151. }
  152. case SemIR::ValueRepr::Custom:
  153. CARBON_FATAL("Aggregate should never have custom value representation");
  154. }
  155. }
  156. auto EmitAggregateInitializer(FunctionContext& context,
  157. SemIR::InstId init_inst_id,
  158. SemIR::InstBlockId refs_id, llvm::Twine name)
  159. -> llvm::Value* {
  160. auto type = context.GetTypeIdOfInst(init_inst_id);
  161. auto* llvm_type = context.GetType(type);
  162. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  163. switch (context.GetInitRepr(type).kind) {
  164. case SemIR::InitRepr::None: {
  165. // TODO: Add a helper to poison a value slot.
  166. return llvm::PoisonValue::get(llvm_type);
  167. }
  168. case SemIR::InitRepr::InPlace: {
  169. // Finish initialization of constant fields. We will have skipped this
  170. // when emitting the initializers because they have constant values.
  171. //
  172. // TODO: This emits the initializers for constant fields after all
  173. // initialization of non-constant fields. This may be observable in some
  174. // ways such as under a debugger in a debug build. It would be preferable
  175. // to initialize the constant portions of the aggregate first, but this
  176. // will likely need a change to the SemIR representation.
  177. //
  178. // TODO: If most of the bytes of the result have known constant values,
  179. // it'd be nice to emit a memcpy from a constant followed by the
  180. // non-constant initialization.
  181. for (auto [i, ref_id] : llvm::enumerate(refs)) {
  182. if (context.sem_ir().constant_values().Get(ref_id).is_constant()) {
  183. auto dest_id =
  184. SemIR::FindStorageArgForInitializer(context.sem_ir(), ref_id);
  185. auto src_id = ref_id;
  186. auto storage_type = context.GetTypeIdOfInst(dest_id);
  187. context.InitializeStorage(storage_type, dest_id, src_id);
  188. }
  189. }
  190. // TODO: Add a helper to poison a value slot.
  191. return llvm::PoisonValue::get(llvm_type);
  192. }
  193. case SemIR::InitRepr::ByCopy: {
  194. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  195. CARBON_CHECK(
  196. refs.size() == 1,
  197. "Unexpected size for aggregate with by-copy value representation");
  198. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  199. // need this `insert_value` wrapping.
  200. return context.builder().CreateInsertValue(
  201. llvm::PoisonValue::get(llvm_type), context.GetValue(refs[0]), {0},
  202. name);
  203. }
  204. case SemIR::InitRepr::Abstract:
  205. CARBON_FATAL("Lowering aggregate initialization of abstract type {0}",
  206. type.file->types().GetAsInst(type.type_id));
  207. case SemIR::InitRepr::Incomplete:
  208. CARBON_FATAL("Lowering aggregate initialization of incomplete type {0}",
  209. type.file->types().GetAsInst(type.type_id));
  210. case SemIR::InitRepr::Dependent:
  211. CARBON_FATAL("Lowering aggregate initialization of dependent type {0}",
  212. type.file->types().GetAsInst(type.type_id));
  213. }
  214. }
  215. } // namespace Carbon::Lower