[llvm-dev] Adding [[nodiscard]] to Compiler.h

Sanjoy Das via llvm-dev llvm-dev at lists.llvm.org
Sun Sep 4 14:55:20 PDT 2016


Hi Justin,

Justin Bogner wrote:
 > Sanjoy Das<sanjoy at playingwithpointers.com>  writes:
 >> Hi Justin,
 >>
 >> This SGTM generally, but please make the difference between
 >> LLVM_NODISCARD and LLVM_UNUSED_RESULT clear in the code. :)
 >
 > Right, this is where it gets a little weird. LLVM_NODISCARD would be for
 > types, whereas LLVM_UNUSED_RESULT would be for functions. Depending on
 > your host compiler, using the wrong one might DTRT, but it won't across
 > all compilers.
 >
 > Do you think documenting this is sufficient, or should we try to name
 > these to better represent where they should be used?

Firstly, perhaps "LLVM_NODISCARD_TYPE" would be a better name?

Secondly, if we define the following when the host compiler is clang,

#define LLVM_UNUSED_RESULT __attribute__((warn_unused_result))
#define LLVM_NODISCARD_TYPE [[clang::warn_unused_result]]

via some shallow manual testing, it looks like using
LLVM_NODISCARD_TYPE on a function should break the build (though I'd
love it if someone more familiar with clang chimed in on this). So, is
the problem that we can accidentally use LLVM_UNUSED_RESULT on a type
and not know it?

I think there is a dirty trick here -- we could:

#define LLVM_UNUSED_RESULT __attribute__((warn_unused_result, enable_if(true, "")))
#define LLVM_NODISCARD_TYPE [[clang::warn_unused_result]]

This breaks the (clang) build if LLVM_UNUSED_RESULT is used on a type.

It would still be possible to not do the right thing on GCC or MSVC
and be able to build a binary, but I think as long as the clang bots
catch bad uses we're okay.

-- Sanjoy`


More information about the llvm-dev mailing list