[PATCH] D22445: Avoid UB in maxIntN(64).

Justin Lebar via llvm-commits llvm-commits at lists.llvm.org
Sat Jul 16 15:20:33 PDT 2016


jlebar created this revision.
jlebar added a reviewer: rnk.
jlebar added subscribers: llvm-commits, dylanmckay.

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.

https://reviews.llvm.org/D22445

Files:
  include/llvm/Support/MathExtras.h

Index: include/llvm/Support/MathExtras.h
===================================================================
--- include/llvm/Support/MathExtras.h
+++ include/llvm/Support/MathExtras.h
@@ -343,7 +343,9 @@
 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 cast to
+  // uint64_t to avoid UB.
+  return static_cast<uint64_t>(INT64_C(1) << (N - 1)) - 1;
 }
 
 /// isUIntN - Checks if an unsigned integer fits into the given (dynamic)


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D22445.64237.patch
Type: text/x-patch
Size: 585 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20160716/c0aac6da/attachment.bin>


More information about the llvm-commits mailing list