aggregate.cpp 9.7 KB

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