builtin_function_kind.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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/sem_ir/builtin_function_kind.h"
  5. #include <utility>
  6. #include "toolchain/sem_ir/file.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. #include "toolchain/sem_ir/typed_insts.h"
  9. namespace Carbon::SemIR {
  10. // A function that validates that a builtin was declared properly.
  11. using ValidateFn = auto(const File& sem_ir, llvm::ArrayRef<TypeId> arg_types,
  12. TypeId return_type) -> bool;
  13. namespace {
  14. // Information about a builtin function.
  15. struct BuiltinInfo {
  16. llvm::StringLiteral name;
  17. ValidateFn* validate;
  18. };
  19. // The maximum number of type parameters any builtin needs.
  20. constexpr int MaxTypeParams = 2;
  21. // State used when validating a builtin signature that persists between
  22. // individual checks.
  23. struct ValidateState {
  24. // The type values of type parameters in the builtin signature. Invalid if
  25. // either no value has been deduced yet or the parameter is not used.
  26. TypeId type_params[MaxTypeParams] = {TypeId::Invalid, TypeId::Invalid};
  27. };
  28. // Constraint that a type is generic type parameter `I` of the builtin,
  29. // satisfying `TypeConstraint`. See ValidateSignature for details.
  30. template <int I, typename TypeConstraint>
  31. struct TypeParam {
  32. static_assert(I >= 0 && I < MaxTypeParams);
  33. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  34. -> bool {
  35. if (state.type_params[I].is_valid() && type_id != state.type_params[I]) {
  36. return false;
  37. }
  38. state.type_params[I] = type_id;
  39. return TypeConstraint::Check(sem_ir, state, type_id);
  40. }
  41. };
  42. // Constraint that a type is a specific builtin. See ValidateSignature for
  43. // details.
  44. template <const InstId& BuiltinId>
  45. struct BuiltinType {
  46. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  47. TypeId type_id) -> bool {
  48. return sem_ir.types().GetInstId(type_id) == BuiltinId;
  49. }
  50. };
  51. // Constraint that a type is `bool`.
  52. using Bool = BuiltinType<InstId::BuiltinBoolType>;
  53. // Constraint that requires the type to be an integer type.
  54. struct AnyInt {
  55. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  56. -> bool {
  57. // TODO: Support Core.BigInt once it exists.
  58. if (BuiltinType<InstId::BuiltinIntType>::Check(sem_ir, state, type_id)) {
  59. return true;
  60. }
  61. return sem_ir.types().Is<IntType>(type_id);
  62. }
  63. };
  64. // Constraint that requires the type to be the type type.
  65. using Type = BuiltinType<InstId::BuiltinTypeType>;
  66. } // namespace
  67. // Validates that this builtin has a signature matching the specified signature.
  68. //
  69. // `SignatureFnType` is a C++ function type that describes the signature that is
  70. // expected for this builtin. For example, `auto (AnyInt, AnyInt) -> AnyInt`
  71. // specifies that the builtin takes values of two integer types and returns a
  72. // value of a third integer type. Types used within the signature should provide
  73. // a `Check` function that validates that the Carbon type is expected:
  74. //
  75. // auto Check(const File&, ValidateState&, TypeId) -> bool;
  76. //
  77. // To constrain that the same type is used in multiple places in the signature,
  78. // `TypeParam<I, T>` can be used. For example:
  79. //
  80. // auto (TypeParam<0, AnyInt>, AnyInt) -> TypeParam<0, AnyInt>
  81. //
  82. // describes a builtin that takes two integers, and whose return type matches
  83. // its first parameter type. For convenience, typedefs for `TypeParam<I, T>`
  84. // are used in the descriptions of the builtins.
  85. template <typename SignatureFnType>
  86. static auto ValidateSignature(const File& sem_ir,
  87. llvm::ArrayRef<TypeId> arg_types,
  88. TypeId return_type) -> bool {
  89. using SignatureTraits = llvm::function_traits<SignatureFnType*>;
  90. ValidateState state;
  91. // Must have expected number of arguments.
  92. if (arg_types.size() != SignatureTraits::num_args) {
  93. return false;
  94. }
  95. // Argument types must match.
  96. if (![&]<std::size_t... Indexes>(std::index_sequence<Indexes...>) {
  97. return ((SignatureTraits::template arg_t<Indexes>::Check(
  98. sem_ir, state, arg_types[Indexes])) &&
  99. ...);
  100. }(std::make_index_sequence<SignatureTraits::num_args>())) {
  101. return false;
  102. }
  103. // Result type must match.
  104. if (!SignatureTraits::result_t::Check(sem_ir, state, return_type)) {
  105. return false;
  106. }
  107. return true;
  108. }
  109. // Descriptions of builtin functions follow. For each builtin, a corresponding
  110. // `BuiltinInfo` constant is declared describing properties of that builtin.
  111. namespace BuiltinFunctionInfo {
  112. // Convenience name used in the builtin type signatures below for a first
  113. // generic type parameter that is constrained to be an integer type.
  114. using IntT = TypeParam<0, AnyInt>;
  115. // Convenience name used in the builtin type signatures below for a second
  116. // generic type parameter that is constrained to be an integer type.
  117. using IntU = TypeParam<1, AnyInt>;
  118. // Not a builtin function.
  119. constexpr BuiltinInfo None = {"", nullptr};
  120. // Returns the `i32` type. Doesn't take a bit size because we need an integer
  121. // type as a basis for that.
  122. constexpr BuiltinInfo IntMakeType32 = {"int.make_type_32",
  123. ValidateSignature<auto()->Type>};
  124. // Returns the `iN` type.
  125. // TODO: Should we use a more specific type as the type of the bit width?
  126. constexpr BuiltinInfo IntMakeTypeSigned = {
  127. "int.make_type_signed", ValidateSignature<auto(AnyInt)->Type>};
  128. // Returns the `uN` type.
  129. constexpr BuiltinInfo IntMakeTypeUnsigned = {
  130. "int.make_type_unsigned", ValidateSignature<auto(AnyInt)->Type>};
  131. // Returns float types, such as `f64`. Currently only supports `f64`.
  132. constexpr BuiltinInfo FloatMakeType = {"float.make_type",
  133. ValidateSignature<auto(AnyInt)->Type>};
  134. // Returns the `bool` type.
  135. constexpr BuiltinInfo BoolMakeType = {"bool.make_type",
  136. ValidateSignature<auto()->Type>};
  137. // "int.negate": integer negation.
  138. constexpr BuiltinInfo IntNegate = {"int.negate",
  139. ValidateSignature<auto(IntT)->IntT>};
  140. // "int.add": integer addition.
  141. constexpr BuiltinInfo IntAdd = {"int.add",
  142. ValidateSignature<auto(IntT, IntT)->IntT>};
  143. // "int.sub": integer subtraction.
  144. constexpr BuiltinInfo IntSub = {"int.sub",
  145. ValidateSignature<auto(IntT, IntT)->IntT>};
  146. // "int.mul": integer multiplication.
  147. constexpr BuiltinInfo IntMul = {"int.mul",
  148. ValidateSignature<auto(IntT, IntT)->IntT>};
  149. // "int.div": integer division.
  150. constexpr BuiltinInfo IntDiv = {"int.div",
  151. ValidateSignature<auto(IntT, IntT)->IntT>};
  152. // "int.mod": integer modulo.
  153. constexpr BuiltinInfo IntMod = {"int.mod",
  154. ValidateSignature<auto(IntT, IntT)->IntT>};
  155. // "int.complement": integer bitwise complement.
  156. constexpr BuiltinInfo IntComplement = {"int.complement",
  157. ValidateSignature<auto(IntT)->IntT>};
  158. // "int.and": integer bitwise and.
  159. constexpr BuiltinInfo IntAnd = {"int.and",
  160. ValidateSignature<auto(IntT, IntT)->IntT>};
  161. // "int.or": integer bitwise or.
  162. constexpr BuiltinInfo IntOr = {"int.or",
  163. ValidateSignature<auto(IntT, IntT)->IntT>};
  164. // "int.xor": integer bitwise xor.
  165. constexpr BuiltinInfo IntXor = {"int.xor",
  166. ValidateSignature<auto(IntT, IntT)->IntT>};
  167. // "int.left_shift": integer left shift.
  168. constexpr BuiltinInfo IntLeftShift = {
  169. "int.left_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  170. // "int.left_shift": integer right shift.
  171. constexpr BuiltinInfo IntRightShift = {
  172. "int.right_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  173. // "int.eq": integer equality comparison.
  174. constexpr BuiltinInfo IntEq = {"int.eq",
  175. ValidateSignature<auto(IntT, IntT)->Bool>};
  176. // "int.neq": integer non-equality comparison.
  177. constexpr BuiltinInfo IntNeq = {"int.neq",
  178. ValidateSignature<auto(IntT, IntT)->Bool>};
  179. // "int.less": integer less than comparison.
  180. constexpr BuiltinInfo IntLess = {"int.less",
  181. ValidateSignature<auto(IntT, IntT)->Bool>};
  182. // "int.less_eq": integer less than or equal comparison.
  183. constexpr BuiltinInfo IntLessEq = {"int.less_eq",
  184. ValidateSignature<auto(IntT, IntT)->Bool>};
  185. // "int.greater": integer greater than comparison.
  186. constexpr BuiltinInfo IntGreater = {"int.greater",
  187. ValidateSignature<auto(IntT, IntT)->Bool>};
  188. // "int.greater_eq": integer greater than or equal comparison.
  189. constexpr BuiltinInfo IntGreaterEq = {
  190. "int.greater_eq", ValidateSignature<auto(IntT, IntT)->Bool>};
  191. } // namespace BuiltinFunctionInfo
  192. CARBON_DEFINE_ENUM_CLASS_NAMES(BuiltinFunctionKind) = {
  193. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  194. BuiltinFunctionInfo::Name.name,
  195. #include "toolchain/sem_ir/builtin_function_kind.def"
  196. };
  197. // Returns the builtin function kind with the given name, or None if the name
  198. // is unknown.
  199. auto BuiltinFunctionKind::ForBuiltinName(llvm::StringRef name)
  200. -> BuiltinFunctionKind {
  201. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  202. if (name == BuiltinFunctionInfo::Name.name) { \
  203. return BuiltinFunctionKind::Name; \
  204. }
  205. #include "toolchain/sem_ir/builtin_function_kind.def"
  206. return BuiltinFunctionKind::None;
  207. }
  208. // Returns the builtin function kind corresponding to the given function
  209. // callee, or None if the callee is not known to be a builtin.
  210. auto BuiltinFunctionKind::ForCallee(const File& sem_ir, InstId callee_id)
  211. -> BuiltinFunctionKind {
  212. if (auto bound_method =
  213. sem_ir.insts().TryGetAs<SemIR::BoundMethod>(callee_id)) {
  214. callee_id = bound_method->function_id;
  215. }
  216. callee_id = sem_ir.constant_values().Get(callee_id).inst_id();
  217. if (!callee_id.is_valid()) {
  218. return SemIR::BuiltinFunctionKind::None;
  219. }
  220. if (auto callee = sem_ir.insts().TryGetAs<SemIR::FunctionDecl>(callee_id)) {
  221. return sem_ir.functions().Get(callee->function_id).builtin_kind;
  222. }
  223. return SemIR::BuiltinFunctionKind::None;
  224. }
  225. auto BuiltinFunctionKind::IsValidType(const File& sem_ir,
  226. llvm::ArrayRef<TypeId> arg_types,
  227. TypeId return_type) const -> bool {
  228. static constexpr ValidateFn* ValidateFns[] = {
  229. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  230. BuiltinFunctionInfo::Name.validate,
  231. #include "toolchain/sem_ir/builtin_function_kind.def"
  232. };
  233. return ValidateFns[AsInt()](sem_ir, arg_types, return_type);
  234. }
  235. } // namespace Carbon::SemIR