[PATCH] D153356: [Align] Add isAligned taking an APInt

Guillaume Chatelet via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 20 07:42:05 PDT 2023


gchatelet created this revision.
gchatelet added a reviewer: courbet.
Herald added a project: All.
gchatelet requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

This showed up in https://reviews.llvm.org/D153308


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D153356

Files:
  llvm/include/llvm/Support/Alignment.h
  llvm/unittests/Support/AlignmentTest.cpp


Index: llvm/unittests/Support/AlignmentTest.cpp
===================================================================
--- llvm/unittests/Support/AlignmentTest.cpp
+++ llvm/unittests/Support/AlignmentTest.cpp
@@ -153,8 +153,14 @@
     if (A) {
       EXPECT_EQ(isAligned(*A, T.offset), T.isAligned);
       EXPECT_EQ(isAddrAligned(*A, T.forgedAddr()), T.isAligned);
+      EXPECT_EQ(isAligned(*A, APInt(32, T.offset)), T.isAligned);
     }
   }
+  // Additional tests for APInt that can't represent the alignment.
+  // Here APInt(4, I) can represent values from 0 to 15.
+  EXPECT_TRUE(isAligned(Align(32), APInt(4, 0))); // zero is always aligned.
+  for (int I = 1; I < 16; ++I)
+    EXPECT_FALSE(isAligned(Align(32), APInt(4, I)));
 }
 
 TEST(AlignmentTest, offsetToAlignment) {
Index: llvm/include/llvm/Support/Alignment.h
===================================================================
--- llvm/include/llvm/Support/Alignment.h
+++ llvm/include/llvm/Support/Alignment.h
@@ -21,6 +21,7 @@
 #ifndef LLVM_SUPPORT_ALIGNMENT_H_
 #define LLVM_SUPPORT_ALIGNMENT_H_
 
+#include "llvm/ADT/APInt.h"
 #include "llvm/Support/MathExtras.h"
 #include <cassert>
 #include <optional>
@@ -146,6 +147,15 @@
   return SizeInBytes % Lhs.value() == 0;
 }
 
+/// Checks that SizeInBytes is a multiple of the alignment.
+inline bool isAligned(Align Lhs, const APInt &SizeInBytes) {
+  if (SizeInBytes.isZero())
+    return true;
+  const unsigned OffsetTrailingZeroes = SizeInBytes.countr_zero();
+  const unsigned MinimumTrailingZeroes = Log2(Lhs);
+  return OffsetTrailingZeroes >= MinimumTrailingZeroes;
+}
+
 /// Checks that Addr is a multiple of the alignment.
 inline bool isAddrAligned(Align Lhs, const void *Addr) {
   return isAligned(Lhs, reinterpret_cast<uintptr_t>(Addr));


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D153356.532931.patch
Type: text/x-patch
Size: 1769 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20230620/dfc2f489/attachment.bin>


More information about the llvm-commits mailing list