From f36e8699d3c7caab41f1ebd77ae1f81ba9d0598f Mon Sep 17 00:00:00 2001 From: Justin Lebar Date: Sun, 17 Jul 2016 18:19:26 +0000 Subject: [PATCH] Avoid UB in maxIntN(64). Summary: Previously we were relying on 2's complement underflow in an int64_t. Now we cast to a uint64_t so we explicitly get the behavior we want. Reviewers: rnk Subscribers: dylanmckay, llvm-commits Differential Revision: https://reviews.llvm.org/D22445 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@275722 91177308-0d34-0410-b5e6-96231b3b80d8 --- include/llvm/Support/MathExtras.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/include/llvm/Support/MathExtras.h b/include/llvm/Support/MathExtras.h index 939800b42b6..cf033e30aac 100644 --- a/include/llvm/Support/MathExtras.h +++ b/include/llvm/Support/MathExtras.h @@ -344,7 +344,9 @@ inline int64_t minIntN(int64_t N) { inline int64_t maxIntN(int64_t N) { assert(N > 0 && N <= 64 && "integer width out of range"); - return (INT64_C(1)<<(N-1)) - 1; + // This relies on two's complement wraparound when N == 64, so we convert to + // int64_t only at the very end to avoid UB. + return (UINT64_C(1) << (N - 1)) - 1; } /// isUIntN - Checks if an unsigned integer fits into the given (dynamic) -- 2.50.1