check_internal.h 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. #ifndef CARBON_COMMON_CHECK_INTERNAL_H_
  5. #define CARBON_COMMON_CHECK_INTERNAL_H_
  6. #include "common/template_string.h"
  7. #include "llvm/Support/FormatVariadic.h"
  8. namespace Carbon::Internal {
  9. // Evaluates a condition in a CHECK. This diagnoses if the condition evaluates
  10. // to the constant `true` or `false`.
  11. [[clang::always_inline]] constexpr bool
  12. // Trailing GNU function attributes are incompatible with trailing return types.
  13. // Filed as https://github.com/llvm/llvm-project/issues/118697
  14. // NOLINTNEXTLINE(modernize-use-trailing-return-type)
  15. CheckCondition(bool condition)
  16. __attribute__((diagnose_if(condition,
  17. "CHECK condition is always true; replace with "
  18. "static_assert if this is intended",
  19. "error")))
  20. __attribute__((diagnose_if(!condition,
  21. "CHECK condition is always false; replace with "
  22. "CARBON_FATAL if this is intended",
  23. "error"))) {
  24. return condition;
  25. }
  26. // Implements the check failure message printing.
  27. //
  28. // This is out-of-line and will arrange to stop the program, print any debugging
  29. // information and this string. In `!NDEBUG` mode (`dbg` and `fastbuild`), check
  30. // failures can be made non-fatal by a build flag, so this is not `[[noreturn]]`
  31. // in that case.
  32. //
  33. // This API uses `const char*` C string arguments rather than `llvm::StringRef`
  34. // because we know that these are available as C strings and passing them that
  35. // way lets the code size of calling it be smaller: it only needs to materialize
  36. // a single pointer argument for each. The runtime cost of re-computing the size
  37. // should be minimal. The extra message however might not be compile-time
  38. // guaranteed to be a C string so we use a normal `StringRef` there.
  39. #ifdef NDEBUG
  40. [[noreturn]]
  41. #endif
  42. auto CheckFailImpl(const char* kind, const char* file, int line,
  43. const char* condition_str, llvm::StringRef extra_message)
  44. -> void;
  45. // Allow converting format values; the default behaviour is to just pass them
  46. // through.
  47. template <typename T>
  48. auto ConvertFormatValue(T&& t) -> T&& {
  49. return std::forward<T>(t);
  50. }
  51. // Convert enums to larger integers so that byte-sized enums are not confused
  52. // with being chars and printed as invalid (or nul-terminating) characters.
  53. // Scoped enums are explicitly converted to integers so they can be printed
  54. // without the user writing a cast.
  55. template <typename T>
  56. requires(std::is_enum_v<std::remove_reference_t<T>>)
  57. auto ConvertFormatValue(T&& t) {
  58. if constexpr (std::is_signed_v<
  59. std::underlying_type_t<std::remove_reference_t<T>>>) {
  60. return static_cast<int64_t>(t);
  61. } else {
  62. return static_cast<uint64_t>(t);
  63. }
  64. }
  65. // Prints a check failure, including rendering any user-provided message using
  66. // a format string.
  67. //
  68. // Most of the parameters are passed as compile-time template strings to avoid
  69. // runtime cost of parameter setup in optimized builds. Each of these are passed
  70. // along to the underlying implementation to include in the final printed
  71. // message.
  72. //
  73. // Any user-provided format string and values are directly passed to
  74. // `llvm::formatv` which handles all of the formatting of output.
  75. template <TemplateString Kind, TemplateString File, int Line,
  76. TemplateString ConditionStr, TemplateString FormatStr, typename... Ts>
  77. #ifdef NDEBUG
  78. [[noreturn]]
  79. #endif
  80. [[gnu::cold, clang::noinline]] auto
  81. CheckFail(Ts&&... values) -> void {
  82. if constexpr (llvm::StringRef(FormatStr).empty()) {
  83. // Skip the format string rendering if empty. Note that we don't skip it
  84. // even if there are no values as we want to have consistent handling of
  85. // `{}`s in the format string. This case is about when there is no message
  86. // at all, just the condition.
  87. CheckFailImpl(Kind.c_str(), File.c_str(), Line, ConditionStr.c_str(), "");
  88. } else {
  89. CheckFailImpl(Kind.c_str(), File.c_str(), Line, ConditionStr.c_str(),
  90. llvm::formatv(FormatStr.c_str(),
  91. ConvertFormatValue(std::forward<Ts>(values))...)
  92. .str());
  93. }
  94. }
  95. } // namespace Carbon::Internal
  96. // Evaluates the condition of a CHECK as a boolean value.
  97. //
  98. // This performs a contextual conversion to bool, diagnoses if the condition is
  99. // always true or always false, and returns its value.
  100. #define CARBON_INTERNAL_CHECK_CONDITION(cond) \
  101. (Carbon::Internal::CheckCondition(true && (cond)))
  102. // Implements check messages without any formatted values.
  103. //
  104. // Passes each of the provided components of the message to the template
  105. // parameters of the check failure printing function above, including an empty
  106. // string for the format string. Because there are multiple template arguments,
  107. // the entire call is wrapped in parentheses.
  108. #define CARBON_INTERNAL_CHECK_IMPL(kind, file, line, condition_str) \
  109. (Carbon::Internal::CheckFail<kind, file, line, condition_str, "">())
  110. // Implements check messages with a format string and potentially formatted
  111. // values.
  112. //
  113. // Each of the main components is passed as a template arguments, and then any
  114. // formatted values are passed as arguments. Because there are multiple template
  115. // arguments, the entire call is wrapped in parentheses.
  116. #define CARBON_INTERNAL_CHECK_IMPL_FORMAT(kind, file, line, condition_str, \
  117. format_str, ...) \
  118. (Carbon::Internal::CheckFail<kind, file, line, condition_str, format_str>( \
  119. __VA_ARGS__))
  120. // Implements the failure of a check.
  121. //
  122. // Collects all the metadata about the failure to be printed, such as source
  123. // location and stringified condition, and passes those, any format string and
  124. // formatted arguments to the correct implementation macro above.
  125. #define CARBON_INTERNAL_CHECK(condition, ...) \
  126. CARBON_INTERNAL_CHECK_IMPL##__VA_OPT__(_FORMAT)( \
  127. "CHECK", __FILE__, __LINE__, #condition __VA_OPT__(, ) __VA_ARGS__)
  128. // Implements the fatal macro.
  129. //
  130. // Similar to the check failure macro, but tags the message as a fatal one and
  131. // leaves the stringified condition empty.
  132. #define CARBON_INTERNAL_FATAL(...) \
  133. (CARBON_INTERNAL_CHECK_IMPL##__VA_OPT__(_FORMAT)( \
  134. "FATAL", __FILE__, __LINE__, "" __VA_OPT__(, ) __VA_ARGS__), \
  135. CARBON_INTERNAL_FATAL_NORETURN_SUFFIX())
  136. #ifdef NDEBUG
  137. // For `DCHECK` in optimized builds we have a dead check that we want to
  138. // potentially "use" arguments, but otherwise have the minimal overhead. We
  139. // avoid forming interesting format strings here so that we don't have to
  140. // repeatedly instantiate the `Check` function above. This format string would
  141. // be an error if actually used.
  142. #define CARBON_INTERNAL_DEAD_DCHECK(condition, ...) \
  143. CARBON_INTERNAL_DEAD_DCHECK_IMPL##__VA_OPT__(_FORMAT)(__VA_ARGS__)
  144. #define CARBON_INTERNAL_DEAD_DCHECK_IMPL() \
  145. Carbon::Internal::CheckFail<"", "", 0, "", "">()
  146. #define CARBON_INTERNAL_DEAD_DCHECK_IMPL_FORMAT(format_str, ...) \
  147. Carbon::Internal::CheckFail<"", "", 0, "", "">(__VA_ARGS__)
  148. // The CheckFail function itself is noreturn in NDEBUG.
  149. #define CARBON_INTERNAL_FATAL_NORETURN_SUFFIX() void()
  150. #else
  151. #define CARBON_INTERNAL_FATAL_NORETURN_SUFFIX() std::abort()
  152. #endif
  153. #endif // CARBON_COMMON_CHECK_INTERNAL_H_