Fixes error when splitting block comments.

When trying to fall back to search from the end onwards, we
would still find leading whitespace if the leading whitespace
went on after the end of the line.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@182886 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Format/BreakableToken.cpp b/lib/Format/BreakableToken.cpp
index c102f8b..5c3ad9ce 100644
--- a/lib/Format/BreakableToken.cpp
+++ b/lib/Format/BreakableToken.cpp
@@ -87,8 +87,16 @@
   StringRef::size_type SpaceOffset = Text.rfind(' ', MaxSplit);
   if (SpaceOffset == StringRef::npos ||
       // Don't break at leading whitespace.
-      Text.find_last_not_of(' ', SpaceOffset) == StringRef::npos)
-    SpaceOffset = Text.find(' ', MaxSplit);
+      Text.find_last_not_of(' ', SpaceOffset) == StringRef::npos) {
+    // Make sure that we don't break at leading whitespace that
+    // reaches past MaxSplit.
+    StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(" ");
+    if (FirstNonWhitespace == StringRef::npos)
+      // If the comment is only whitespace, we cannot split.
+      return BreakableToken::Split(StringRef::npos, 0);
+    SpaceOffset =
+        Text.find(' ', std::max<unsigned>(MaxSplit, FirstNonWhitespace));
+  }
   if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
     StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim();
     StringRef AfterCut = Text.substr(SpaceOffset).ltrim();
diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp
index 18a1a00..1f4f480 100644
--- a/unittests/Format/FormatTest.cpp
+++ b/unittests/Format/FormatTest.cpp
@@ -3694,6 +3694,33 @@
                    getLLVMStyleWithColumns(20)));
 }
 
+TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
+  EXPECT_EQ("a = {\n"
+            "  1111 /*    */\n"
+            "};",
+            format("a = {1111\n"
+                   "/*    */\n"
+                   "};",
+                   getLLVMStyleWithColumns(15)));
+  EXPECT_EQ("a = {\n"
+            "  1111 /*      */\n"
+            "};",
+            format("a = {1111\n"
+                   "/*      */\n"
+                   "};",
+                   getLLVMStyleWithColumns(15)));
+
+  // FIXME: The formatting is still wrong here.
+  EXPECT_EQ("a = {\n"
+            "  1111 /*      a\n"
+            "          */\n"
+            "};",
+            format("a = {1111\n"
+                   "/*      a */\n"
+                   "};",
+                   getLLVMStyleWithColumns(15)));
+}
+
 TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
   // FIXME: This is not what we want...
   verifyFormat("{\n"