constant.cpp 10 KB

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