[demangler] Reorder parseNestedName loop

parseNestedName's main loop allowed parsing a grammar that was more
flexible than the actual grammar.  This refactors that to rule out
some more incorrect manglings.

1) The 'L' extension only applies to unqualified-name components, so
check it just there.

2) The 'M' suffix is, AFAICT, removed from the grammar.  Rather than
eliminate it, let's parse it after we've parsed a component.

Added some additional bad mangling tests, which are now rejected.

I don't break the 'T' and 'D[tT]' cases out of the loop, even though
they can only appear at first position, as it seems simpler to just
check there is nothing SoFar.

Reviewed By: ChuanqiXu

Differential Revision: https://reviews.llvm.org/D119542

GitOrigin-RevId: 6244730e29f66ae3d0ba80c2341f9f17c7eb78d3
diff --git a/src/demangle/ItaniumDemangle.h b/src/demangle/ItaniumDemangle.h
index a8d96fd..5318a4c 100644
--- a/src/demangle/ItaniumDemangle.h
+++ b/src/demangle/ItaniumDemangle.h
@@ -3188,15 +3188,6 @@
 
   Node *SoFar = nullptr;
   while (!consumeIf('E')) {
-    consumeIf('L'); // extension
-
-    if (consumeIf('M')) {
-      // <data-member-prefix> := <member source-name> [<template-args>] M
-      if (SoFar == nullptr)
-        return nullptr;
-      continue;
-    }
-
     if (State)
       // Only set end-with-template on the case that does that.
       State->EndsWithTemplateArgs = false;
@@ -3241,12 +3232,17 @@
         return nullptr;
       continue; // Do not push a new substitution.
     } else {
+      consumeIf('L'); // extension
       //          ::= [<prefix>] <unqualified-name>
       SoFar = getDerived().parseUnqualifiedName(State, SoFar);
     }
     if (SoFar == nullptr)
       return nullptr;
     Subs.push_back(SoFar);
+
+    // No longer used.
+    // <data-member-prefix> := <member source-name> [<template-args>] M
+    consumeIf('M');
   }
 
   if (SoFar == nullptr || Subs.empty())
diff --git a/test/test_demangle.pass.cpp b/test/test_demangle.pass.cpp
index cc9e4ac..2f43814 100644
--- a/test/test_demangle.pass.cpp
+++ b/test/test_demangle.pass.cpp
@@ -29947,6 +29947,9 @@
     "_ZN3CLSIiEIiEE",
     "_ZN3CLSDtLi0EEE",
     "_ZN3CLSIiEEvNS_T_Ev",
+
+    "_ZN1fIiEEvNTUt_E",
+    "_ZNDTUt_Ev",
 };
 
 const unsigned NI = sizeof(invalid_cases) / sizeof(invalid_cases[0]);