assert.h 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <cstdlib>
  6. #include "common/common_funcs.h"
  7. #include "common/logging/log.h"
  8. // For asserts we'd like to keep all the junk executed when an assert happens away from the
  9. // important code in the function. One way of doing this is to put all the relevant code inside a
  10. // lambda and force the compiler to not inline it. Unfortunately, MSVC seems to have no syntax to
  11. // specify __declspec on lambda functions, so what we do instead is define a noinline wrapper
  12. // template that calls the lambda. This seems to generate an extra instruction at the call-site
  13. // compared to the ideal implementation (which wouldn't support ASSERT_MSG parameters), but is good
  14. // enough for our purposes.
  15. template <typename Fn>
  16. #if defined(_MSC_VER)
  17. __declspec(noinline, noreturn)
  18. #elif defined(__GNUC__)
  19. __attribute__((noinline, noreturn, cold))
  20. #endif
  21. static void assert_noinline_call(const Fn& fn) {
  22. fn();
  23. Crash();
  24. exit(1); // Keeps GCC's mouth shut about this actually returning
  25. }
  26. #define ASSERT(_a_) \
  27. do \
  28. if (!(_a_)) { \
  29. assert_noinline_call([] { LOG_CRITICAL(Debug, "Assertion Failed!"); }); \
  30. } \
  31. while (0)
  32. #define ASSERT_MSG(_a_, ...) \
  33. do \
  34. if (!(_a_)) { \
  35. assert_noinline_call([&] { LOG_CRITICAL(Debug, "Assertion Failed!\n" __VA_ARGS__); }); \
  36. } \
  37. while (0)
  38. #define UNREACHABLE() assert_noinline_call([] { LOG_CRITICAL(Debug, "Unreachable code!"); })
  39. #define UNREACHABLE_MSG(...) \
  40. assert_noinline_call([&] { LOG_CRITICAL(Debug, "Unreachable code!\n" __VA_ARGS__); })
  41. #ifdef _DEBUG
  42. #define DEBUG_ASSERT(_a_) ASSERT(_a_)
  43. #define DEBUG_ASSERT_MSG(_a_, ...) ASSERT_MSG(_a_, __VA_ARGS__)
  44. #else // not debug
  45. #define DEBUG_ASSERT(_a_)
  46. #define DEBUG_ASSERT_MSG(_a_, _desc_, ...)
  47. #endif
  48. #define UNIMPLEMENTED() ASSERT_MSG(false, "Unimplemented code!")
  49. #define UNIMPLEMENTED_MSG(...) ASSERT_MSG(false, __VA_ARGS__)
  50. #define UNIMPLEMENTED_IF(cond) ASSERT_MSG(!(cond), "Unimplemented code!")
  51. #define UNIMPLEMENTED_IF_MSG(cond, ...) ASSERT_MSG(!(cond), __VA_ARGS__)
  52. // If the assert is ignored, execute _b_
  53. #define ASSERT_OR_EXECUTE(_a_, _b_) \
  54. do { \
  55. ASSERT(_a_); \
  56. if (!(_a_)) { \
  57. _b_ \
  58. } \
  59. } while (0)
  60. // If the assert is ignored, execute _b_
  61. #define ASSERT_OR_EXECUTE_MSG(_a_, _b_, ...) \
  62. do { \
  63. ASSERT_MSG(_a_, __VA_ARGS__); \
  64. if (!(_a_)) { \
  65. _b_ \
  66. } \
  67. } while (0)