constant.cpp 10 KB

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