constant.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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/constant.h"
  5. #include "llvm/ADT/STLExtras.h"
  6. #include "llvm/IR/Constants.h"
  7. #include "llvm/IR/Value.h"
  8. #include "toolchain/base/kind_switch.h"
  9. #include "toolchain/lower/file_context.h"
  10. #include "toolchain/sem_ir/inst.h"
  11. #include "toolchain/sem_ir/typed_insts.h"
  12. namespace Carbon::Lower {
  13. // Context and shared functionality for lowering constant values.
  14. class ConstantContext {
  15. public:
  16. explicit ConstantContext(FileContext& file_context,
  17. llvm::MutableArrayRef<llvm::Constant*> constants)
  18. : file_context_(&file_context), constants_(constants) {}
  19. // Gets the lowered constant value for an instruction, which must have a
  20. // constant value that has already been lowered.
  21. auto GetConstant(SemIR::InstId inst_id) const -> llvm::Constant* {
  22. return GetConstant(file_context_->sem_ir().constant_values().Get(inst_id));
  23. }
  24. // Gets the lowered constant value for a constant that has already been
  25. // lowered.
  26. auto GetConstant(SemIR::ConstantId const_id) const -> llvm::Constant* {
  27. CARBON_CHECK(const_id.is_template(), "Unexpected constant ID {0}",
  28. const_id);
  29. auto inst_id =
  30. file_context_->sem_ir().constant_values().GetInstId(const_id);
  31. CARBON_CHECK(
  32. inst_id.index >= 0 && inst_id.index <= last_lowered_constant_index_,
  33. "Queried constant {0} with instruction {1} that has not been lowered "
  34. "yet",
  35. const_id, inst_id);
  36. return constants_[inst_id.index];
  37. }
  38. // Returns a constant for the case of a value that should never be used.
  39. auto GetUnusedConstant(SemIR::TypeId /*type_id*/) const -> llvm::Constant* {
  40. // TODO: Consider using a poison value of the appropriate type.
  41. return nullptr;
  42. }
  43. // Gets a callable's function. Returns nullptr for a builtin.
  44. auto GetFunction(SemIR::FunctionId function_id) -> llvm::Function* {
  45. return file_context_->GetFunction(function_id);
  46. }
  47. // Returns a lowered type for the given type_id.
  48. auto GetType(SemIR::TypeId type_id) const -> llvm::Type* {
  49. return file_context_->GetType(type_id);
  50. }
  51. // Returns a lowered value to use for a value of type `type`.
  52. auto GetTypeAsValue() const -> llvm::Constant* {
  53. return file_context_->GetTypeAsValue();
  54. }
  55. // Sets the index of the constant we most recently lowered. This is used to
  56. // check we don't look at constants that we've not lowered yet.
  57. auto SetLastLoweredConstantIndex(int32_t index) {
  58. last_lowered_constant_index_ = index;
  59. }
  60. auto llvm_context() const -> llvm::LLVMContext& {
  61. return file_context_->llvm_context();
  62. }
  63. auto llvm_module() const -> llvm::Module& {
  64. return file_context_->llvm_module();
  65. }
  66. auto sem_ir() const -> const SemIR::File& { return file_context_->sem_ir(); }
  67. private:
  68. FileContext* file_context_;
  69. llvm::MutableArrayRef<llvm::Constant*> constants_;
  70. int32_t last_lowered_constant_index_ = -1;
  71. };
  72. // Emits an aggregate constant of LLVM type `Type` whose elements are the
  73. // contents of `refs_id`.
  74. template <typename ConstantType, typename Type>
  75. static auto EmitAggregateConstant(ConstantContext& context,
  76. SemIR::InstBlockId refs_id, Type* llvm_type)
  77. -> llvm::Constant* {
  78. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  79. llvm::SmallVector<llvm::Constant*> elements;
  80. elements.reserve(refs.size());
  81. for (auto ref : refs) {
  82. elements.push_back(context.GetConstant(ref));
  83. }
  84. return ConstantType::get(llvm_type, elements);
  85. }
  86. // For each instruction InstT, there is a function below to convert it to an
  87. // `llvm::Constant*`:
  88. //
  89. // auto EmitAsConstant(ConstantContext& context, SemIR::InstT inst)
  90. // -> llvm::Constant*;
  91. template <typename InstT>
  92. requires(InstT::Kind.constant_kind() == SemIR::InstConstantKind::Never ||
  93. InstT::Kind.constant_kind() == SemIR::InstConstantKind::SymbolicOnly)
  94. static auto EmitAsConstant(ConstantContext& /*context*/, InstT inst)
  95. -> llvm::Constant* {
  96. CARBON_FATAL("Unexpected constant instruction kind {0}", inst);
  97. }
  98. // For constants that are always of type `type`, produce the trivial runtime
  99. // representation of type `type`.
  100. template <typename InstT>
  101. requires(InstT::Kind.is_type() == SemIR::InstIsType::Always)
  102. static auto EmitAsConstant(ConstantContext& context, InstT /*inst*/)
  103. -> llvm::Constant* {
  104. return context.GetTypeAsValue();
  105. }
  106. static auto EmitAsConstant(ConstantContext& context, SemIR::StructValue inst)
  107. -> llvm::Constant* {
  108. return EmitAggregateConstant<llvm::ConstantStruct>(
  109. context, inst.elements_id,
  110. cast<llvm::StructType>(context.GetType(inst.type_id)));
  111. }
  112. static auto EmitAsConstant(ConstantContext& context, SemIR::TupleValue inst)
  113. -> llvm::Constant* {
  114. // TODO: Add an ArrayValue instruction and stop using TupleValues to represent
  115. // array constants.
  116. if (context.sem_ir().types().Is<SemIR::ArrayType>(inst.type_id)) {
  117. return EmitAggregateConstant<llvm::ConstantArray>(
  118. context, inst.elements_id,
  119. cast<llvm::ArrayType>(context.GetType(inst.type_id)));
  120. }
  121. return EmitAggregateConstant<llvm::ConstantStruct>(
  122. context, inst.elements_id,
  123. cast<llvm::StructType>(context.GetType(inst.type_id)));
  124. }
  125. static auto EmitAsConstant(ConstantContext& /*context*/, SemIR::AddrOf /*inst*/)
  126. -> llvm::Constant* {
  127. // TODO: Constant lvalue support. For now we have no constant lvalues, so we
  128. // should never form a constant AddrOf.
  129. CARBON_FATAL("AddrOf constants not supported yet");
  130. }
  131. static auto EmitAsConstant(ConstantContext& context,
  132. SemIR::AssociatedEntity inst) -> llvm::Constant* {
  133. return context.GetUnusedConstant(inst.type_id);
  134. }
  135. static auto EmitAsConstant(ConstantContext& context, SemIR::BaseDecl inst)
  136. -> llvm::Constant* {
  137. return context.GetUnusedConstant(inst.type_id);
  138. }
  139. static auto EmitAsConstant(ConstantContext& context, SemIR::BoolLiteral inst)
  140. -> llvm::Constant* {
  141. return llvm::ConstantInt::get(llvm::Type::getInt1Ty(context.llvm_context()),
  142. inst.value.index);
  143. }
  144. static auto EmitAsConstant(ConstantContext& context, SemIR::BoundMethod inst)
  145. -> llvm::Constant* {
  146. // Propagate just the function; the object is separately provided to the
  147. // enclosing call as an implicit argument.
  148. return context.GetConstant(inst.function_id);
  149. }
  150. static auto EmitAsConstant(ConstantContext& context,
  151. SemIR::CompleteTypeWitness inst) -> llvm::Constant* {
  152. return context.GetUnusedConstant(inst.type_id);
  153. }
  154. static auto EmitAsConstant(ConstantContext& context, SemIR::FieldDecl inst)
  155. -> llvm::Constant* {
  156. return context.GetUnusedConstant(inst.type_id);
  157. }
  158. static auto EmitAsConstant(ConstantContext& context, SemIR::FloatLiteral inst)
  159. -> llvm::Constant* {
  160. const llvm::APFloat& value = context.sem_ir().floats().Get(inst.float_id);
  161. return llvm::ConstantFP::get(context.GetType(inst.type_id), value);
  162. }
  163. static auto EmitAsConstant(ConstantContext& context,
  164. SemIR::InterfaceWitness inst) -> llvm::Constant* {
  165. // TODO: For dynamic dispatch, we might want to lower witness tables as
  166. // constants.
  167. return context.GetUnusedConstant(inst.type_id);
  168. }
  169. static auto EmitAsConstant(ConstantContext& /*context*/,
  170. SemIR::ImplDecl /*inst*/) -> llvm::Constant* {
  171. // An ImplDecl isn't a value, so this constant value won't ever be used.
  172. // It also doesn't even have a type, so we can't use GetUnusedConstant.
  173. return nullptr;
  174. }
  175. static auto EmitAsConstant(ConstantContext& context, SemIR::IntValue inst)
  176. -> llvm::Constant* {
  177. auto* type = context.GetType(inst.type_id);
  178. // IntLiteral is represented as an empty struct. All other integer types are
  179. // represented as an LLVM integer type.
  180. if (!llvm::isa<llvm::IntegerType>(type)) {
  181. auto* struct_type = llvm::dyn_cast<llvm::StructType>(type);
  182. CARBON_CHECK(struct_type && struct_type->getNumElements() == 0);
  183. return llvm::ConstantStruct::get(struct_type);
  184. }
  185. return llvm::ConstantInt::get(type, context.sem_ir().ints().Get(inst.int_id));
  186. }
  187. static auto EmitAsConstant(ConstantContext& context, SemIR::Namespace inst)
  188. -> llvm::Constant* {
  189. return context.GetUnusedConstant(inst.type_id);
  190. }
  191. static auto EmitAsConstant(ConstantContext& context,
  192. SemIR::SpecificFunction inst) -> llvm::Constant* {
  193. return context.GetUnusedConstant(inst.type_id);
  194. }
  195. static auto EmitAsConstant(ConstantContext& /*context*/,
  196. SemIR::StringLiteral inst) -> llvm::Constant* {
  197. CARBON_FATAL("TODO: Add support: {0}", inst);
  198. }
  199. static auto EmitAsConstant(ConstantContext& /*context*/,
  200. SemIR::StructTypeField /*inst*/) -> llvm::Constant* {
  201. // A StructTypeField isn't a value, so this constant value won't ever be used.
  202. // It also doesn't even have a type, so we can't use GetUnusedConstant.
  203. return nullptr;
  204. }
  205. auto LowerConstants(FileContext& file_context,
  206. llvm::MutableArrayRef<llvm::Constant*> constants) -> void {
  207. ConstantContext context(file_context, constants);
  208. // Lower each constant in InstId order. This guarantees we lower the
  209. // dependencies of a constant before we lower the constant itself.
  210. for (auto [inst_id_val, const_id] :
  211. llvm::enumerate(file_context.sem_ir().constant_values().array_ref())) {
  212. if (!const_id.is_valid() || !const_id.is_template()) {
  213. // We are only interested in lowering template constants.
  214. continue;
  215. }
  216. auto inst_id = file_context.sem_ir().constant_values().GetInstId(const_id);
  217. if (inst_id.index != static_cast<int32_t>(inst_id_val)) {
  218. // This isn't the instruction that defines the constant.
  219. continue;
  220. }
  221. auto inst = file_context.sem_ir().insts().Get(inst_id);
  222. if (inst.type_id().is_valid() &&
  223. !file_context.sem_ir().types().IsComplete(inst.type_id())) {
  224. // If a constant doesn't have a complete type, that means we imported it
  225. // but didn't actually use it.
  226. continue;
  227. }
  228. llvm::Constant* value = nullptr;
  229. CARBON_KIND_SWITCH(inst) {
  230. #define CARBON_SEM_IR_INST_KIND(Name) \
  231. case CARBON_KIND(SemIR::Name const_inst): { \
  232. value = EmitAsConstant(context, const_inst); \
  233. break; \
  234. }
  235. #include "toolchain/sem_ir/inst_kind.def"
  236. }
  237. constants[inst_id.index] = value;
  238. context.SetLastLoweredConstantIndex(inst_id.index);
  239. }
  240. } // namespace Carbon::Lower
  241. } // namespace Carbon::Lower