handle_aggregates.cpp 14 KB

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