[flang-commits] [PATCH] D133693: [flang][runtime] ensure character compares to blank are unsigned

Jean Perier via Phabricator via flang-commits flang-commits at lists.llvm.org
Mon Sep 12 06:41:37 PDT 2022


jeanPerier created this revision.
jeanPerier added reviewers: klausler, clementval, PeteSteinfeld.
jeanPerier added a project: Flang.
Herald added a subscriber: jdoerfert.
Herald added a project: All.
jeanPerier requested review of this revision.

CompareToBlankPadding was doing signed compare on architecture where
`char` is signed. This caused `'abc'//char(128) > 'abc'` to evaluate
to false at runtime instead of true.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133693

Files:
  flang/runtime/character.cpp
  flang/unittests/Runtime/CharacterTest.cpp


Index: flang/unittests/Runtime/CharacterTest.cpp
===================================================================
--- flang/unittests/Runtime/CharacterTest.cpp
+++ flang/unittests/Runtime/CharacterTest.cpp
@@ -171,6 +171,8 @@
         std::make_tuple("abc", "def", 3, 3, -1),
         std::make_tuple("ab ", "abc", 3, 2, 0),
         std::make_tuple("abc", "abc", 2, 3, -1),
+        std::make_tuple("ab\xff", "ab ", 3, 2, 1),
+        std::make_tuple("ab ", "ab\xff", 2, 3, -1),
     },
     {
         std::make_tuple(u"abc", u"abc", 3, 3, 0),
Index: flang/runtime/character.cpp
===================================================================
--- flang/runtime/character.cpp
+++ flang/runtime/character.cpp
@@ -20,11 +20,13 @@
 
 template <typename CHAR>
 inline int CompareToBlankPadding(const CHAR *x, std::size_t chars) {
+  using UNSIGNED_CHAR = std::make_unsigned_t<CHAR>;
+  const auto blank{static_cast<UNSIGNED_CHAR>(' ')};
   for (; chars-- > 0; ++x) {
-    if (*x < ' ') {
+    if (*reinterpret_cast<const UNSIGNED_CHAR *>(x) < blank) {
       return -1;
     }
-    if (*x > ' ') {
+    if (*reinterpret_cast<const UNSIGNED_CHAR *>(x) > blank) {
       return 1;
     }
   }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D133693.459440.patch
Type: text/x-patch
Size: 1195 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/flang-commits/attachments/20220912/f3a3ef82/attachment.bin>


More information about the flang-commits mailing list