builtin_function_kind.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. if (!TypeConstraint::Check(sem_ir, state, type_id)) {
  39. return false;
  40. }
  41. state.type_params[I] = type_id;
  42. return true;
  43. }
  44. };
  45. // Constraint that a type is a specific builtin. See ValidateSignature for
  46. // details.
  47. template <const InstId& BuiltinId>
  48. struct BuiltinType {
  49. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  50. TypeId type_id) -> bool {
  51. return sem_ir.types().GetInstId(type_id) == BuiltinId;
  52. }
  53. };
  54. // Constraint that a type is `()`, used as the return type of builtin functions
  55. // with no return value.
  56. struct NoReturn {
  57. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  58. TypeId type_id) -> bool {
  59. auto tuple = sem_ir.types().TryGetAs<SemIR::TupleType>(type_id);
  60. if (!tuple) {
  61. return false;
  62. }
  63. return sem_ir.type_blocks().Get(tuple->elements_id).empty();
  64. }
  65. };
  66. // Constraint that a type is `bool`.
  67. using Bool = BuiltinType<BoolType::SingletonInstId>;
  68. // Constraint that requires the type to be an integer type.
  69. struct AnyInt {
  70. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  71. -> bool {
  72. if (BuiltinType<IntLiteralType::SingletonInstId>::Check(sem_ir, state,
  73. type_id)) {
  74. return true;
  75. }
  76. return sem_ir.types().Is<IntType>(type_id);
  77. }
  78. };
  79. // Constraint that requires the type to be a float type.
  80. struct AnyFloat {
  81. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  82. -> bool {
  83. if (BuiltinType<LegacyFloatType::SingletonInstId>::Check(sem_ir, state,
  84. type_id)) {
  85. return true;
  86. }
  87. return sem_ir.types().Is<FloatType>(type_id);
  88. }
  89. };
  90. // Checks that the specified type matches the given type constraint.
  91. template <typename TypeConstraint>
  92. auto Check(const File& sem_ir, ValidateState& state, TypeId type_id) -> bool {
  93. while (type_id.is_valid()) {
  94. // Allow a type that satisfies the constraint.
  95. if (TypeConstraint::Check(sem_ir, state, type_id)) {
  96. return true;
  97. }
  98. // Also allow a class type that adapts a matching type.
  99. auto class_type = sem_ir.types().TryGetAs<ClassType>(type_id);
  100. if (!class_type) {
  101. break;
  102. }
  103. type_id = sem_ir.classes()
  104. .Get(class_type->class_id)
  105. .GetAdaptedType(sem_ir, class_type->specific_id);
  106. }
  107. return false;
  108. }
  109. // Constraint that requires the type to be the type type.
  110. using Type = BuiltinType<TypeType::SingletonInstId>;
  111. } // namespace
  112. // Validates that this builtin has a signature matching the specified signature.
  113. //
  114. // `SignatureFnType` is a C++ function type that describes the signature that is
  115. // expected for this builtin. For example, `auto (AnyInt, AnyInt) -> AnyInt`
  116. // specifies that the builtin takes values of two integer types and returns a
  117. // value of a third integer type. Types used within the signature should provide
  118. // a `Check` function that validates that the Carbon type is expected:
  119. //
  120. // auto Check(const File&, ValidateState&, TypeId) -> bool;
  121. //
  122. // To constrain that the same type is used in multiple places in the signature,
  123. // `TypeParam<I, T>` can be used. For example:
  124. //
  125. // auto (TypeParam<0, AnyInt>, AnyInt) -> TypeParam<0, AnyInt>
  126. //
  127. // describes a builtin that takes two integers, and whose return type matches
  128. // its first parameter type. For convenience, typedefs for `TypeParam<I, T>`
  129. // are used in the descriptions of the builtins.
  130. template <typename SignatureFnType>
  131. static auto ValidateSignature(const File& sem_ir,
  132. llvm::ArrayRef<TypeId> arg_types,
  133. TypeId return_type) -> bool {
  134. using SignatureTraits = llvm::function_traits<SignatureFnType*>;
  135. ValidateState state;
  136. // Must have expected number of arguments.
  137. if (arg_types.size() != SignatureTraits::num_args) {
  138. return false;
  139. }
  140. // Argument types must match.
  141. if (![&]<size_t... Indexes>(std::index_sequence<Indexes...>) {
  142. return ((Check<typename SignatureTraits::template arg_t<Indexes>>(
  143. sem_ir, state, arg_types[Indexes])) &&
  144. ...);
  145. }(std::make_index_sequence<SignatureTraits::num_args>())) {
  146. return false;
  147. }
  148. // Result type must match.
  149. if (!Check<typename SignatureTraits::result_t>(sem_ir, state, return_type)) {
  150. return false;
  151. }
  152. return true;
  153. }
  154. // Descriptions of builtin functions follow. For each builtin, a corresponding
  155. // `BuiltinInfo` constant is declared describing properties of that builtin.
  156. namespace BuiltinFunctionInfo {
  157. // Convenience name used in the builtin type signatures below for a first
  158. // generic type parameter that is constrained to be an integer type.
  159. using IntT = TypeParam<0, AnyInt>;
  160. // Convenience name used in the builtin type signatures below for a second
  161. // generic type parameter that is constrained to be an integer type.
  162. using IntU = TypeParam<1, AnyInt>;
  163. // Convenience name used in the builtin type signatures below for a first
  164. // generic type parameter that is constrained to be an float type.
  165. using FloatT = TypeParam<0, AnyFloat>;
  166. // Not a builtin function.
  167. constexpr BuiltinInfo None = {"", nullptr};
  168. // Prints a single character.
  169. constexpr BuiltinInfo PrintChar = {"print.char",
  170. ValidateSignature<auto(AnyInt)->AnyInt>};
  171. // Prints an integer.
  172. constexpr BuiltinInfo PrintInt = {"print.int",
  173. ValidateSignature<auto(AnyInt)->NoReturn>};
  174. // Reads a single character from stdin.
  175. constexpr BuiltinInfo ReadChar = {"read.char",
  176. ValidateSignature<auto()->AnyInt>};
  177. // Returns the `Core.IntLiteral` type.
  178. constexpr BuiltinInfo IntLiteralMakeType = {"int_literal.make_type",
  179. ValidateSignature<auto()->Type>};
  180. // Returns the `iN` type.
  181. // TODO: Should we use a more specific type as the type of the bit width?
  182. constexpr BuiltinInfo IntMakeTypeSigned = {
  183. "int.make_type_signed", ValidateSignature<auto(AnyInt)->Type>};
  184. // Returns the `uN` type.
  185. constexpr BuiltinInfo IntMakeTypeUnsigned = {
  186. "int.make_type_unsigned", ValidateSignature<auto(AnyInt)->Type>};
  187. // Returns float types, such as `f64`. Currently only supports `f64`.
  188. constexpr BuiltinInfo FloatMakeType = {"float.make_type",
  189. ValidateSignature<auto(AnyInt)->Type>};
  190. // Returns the `bool` type.
  191. constexpr BuiltinInfo BoolMakeType = {"bool.make_type",
  192. ValidateSignature<auto()->Type>};
  193. // Converts between integer types, with a diagnostic if the value doesn't fit.
  194. constexpr BuiltinInfo IntConvertChecked = {
  195. "int.convert_checked", ValidateSignature<auto(AnyInt)->AnyInt>};
  196. // "int.snegate": integer negation.
  197. constexpr BuiltinInfo IntSNegate = {"int.snegate",
  198. ValidateSignature<auto(IntT)->IntT>};
  199. // "int.sadd": integer addition.
  200. constexpr BuiltinInfo IntSAdd = {"int.sadd",
  201. ValidateSignature<auto(IntT, IntT)->IntT>};
  202. // "int.ssub": integer subtraction.
  203. constexpr BuiltinInfo IntSSub = {"int.ssub",
  204. ValidateSignature<auto(IntT, IntT)->IntT>};
  205. // "int.smul": integer multiplication.
  206. constexpr BuiltinInfo IntSMul = {"int.smul",
  207. ValidateSignature<auto(IntT, IntT)->IntT>};
  208. // "int.sdiv": integer division.
  209. constexpr BuiltinInfo IntSDiv = {"int.sdiv",
  210. ValidateSignature<auto(IntT, IntT)->IntT>};
  211. // "int.smod": integer modulo.
  212. constexpr BuiltinInfo IntSMod = {"int.smod",
  213. ValidateSignature<auto(IntT, IntT)->IntT>};
  214. // "int.unegate": unsigned integer negation.
  215. constexpr BuiltinInfo IntUNegate = {"int.unegate",
  216. ValidateSignature<auto(IntT)->IntT>};
  217. // "int.uadd": unsigned integer addition.
  218. constexpr BuiltinInfo IntUAdd = {"int.uadd",
  219. ValidateSignature<auto(IntT, IntT)->IntT>};
  220. // "int.usub": unsigned integer subtraction.
  221. constexpr BuiltinInfo IntUSub = {"int.usub",
  222. ValidateSignature<auto(IntT, IntT)->IntT>};
  223. // "int.umul": unsigned integer multiplication.
  224. constexpr BuiltinInfo IntUMul = {"int.umul",
  225. ValidateSignature<auto(IntT, IntT)->IntT>};
  226. // "int.udiv": unsigned integer division.
  227. constexpr BuiltinInfo IntUDiv = {"int.udiv",
  228. ValidateSignature<auto(IntT, IntT)->IntT>};
  229. // "int.mod": integer modulo.
  230. constexpr BuiltinInfo IntUMod = {"int.umod",
  231. ValidateSignature<auto(IntT, IntT)->IntT>};
  232. // "int.complement": integer bitwise complement.
  233. constexpr BuiltinInfo IntComplement = {"int.complement",
  234. ValidateSignature<auto(IntT)->IntT>};
  235. // "int.and": integer bitwise and.
  236. constexpr BuiltinInfo IntAnd = {"int.and",
  237. ValidateSignature<auto(IntT, IntT)->IntT>};
  238. // "int.or": integer bitwise or.
  239. constexpr BuiltinInfo IntOr = {"int.or",
  240. ValidateSignature<auto(IntT, IntT)->IntT>};
  241. // "int.xor": integer bitwise xor.
  242. constexpr BuiltinInfo IntXor = {"int.xor",
  243. ValidateSignature<auto(IntT, IntT)->IntT>};
  244. // "int.left_shift": integer left shift.
  245. constexpr BuiltinInfo IntLeftShift = {
  246. "int.left_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  247. // "int.left_shift": integer right shift.
  248. constexpr BuiltinInfo IntRightShift = {
  249. "int.right_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  250. // "int.eq": integer equality comparison.
  251. constexpr BuiltinInfo IntEq = {"int.eq",
  252. ValidateSignature<auto(IntT, IntT)->Bool>};
  253. // "int.neq": integer non-equality comparison.
  254. constexpr BuiltinInfo IntNeq = {"int.neq",
  255. ValidateSignature<auto(IntT, IntT)->Bool>};
  256. // "int.less": integer less than comparison.
  257. constexpr BuiltinInfo IntLess = {"int.less",
  258. ValidateSignature<auto(IntT, IntT)->Bool>};
  259. // "int.less_eq": integer less than or equal comparison.
  260. constexpr BuiltinInfo IntLessEq = {"int.less_eq",
  261. ValidateSignature<auto(IntT, IntT)->Bool>};
  262. // "int.greater": integer greater than comparison.
  263. constexpr BuiltinInfo IntGreater = {"int.greater",
  264. ValidateSignature<auto(IntT, IntT)->Bool>};
  265. // "int.greater_eq": integer greater than or equal comparison.
  266. constexpr BuiltinInfo IntGreaterEq = {
  267. "int.greater_eq", ValidateSignature<auto(IntT, IntT)->Bool>};
  268. // "float.negate": float negation.
  269. constexpr BuiltinInfo FloatNegate = {"float.negate",
  270. ValidateSignature<auto(FloatT)->FloatT>};
  271. // "float.add": float addition.
  272. constexpr BuiltinInfo FloatAdd = {
  273. "float.add", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  274. // "float.sub": float subtraction.
  275. constexpr BuiltinInfo FloatSub = {
  276. "float.sub", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  277. // "float.mul": float multiplication.
  278. constexpr BuiltinInfo FloatMul = {
  279. "float.mul", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  280. // "float.div": float division.
  281. constexpr BuiltinInfo FloatDiv = {
  282. "float.div", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  283. // "float.eq": float equality comparison.
  284. constexpr BuiltinInfo FloatEq = {"float.eq",
  285. ValidateSignature<auto(FloatT, FloatT)->Bool>};
  286. // "float.neq": float non-equality comparison.
  287. constexpr BuiltinInfo FloatNeq = {
  288. "float.neq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  289. // "float.less": float less than comparison.
  290. constexpr BuiltinInfo FloatLess = {
  291. "float.less", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  292. // "float.less_eq": float less than or equal comparison.
  293. constexpr BuiltinInfo FloatLessEq = {
  294. "float.less_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  295. // "float.greater": float greater than comparison.
  296. constexpr BuiltinInfo FloatGreater = {
  297. "float.greater", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  298. // "float.greater_eq": float greater than or equal comparison.
  299. constexpr BuiltinInfo FloatGreaterEq = {
  300. "float.greater_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  301. // "bool.eq": bool equality comparison.
  302. constexpr BuiltinInfo BoolEq = {"bool.eq",
  303. ValidateSignature<auto(Bool, Bool)->Bool>};
  304. // "bool.neq": bool non-equality comparison.
  305. constexpr BuiltinInfo BoolNeq = {"bool.neq",
  306. ValidateSignature<auto(Bool, Bool)->Bool>};
  307. } // namespace BuiltinFunctionInfo
  308. CARBON_DEFINE_ENUM_CLASS_NAMES(BuiltinFunctionKind) = {
  309. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  310. BuiltinFunctionInfo::Name.name,
  311. #include "toolchain/sem_ir/builtin_function_kind.def"
  312. };
  313. // Returns the builtin function kind with the given name, or None if the name
  314. // is unknown.
  315. auto BuiltinFunctionKind::ForBuiltinName(llvm::StringRef name)
  316. -> BuiltinFunctionKind {
  317. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  318. if (name == BuiltinFunctionInfo::Name.name) { \
  319. return BuiltinFunctionKind::Name; \
  320. }
  321. #include "toolchain/sem_ir/builtin_function_kind.def"
  322. return BuiltinFunctionKind::None;
  323. }
  324. auto BuiltinFunctionKind::IsValidType(const File& sem_ir,
  325. llvm::ArrayRef<TypeId> arg_types,
  326. TypeId return_type) const -> bool {
  327. static constexpr ValidateFn* ValidateFns[] = {
  328. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  329. BuiltinFunctionInfo::Name.validate,
  330. #include "toolchain/sem_ir/builtin_function_kind.def"
  331. };
  332. return ValidateFns[AsInt()](sem_ir, arg_types, return_type);
  333. }
  334. auto BuiltinFunctionKind::IsCompTimeOnly() const -> bool {
  335. return *this == BuiltinFunctionKind::IntConvertChecked;
  336. }
  337. } // namespace Carbon::SemIR