builtin_function_kind.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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::None, TypeId::None};
  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].has_value() && 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 TypeInstId& 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.inst_blocks().Get(tuple->type_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 a sized integer type.
  69. struct AnySizedInt {
  70. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  71. TypeId type_id) -> bool {
  72. return sem_ir.types().Is<IntType>(type_id);
  73. }
  74. };
  75. // Constraint that requires the type to be an integer type.
  76. struct AnyInt {
  77. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  78. -> bool {
  79. return AnySizedInt::Check(sem_ir, state, type_id) ||
  80. BuiltinType<IntLiteralType::SingletonInstId>::Check(sem_ir, state,
  81. type_id);
  82. }
  83. };
  84. // Constraint that requires the type to be a float type.
  85. struct AnyFloat {
  86. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  87. -> bool {
  88. if (BuiltinType<LegacyFloatType::SingletonInstId>::Check(sem_ir, state,
  89. type_id)) {
  90. return true;
  91. }
  92. return sem_ir.types().Is<FloatType>(type_id);
  93. }
  94. };
  95. // Constraint that requires the type to be the type type.
  96. using Type = BuiltinType<TypeType::SingletonInstId>;
  97. // Constraint that requires the type to be a type value, whose type is type
  98. // type. Also accepts symbolic constant value types.
  99. struct AnyType {
  100. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  101. -> bool {
  102. if (BuiltinType<TypeType::SingletonInstId>::Check(sem_ir, state, type_id)) {
  103. return true;
  104. }
  105. return sem_ir.types().GetAsInst(type_id).type_id() ==
  106. TypeType::SingletonTypeId;
  107. }
  108. };
  109. // Checks that the specified type matches the given type constraint.
  110. template <typename TypeConstraint>
  111. auto Check(const File& sem_ir, ValidateState& state, TypeId type_id) -> bool {
  112. while (type_id.has_value()) {
  113. // Allow a type that satisfies the constraint.
  114. if (TypeConstraint::Check(sem_ir, state, type_id)) {
  115. return true;
  116. }
  117. // Also allow a class type that adapts a matching type.
  118. auto class_type = sem_ir.types().TryGetAs<ClassType>(type_id);
  119. if (!class_type) {
  120. break;
  121. }
  122. type_id = sem_ir.classes()
  123. .Get(class_type->class_id)
  124. .GetAdaptedType(sem_ir, class_type->specific_id);
  125. }
  126. return false;
  127. }
  128. } // namespace
  129. // Validates that this builtin has a signature matching the specified signature.
  130. //
  131. // `SignatureFnType` is a C++ function type that describes the signature that is
  132. // expected for this builtin. For example, `auto (AnyInt, AnyInt) -> AnyInt`
  133. // specifies that the builtin takes values of two integer types and returns a
  134. // value of a third integer type. Types used within the signature should provide
  135. // a `Check` function that validates that the Carbon type is expected:
  136. //
  137. // auto Check(const File&, ValidateState&, TypeId) -> bool;
  138. //
  139. // To constrain that the same type is used in multiple places in the signature,
  140. // `TypeParam<I, T>` can be used. For example:
  141. //
  142. // auto (TypeParam<0, AnyInt>, AnyInt) -> TypeParam<0, AnyInt>
  143. //
  144. // describes a builtin that takes two integers, and whose return type matches
  145. // its first parameter type. For convenience, typedefs for `TypeParam<I, T>`
  146. // are used in the descriptions of the builtins.
  147. template <typename SignatureFnType>
  148. static auto ValidateSignature(const File& sem_ir,
  149. llvm::ArrayRef<TypeId> arg_types,
  150. TypeId return_type) -> bool {
  151. using SignatureTraits = llvm::function_traits<SignatureFnType*>;
  152. ValidateState state;
  153. // Must have expected number of arguments.
  154. if (arg_types.size() != SignatureTraits::num_args) {
  155. return false;
  156. }
  157. // Argument types must match.
  158. if (![&]<size_t... Indexes>(std::index_sequence<Indexes...>) {
  159. return ((Check<typename SignatureTraits::template arg_t<Indexes>>(
  160. sem_ir, state, arg_types[Indexes])) &&
  161. ...);
  162. }(std::make_index_sequence<SignatureTraits::num_args>())) {
  163. return false;
  164. }
  165. // Result type must match.
  166. if (!Check<typename SignatureTraits::result_t>(sem_ir, state, return_type)) {
  167. return false;
  168. }
  169. return true;
  170. }
  171. // Descriptions of builtin functions follow. For each builtin, a corresponding
  172. // `BuiltinInfo` constant is declared describing properties of that builtin.
  173. namespace BuiltinFunctionInfo {
  174. // Convenience name used in the builtin type signatures below for a first
  175. // generic type parameter that is constrained to be an integer type.
  176. using IntT = TypeParam<0, AnyInt>;
  177. // Convenience name used in the builtin type signatures below for a second
  178. // generic type parameter that is constrained to be an integer type.
  179. using IntU = TypeParam<1, AnyInt>;
  180. // Convenience name used in the builtin type signatures below for a first
  181. // generic type parameter that is constrained to be a sized integer type.
  182. using SizedIntT = TypeParam<0, AnySizedInt>;
  183. // Convenience name used in the builtin type signatures below for a first
  184. // generic type parameter that is constrained to be an float type.
  185. using FloatT = TypeParam<0, AnyFloat>;
  186. // Not a builtin function.
  187. constexpr BuiltinInfo None = {"", nullptr};
  188. constexpr BuiltinInfo NoOp = {"no_op", ValidateSignature<auto()->NoReturn>};
  189. // Prints a single character.
  190. constexpr BuiltinInfo PrintChar = {
  191. "print.char", ValidateSignature<auto(AnySizedInt)->AnySizedInt>};
  192. // Prints an integer.
  193. constexpr BuiltinInfo PrintInt = {
  194. "print.int", ValidateSignature<auto(AnySizedInt)->NoReturn>};
  195. // Reads a single character from stdin.
  196. constexpr BuiltinInfo ReadChar = {"read.char",
  197. ValidateSignature<auto()->AnySizedInt>};
  198. // Returns the `Core.IntLiteral` type.
  199. constexpr BuiltinInfo IntLiteralMakeType = {"int_literal.make_type",
  200. ValidateSignature<auto()->Type>};
  201. // Returns the `iN` type.
  202. // TODO: Should we use a more specific type as the type of the bit width?
  203. constexpr BuiltinInfo IntMakeTypeSigned = {
  204. "int.make_type_signed", ValidateSignature<auto(AnyInt)->Type>};
  205. // Returns the `uN` type.
  206. constexpr BuiltinInfo IntMakeTypeUnsigned = {
  207. "int.make_type_unsigned", ValidateSignature<auto(AnyInt)->Type>};
  208. // Returns float types, such as `f64`. Currently only supports `f64`.
  209. constexpr BuiltinInfo FloatMakeType = {"float.make_type",
  210. ValidateSignature<auto(AnyInt)->Type>};
  211. // Returns the `bool` type.
  212. constexpr BuiltinInfo BoolMakeType = {"bool.make_type",
  213. ValidateSignature<auto()->Type>};
  214. // Converts between integer types, truncating if necessary.
  215. constexpr BuiltinInfo IntConvert = {"int.convert",
  216. ValidateSignature<auto(AnyInt)->AnyInt>};
  217. // Converts between integer types, with a diagnostic if the value doesn't fit.
  218. constexpr BuiltinInfo IntConvertChecked = {
  219. "int.convert_checked", ValidateSignature<auto(AnyInt)->AnyInt>};
  220. // "int.snegate": integer negation.
  221. constexpr BuiltinInfo IntSNegate = {"int.snegate",
  222. ValidateSignature<auto(IntT)->IntT>};
  223. // "int.sadd": integer addition.
  224. constexpr BuiltinInfo IntSAdd = {"int.sadd",
  225. ValidateSignature<auto(IntT, IntT)->IntT>};
  226. // "int.ssub": integer subtraction.
  227. constexpr BuiltinInfo IntSSub = {"int.ssub",
  228. ValidateSignature<auto(IntT, IntT)->IntT>};
  229. // "int.smul": integer multiplication.
  230. constexpr BuiltinInfo IntSMul = {"int.smul",
  231. ValidateSignature<auto(IntT, IntT)->IntT>};
  232. // "int.sdiv": integer division.
  233. constexpr BuiltinInfo IntSDiv = {"int.sdiv",
  234. ValidateSignature<auto(IntT, IntT)->IntT>};
  235. // "int.smod": integer modulo.
  236. constexpr BuiltinInfo IntSMod = {"int.smod",
  237. ValidateSignature<auto(IntT, IntT)->IntT>};
  238. // "int.unegate": unsigned integer negation.
  239. constexpr BuiltinInfo IntUNegate = {
  240. "int.unegate", ValidateSignature<auto(SizedIntT)->SizedIntT>};
  241. // "int.uadd": unsigned integer addition.
  242. constexpr BuiltinInfo IntUAdd = {
  243. "int.uadd", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  244. // "int.usub": unsigned integer subtraction.
  245. constexpr BuiltinInfo IntUSub = {
  246. "int.usub", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  247. // "int.umul": unsigned integer multiplication.
  248. constexpr BuiltinInfo IntUMul = {
  249. "int.umul", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  250. // "int.udiv": unsigned integer division.
  251. constexpr BuiltinInfo IntUDiv = {
  252. "int.udiv", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  253. // "int.mod": integer modulo.
  254. constexpr BuiltinInfo IntUMod = {
  255. "int.umod", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  256. // "int.complement": integer bitwise complement.
  257. constexpr BuiltinInfo IntComplement = {"int.complement",
  258. ValidateSignature<auto(IntT)->IntT>};
  259. // "int.and": integer bitwise and.
  260. constexpr BuiltinInfo IntAnd = {"int.and",
  261. ValidateSignature<auto(IntT, IntT)->IntT>};
  262. // "int.or": integer bitwise or.
  263. constexpr BuiltinInfo IntOr = {"int.or",
  264. ValidateSignature<auto(IntT, IntT)->IntT>};
  265. // "int.xor": integer bitwise xor.
  266. constexpr BuiltinInfo IntXor = {"int.xor",
  267. ValidateSignature<auto(IntT, IntT)->IntT>};
  268. // "int.left_shift": integer left shift.
  269. constexpr BuiltinInfo IntLeftShift = {
  270. "int.left_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  271. // "int.left_shift": integer right shift.
  272. constexpr BuiltinInfo IntRightShift = {
  273. "int.right_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  274. // "int.eq": integer equality comparison.
  275. constexpr BuiltinInfo IntEq = {"int.eq",
  276. ValidateSignature<auto(IntT, IntU)->Bool>};
  277. // "int.neq": integer non-equality comparison.
  278. constexpr BuiltinInfo IntNeq = {"int.neq",
  279. ValidateSignature<auto(IntT, IntU)->Bool>};
  280. // "int.less": integer less than comparison.
  281. constexpr BuiltinInfo IntLess = {"int.less",
  282. ValidateSignature<auto(IntT, IntU)->Bool>};
  283. // "int.less_eq": integer less than or equal comparison.
  284. constexpr BuiltinInfo IntLessEq = {"int.less_eq",
  285. ValidateSignature<auto(IntT, IntU)->Bool>};
  286. // "int.greater": integer greater than comparison.
  287. constexpr BuiltinInfo IntGreater = {"int.greater",
  288. ValidateSignature<auto(IntT, IntU)->Bool>};
  289. // "int.greater_eq": integer greater than or equal comparison.
  290. constexpr BuiltinInfo IntGreaterEq = {
  291. "int.greater_eq", ValidateSignature<auto(IntT, IntU)->Bool>};
  292. // "float.negate": float negation.
  293. constexpr BuiltinInfo FloatNegate = {"float.negate",
  294. ValidateSignature<auto(FloatT)->FloatT>};
  295. // "float.add": float addition.
  296. constexpr BuiltinInfo FloatAdd = {
  297. "float.add", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  298. // "float.sub": float subtraction.
  299. constexpr BuiltinInfo FloatSub = {
  300. "float.sub", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  301. // "float.mul": float multiplication.
  302. constexpr BuiltinInfo FloatMul = {
  303. "float.mul", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  304. // "float.div": float division.
  305. constexpr BuiltinInfo FloatDiv = {
  306. "float.div", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  307. // "float.eq": float equality comparison.
  308. constexpr BuiltinInfo FloatEq = {"float.eq",
  309. ValidateSignature<auto(FloatT, FloatT)->Bool>};
  310. // "float.neq": float non-equality comparison.
  311. constexpr BuiltinInfo FloatNeq = {
  312. "float.neq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  313. // "float.less": float less than comparison.
  314. constexpr BuiltinInfo FloatLess = {
  315. "float.less", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  316. // "float.less_eq": float less than or equal comparison.
  317. constexpr BuiltinInfo FloatLessEq = {
  318. "float.less_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  319. // "float.greater": float greater than comparison.
  320. constexpr BuiltinInfo FloatGreater = {
  321. "float.greater", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  322. // "float.greater_eq": float greater than or equal comparison.
  323. constexpr BuiltinInfo FloatGreaterEq = {
  324. "float.greater_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  325. // "bool.eq": bool equality comparison.
  326. constexpr BuiltinInfo BoolEq = {"bool.eq",
  327. ValidateSignature<auto(Bool, Bool)->Bool>};
  328. // "bool.neq": bool non-equality comparison.
  329. constexpr BuiltinInfo BoolNeq = {"bool.neq",
  330. ValidateSignature<auto(Bool, Bool)->Bool>};
  331. // "type.and": facet type combination.
  332. constexpr BuiltinInfo TypeAnd = {
  333. "type.and", ValidateSignature<auto(AnyType, AnyType)->AnyType>};
  334. } // namespace BuiltinFunctionInfo
  335. CARBON_DEFINE_ENUM_CLASS_NAMES(BuiltinFunctionKind) = {
  336. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  337. BuiltinFunctionInfo::Name.name,
  338. #include "toolchain/sem_ir/builtin_function_kind.def"
  339. };
  340. // Returns the builtin function kind with the given name, or None if the name
  341. // is unknown.
  342. auto BuiltinFunctionKind::ForBuiltinName(llvm::StringRef name)
  343. -> BuiltinFunctionKind {
  344. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  345. if (name == BuiltinFunctionInfo::Name.name) { \
  346. return BuiltinFunctionKind::Name; \
  347. }
  348. #include "toolchain/sem_ir/builtin_function_kind.def"
  349. return BuiltinFunctionKind::None;
  350. }
  351. auto BuiltinFunctionKind::IsValidType(const File& sem_ir,
  352. llvm::ArrayRef<TypeId> arg_types,
  353. TypeId return_type) const -> bool {
  354. static constexpr ValidateFn* ValidateFns[] = {
  355. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  356. BuiltinFunctionInfo::Name.validate,
  357. #include "toolchain/sem_ir/builtin_function_kind.def"
  358. };
  359. return ValidateFns[AsInt()](sem_ir, arg_types, return_type);
  360. }
  361. // Determines whether a builtin call involves an integer literal in its
  362. // arguments or return type. If so, for many builtins we want to treat the call
  363. // as being compile-time-only. This is because `Core.IntLiteral` has an empty
  364. // runtime representation, and a value of that type isn't necessarily a
  365. // compile-time constant, so an arbitrary runtime value of type
  366. // `Core.IntLiteral` may not have a value available for the builtin to use. For
  367. // example, given:
  368. //
  369. // var n: Core.IntLiteral() = 123;
  370. //
  371. // we would be unable to lower a runtime operation such as `(1 as i32) << n`
  372. // because the runtime representation of `n` doesn't track its value at all.
  373. //
  374. // For now, we treat all operations involving `Core.IntLiteral` as being
  375. // compile-time-only.
  376. //
  377. // TODO: We will need to accept things like `some_i32 << 5` eventually. We could
  378. // allow builtin calls at runtime if all the IntLiteral arguments have constant
  379. // values, or add logic to the prelude to promote the `IntLiteral` operand to a
  380. // different type in such cases.
  381. //
  382. // TODO: For now, we also treat builtins *returning* `Core.IntLiteral` as being
  383. // compile-time-only. This is mostly done for simplicity, but should probably be
  384. // revisited.
  385. static auto AnyIntLiteralTypes(const File& sem_ir,
  386. llvm::ArrayRef<InstId> arg_ids,
  387. TypeId return_type_id) -> bool {
  388. if (sem_ir.types().Is<SemIR::IntLiteralType>(return_type_id)) {
  389. return true;
  390. }
  391. for (auto arg_id : arg_ids) {
  392. if (sem_ir.types().Is<SemIR::IntLiteralType>(
  393. sem_ir.insts().Get(arg_id).type_id())) {
  394. return true;
  395. }
  396. }
  397. return false;
  398. }
  399. auto BuiltinFunctionKind::IsCompTimeOnly(const File& sem_ir,
  400. llvm::ArrayRef<InstId> arg_ids,
  401. TypeId return_type_id) const -> bool {
  402. switch (*this) {
  403. case IntConvertChecked:
  404. // Checked integer conversions are compile-time only.
  405. return true;
  406. case IntConvert:
  407. case IntSNegate:
  408. case IntComplement:
  409. case IntSAdd:
  410. case IntSSub:
  411. case IntSMul:
  412. case IntSDiv:
  413. case IntSMod:
  414. case IntAnd:
  415. case IntOr:
  416. case IntXor:
  417. case IntLeftShift:
  418. case IntRightShift:
  419. case IntEq:
  420. case IntNeq:
  421. case IntLess:
  422. case IntLessEq:
  423. case IntGreater:
  424. case IntGreaterEq:
  425. // Integer operations are compile-time-only if they involve integer
  426. // literal types. See AnyIntLiteralTypes comment for explanation.
  427. return AnyIntLiteralTypes(sem_ir, arg_ids, return_type_id);
  428. case TypeAnd:
  429. return true;
  430. default:
  431. // TODO: Should the sized MakeType functions be compile-time only? We
  432. // can't produce diagnostics for bad sizes at runtime.
  433. return false;
  434. }
  435. }
  436. } // namespace Carbon::SemIR