[PATCH] D139683: [APInt] provide a safe API for zext value and sext value.

Peter Rong via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Fri Dec 9 17:21:52 PST 2022


Peter updated this revision to Diff 481800.
Peter marked an inline comment as done.
Peter added a comment.

use std::optional and inlining the API


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D139683/new/

https://reviews.llvm.org/D139683

Files:
  llvm/include/llvm/ADT/APInt.h
  llvm/unittests/ADT/APIntTest.cpp


Index: llvm/unittests/ADT/APIntTest.cpp
===================================================================
--- llvm/unittests/ADT/APIntTest.cpp
+++ llvm/unittests/ADT/APIntTest.cpp
@@ -3133,4 +3133,15 @@
   Map.find(ZeroWidthInt);
 }
 
+TEST(APIntTest, TryExt) {
+  APInt small(32, 42);
+  APInt large(128, {0xffff, 0xffff});
+  ASSERT_TRUE(small.tryZExtValue());
+  ASSERT_TRUE(small.trySExtValue());
+  ASSERT_FALSE(large.tryZExtValue());
+  ASSERT_FALSE(large.trySExtValue());
+  ASSERT_EQ(small.trySExtValue().value_or(41), 42);
+  ASSERT_EQ(large.trySExtValue().value_or(41), 41);
+}
+
 } // end anonymous namespace
Index: llvm/include/llvm/ADT/APInt.h
===================================================================
--- llvm/include/llvm/ADT/APInt.h
+++ llvm/include/llvm/ADT/APInt.h
@@ -1491,6 +1491,16 @@
     return U.pVal[0];
   }
 
+  /// Get zero extended value if possible
+  ///
+  /// This method attempts to return the value of this APInt as a zero extended
+  /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
+  /// uint64_t. Otherwise no value is returned.
+  std::optional<uint64_t> tryZExtValue() const {
+    return (getActiveBits() <= 64) ? std::optional<uint64_t>(getZExtValue())
+                                   : std::optional<uint64_t>();
+  };
+
   /// Get sign extended value
   ///
   /// This method attempts to return the value of this APInt as a sign extended
@@ -1503,6 +1513,16 @@
     return int64_t(U.pVal[0]);
   }
 
+  /// Get sign extended value if possible
+  ///
+  /// This method attempts to return the value of this APInt as a zero extended
+  /// int64_t. The bitwidth must be <= 64 or the value must fit within an
+  /// int64_t. Otherwise no value is returned.
+  std::optional<int64_t> trySExtValue() const {
+    return (getActiveBits() <= 64) ? std::optional<int64_t>(getSExtValue())
+                                   : std::optional<int64_t>();
+  };
+
   /// Get bits required for string value.
   ///
   /// This method determines how many bits are required to hold the APInt


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D139683.481800.patch
Type: text/x-patch
Size: 2062 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20221210/01e3af03/attachment.bin>


More information about the llvm-commits mailing list