constant.cpp 10 KB

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