Make llvm::StringRef to std::string conversions explicit.

This is how it should've been and brings it more in line with
std::string_view. There should be no functional change here.

This is mostly mechanical from a custom clang-tidy check, with a lot of
manual fixups. It uncovers a lot of minor inefficiencies.

This doesn't actually modify StringRef yet, I'll do that in a follow-up.
diff --git a/clang/utils/TableGen/ClangASTNodesEmitter.cpp b/clang/utils/TableGen/ClangASTNodesEmitter.cpp
index 1cc46cb..2b8d7a9 100644
--- a/clang/utils/TableGen/ClangASTNodesEmitter.cpp
+++ b/clang/utils/TableGen/ClangASTNodesEmitter.cpp
@@ -51,7 +51,7 @@
   const std::string &macroHierarchyName() {
     assert(Root && "root node not yet derived!");
     if (MacroHierarchyName.empty())
-      MacroHierarchyName = macroName(Root.getName());
+      MacroHierarchyName = macroName(std::string(Root.getName()));
     return MacroHierarchyName;
   }
 
@@ -86,7 +86,7 @@
 // Called recursively to ensure that nodes remain contiguous
 std::pair<ASTNode, ASTNode> ClangASTNodesEmitter::EmitNode(raw_ostream &OS,
                                                            ASTNode Base) {
-  std::string BaseName = macroName(Base.getName());
+  std::string BaseName = macroName(std::string(Base.getName()));
 
   ChildIterator i = Tree.lower_bound(Base), e = Tree.upper_bound(Base);
   bool HasChildren = (i != e);
@@ -98,7 +98,7 @@
   for (; i != e; ++i) {
     ASTNode Child = i->second;
     bool Abstract = Child.isAbstract();
-    std::string NodeName = macroName(Child.getName());
+    std::string NodeName = macroName(std::string(Child.getName()));
 
     OS << "#ifndef " << NodeName << "\n";
     OS << "#  define " << NodeName << "(Type, Base) "
diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 4c3742c..92792bb 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -54,14 +54,13 @@
   FlattenedSpelling(const std::string &Variety, const std::string &Name,
                     const std::string &Namespace, bool KnownToGCC) :
     V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
-  explicit FlattenedSpelling(const Record &Spelling) :
-    V(Spelling.getValueAsString("Variety")),
-    N(Spelling.getValueAsString("Name")) {
-
+  explicit FlattenedSpelling(const Record &Spelling)
+      : V(std::string(Spelling.getValueAsString("Variety"))),
+        N(std::string(Spelling.getValueAsString("Name"))) {
     assert(V != "GCC" && V != "Clang" &&
            "Given a GCC spelling, which means this hasn't been flattened!");
     if (V == "CXX11" || V == "C2x" || V == "Pragma")
-      NS = Spelling.getValueAsString("Namespace");
+      NS = std::string(Spelling.getValueAsString("Namespace"));
     bool Unset;
     K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
   }
@@ -84,13 +83,13 @@
     StringRef Name = Spelling->getValueAsString("Name");
     if (Variety == "GCC") {
       // Gin up two new spelling objects to add into the list.
-      Ret.emplace_back("GNU", Name, "", true);
-      Ret.emplace_back("CXX11", Name, "gnu", true);
+      Ret.emplace_back("GNU", std::string(Name), "", true);
+      Ret.emplace_back("CXX11", std::string(Name), "gnu", true);
     } else if (Variety == "Clang") {
-      Ret.emplace_back("GNU", Name, "", false);
-      Ret.emplace_back("CXX11", Name, "clang", false);
+      Ret.emplace_back("GNU", std::string(Name), "", false);
+      Ret.emplace_back("CXX11", std::string(Name), "clang", false);
       if (Spelling->getValueAsBit("AllowInC"))
-        Ret.emplace_back("C2x", Name, "clang", false);
+        Ret.emplace_back("C2x", std::string(Name), "clang", false);
     } else
       Ret.push_back(FlattenedSpelling(*Spelling));
   }
@@ -100,14 +99,15 @@
 
 static std::string ReadPCHRecord(StringRef type) {
   return StringSwitch<std::string>(type)
-    .EndsWith("Decl *", "Record.GetLocalDeclAs<" 
-              + std::string(type, 0, type.size()-1) + ">(Record.readInt())")
-    .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
-    .Case("Expr *", "Record.readExpr()")
-    .Case("IdentifierInfo *", "Record.readIdentifier()")
-    .Case("StringRef", "Record.readString()")
-    .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
-    .Default("Record.readInt()");
+      .EndsWith("Decl *", "Record.GetLocalDeclAs<" +
+                              std::string(type.data(), 0, type.size() - 1) +
+                              ">(Record.readInt())")
+      .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
+      .Case("Expr *", "Record.readExpr()")
+      .Case("IdentifierInfo *", "Record.readIdentifier()")
+      .Case("StringRef", "Record.readString()")
+      .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
+      .Default("Record.readInt()");
 }
 
 // Get a type that is suitable for storing an object of the specified type.
@@ -119,14 +119,18 @@
 
 // Assumes that the way to get the value is SA->getname()
 static std::string WritePCHRecord(StringRef type, StringRef name) {
-  return "Record." + StringSwitch<std::string>(type)
-    .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
-    .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
-    .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
-    .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
-    .Case("StringRef", "AddString(" + std::string(name) + ");\n")
-    .Case("ParamIdx", "push_back(" + std::string(name) + ".serialize());\n")
-    .Default("push_back(" + std::string(name) + ");\n");
+  return "Record." +
+         StringSwitch<std::string>(type)
+             .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
+             .Case("TypeSourceInfo *",
+                   "AddTypeSourceInfo(" + std::string(name) + ");\n")
+             .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
+             .Case("IdentifierInfo *",
+                   "AddIdentifierRef(" + std::string(name) + ");\n")
+             .Case("StringRef", "AddString(" + std::string(name) + ");\n")
+             .Case("ParamIdx",
+                   "push_back(" + std::string(name) + ".serialize());\n")
+             .Default("push_back(" + std::string(name) + ");\n");
 }
 
 // Normalize attribute name by removing leading and trailing
@@ -167,7 +171,7 @@
       std::string AN;
       if (Attr->isSubClassOf("TargetSpecificAttr") &&
           !Attr->isValueUnset("ParseKind")) {
-        AN = Attr->getValueAsString("ParseKind");
+        AN = std::string(Attr->getValueAsString("ParseKind"));
 
         // If this attribute has already been handled, it does not need to be
         // handled again.
@@ -196,8 +200,8 @@
 
   public:
     Argument(const Record &Arg, StringRef Attr)
-      : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
-        attrName(Attr), isOpt(false), Fake(false) {
+        : lowerName(std::string(Arg.getValueAsString("Name"))),
+          upperName(lowerName), attrName(Attr), isOpt(false), Fake(false) {
       if (!lowerName.empty()) {
         lowerName[0] = std::tolower(lowerName[0]);
         upperName[0] = std::toupper(upperName[0]);
@@ -299,8 +303,9 @@
     }
 
     void writePCHWrite(raw_ostream &OS) const override {
-      OS << "    " << WritePCHRecord(type, "SA->get" +
-                                           std::string(getUpperName()) + "()");
+      OS << "    "
+         << WritePCHRecord(type,
+                           "SA->get" + std::string(getUpperName()) + "()");
     }
 
     std::string getIsOmitted() const override {
@@ -642,7 +647,7 @@
     VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
         : Argument(Arg, Attr), Type(std::move(T)),
           ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
-          RangeName(getLowerName()) {}
+          RangeName(std::string(getLowerName())) {}
 
     const std::string &getType() const { return Type; }
     const std::string &getArgName() const { return ArgName; }
@@ -719,8 +724,8 @@
       // If we can't store the values in the current type (if it's something
       // like StringRef), store them in a different type and convert the
       // container afterwards.
-      std::string StorageType = getStorageType(getType());
-      std::string StorageName = getLowerName();
+      std::string StorageType = std::string(getStorageType(getType()));
+      std::string StorageName = std::string(getLowerName());
       if (StorageType != getType()) {
         StorageName += "Storage";
         OS << "    SmallVector<" << StorageType << ", 4> "
@@ -805,11 +810,10 @@
 
   public:
     EnumArgument(const Record &Arg, StringRef Attr)
-      : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
-        values(Arg.getValueAsListOfStrings("Values")),
-        enums(Arg.getValueAsListOfStrings("Enums")),
-        uniques(uniqueEnumsInOrder(enums))
-    {
+        : Argument(Arg, Attr), type(std::string(Arg.getValueAsString("Type"))),
+          values(Arg.getValueAsListOfStrings("Values")),
+          enums(Arg.getValueAsListOfStrings("Enums")),
+          uniques(uniqueEnumsInOrder(enums)) {
       // FIXME: Emit a proper error
       assert(!uniques.empty());
     }
@@ -934,12 +938,12 @@
 
   public:
     VariadicEnumArgument(const Record &Arg, StringRef Attr)
-      : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
-        type(Arg.getValueAsString("Type")),
-        values(Arg.getValueAsListOfStrings("Values")),
-        enums(Arg.getValueAsListOfStrings("Enums")),
-        uniques(uniqueEnumsInOrder(enums))
-    {
+        : VariadicArgument(Arg, Attr,
+                           std::string(Arg.getValueAsString("Type"))),
+          type(std::string(Arg.getValueAsString("Type"))),
+          values(Arg.getValueAsListOfStrings("Values")),
+          enums(Arg.getValueAsListOfStrings("Enums")),
+          uniques(uniqueEnumsInOrder(enums)) {
       QualifiedTypeName = getAttrName().str() + "Attr::" + type;
       
       // FIXME: Emit a proper error
@@ -1241,8 +1245,9 @@
     }
 
     void writePCHWrite(raw_ostream &OS) const override {
-      OS << "    " << WritePCHRecord(
-          getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
+      OS << "    "
+         << WritePCHRecord(getType(),
+                           "SA->get" + std::string(getUpperName()) + "Loc()");
     }
   };
 
@@ -1577,11 +1582,12 @@
 static bool
 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
   assert(!Spellings.empty() && "An empty list of spellings was provided");
-  std::string FirstName = NormalizeNameForSpellingComparison(
-    Spellings.front().name());
+  std::string FirstName =
+      std::string(NormalizeNameForSpellingComparison(Spellings.front().name()));
   for (const auto &Spelling :
        llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
-    std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
+    std::string Name =
+        std::string(NormalizeNameForSpellingComparison(Spelling.name()));
     if (Name != FirstName)
       return false;
   }
@@ -1727,7 +1733,7 @@
   }
 
   std::string getSpelling() const {
-    std::string Result = MetaSubject->getValueAsString("Name");
+    std::string Result = std::string(MetaSubject->getValueAsString("Name"));
     if (isSubRule()) {
       Result += '(';
       if (isNegatedSubRule())
@@ -1752,7 +1758,7 @@
     }
     if (isAbstractRule())
       Result += "_abstract";
-    return Result.str();
+    return std::string(Result.str());
   }
 
   std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
@@ -2258,7 +2264,7 @@
       const Record *R = Super.first;
       if (R->getName() != "TargetSpecificAttr" &&
           R->getName() != "DeclOrTypeAttr" && SuperName.empty())
-        SuperName = R->getName();
+        SuperName = std::string(R->getName());
       if (R->getName() == "InheritableAttr")
         Inheritable = true;
     }
@@ -3298,7 +3304,7 @@
 }
 
 static std::string GetDiagnosticSpelling(const Record &R) {
-  std::string Ret = R.getValueAsString("DiagSpelling");
+  std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
   if (!Ret.empty())
     return Ret;
 
@@ -3334,7 +3340,7 @@
       SmallVector<StringRef, 2> Frags;
       llvm::SplitString(V, Frags, ",");
       for (auto Str : Frags) {
-        DiagList.push_back(Str.trim());
+        DiagList.push_back(std::string(Str.trim()));
       }
     }
   }
@@ -3365,7 +3371,7 @@
 }
 
 static std::string GetSubjectWithSuffix(const Record *R) {
-  const std::string &B = R->getName();
+  const std::string &B = std::string(R->getName());
   if (B == "DeclBase")
     return "Decl";
   return B + "Decl";
@@ -3740,7 +3746,7 @@
       std::string AttrName;
       if (Attr.isSubClassOf("TargetSpecificAttr") &&
           !Attr.isValueUnset("ParseKind")) {
-        AttrName = Attr.getValueAsString("ParseKind");
+        AttrName = std::string(Attr.getValueAsString("ParseKind"));
         if (Seen.find(AttrName) != Seen.end())
           continue;
         Seen.insert(AttrName);
@@ -3980,7 +3986,7 @@
                     "documented");
 
   // Determine the heading to be used for this attribute.
-  std::string Heading = Documentation.getValueAsString("Heading");
+  std::string Heading = std::string(Documentation.getValueAsString("Heading"));
   if (Heading.empty()) {
     // If there's only one spelling, we can simply use that.
     if (Spellings.size() == 1)
@@ -3989,7 +3995,8 @@
       std::set<std::string> Uniques;
       for (auto I = Spellings.begin(), E = Spellings.end();
            I != E && Uniques.size() <= 1; ++I) {
-        std::string Spelling = NormalizeNameForSpellingComparison(I->name());
+        std::string Spelling =
+            std::string(NormalizeNameForSpellingComparison(I->name()));
         Uniques.insert(Spelling);
       }
       // If the semantic map has only one spelling, that is sufficient for our
diff --git a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
index fc79d59..eb2f231 100644
--- a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
@@ -63,7 +63,7 @@
   std::vector<StringMatcher::StringPair> Matches;
   for (size_t i = 0, e = Tags.size(); i != e; ++i) {
     Record &Tag = *Tags[i];
-    std::string Name = Tag.getValueAsString("Name");
+    std::string Name = std::string(Tag.getValueAsString("Name"));
     std::string Return;
     raw_string_ostream(Return) << "return &Commands[" << i << "];";
     Matches.emplace_back(std::move(Name), std::move(Return));
diff --git a/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp b/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
index ed3f4bd..a25ab11 100644
--- a/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
@@ -54,7 +54,7 @@
   for (std::vector<Record *>::iterator I = Tags.begin(), E = Tags.end();
        I != E; ++I) {
     Record &Tag = **I;
-    std::string Spelling = Tag.getValueAsString("Spelling");
+    std::string Spelling = std::string(Tag.getValueAsString("Spelling"));
     uint64_t CodePoint = Tag.getValueAsInt("CodePoint");
     CLiteral.clear();
     CLiteral.append("return ");
diff --git a/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp b/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
index 7b9fdfc..1c15029 100644
--- a/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
@@ -40,7 +40,7 @@
   std::vector<StringMatcher::StringPair> MatchesEndTagOptional;
   std::vector<StringMatcher::StringPair> MatchesEndTagForbidden;
   for (Record *Tag : Tags) {
-    std::string Spelling = Tag->getValueAsString("Spelling");
+    std::string Spelling = std::string(Tag->getValueAsString("Spelling"));
     StringMatcher::StringPair Match(Spelling, "return true;");
     if (Tag->getValueAsBit("EndTagOptional"))
       MatchesEndTagOptional.push_back(Match);
diff --git a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
index f694c3e..eb1fb8d 100644
--- a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
+++ b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
@@ -62,7 +62,7 @@
 getCategoryFromDiagGroup(const Record *Group,
                          DiagGroupParentMap &DiagGroupParents) {
   // If the DiagGroup has a category, return it.
-  std::string CatName = Group->getValueAsString("CategoryName");
+  std::string CatName = std::string(Group->getValueAsString("CategoryName"));
   if (!CatName.empty()) return CatName;
 
   // The diag group may the subgroup of one or more other diagnostic groups,
@@ -88,7 +88,7 @@
   }
 
   // If the diagnostic itself has a category, get it.
-  return R->getValueAsString("CategoryName");
+  return std::string(R->getValueAsString("CategoryName"));
 }
 
 namespace {
@@ -168,7 +168,8 @@
       continue;
     assert(R->getValueAsDef("Class")->getName() != "CLASS_NOTE" &&
            "Note can't be in a DiagGroup");
-    std::string GroupName = DI->getDef()->getValueAsString("GroupName");
+    std::string GroupName =
+        std::string(DI->getDef()->getValueAsString("GroupName"));
     DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
   }
 
@@ -179,7 +180,8 @@
   // groups (these are warnings that GCC supports that clang never produces).
   for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
     Record *Group = DiagGroups[i];
-    GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];
+    GroupInfo &GI =
+        DiagsInGroup[std::string(Group->getValueAsString("GroupName"))];
     if (Group->isAnonymous()) {
       if (GI.DiagsInGroup.size() > 1)
         ImplicitGroups.insert(&GI);
@@ -192,7 +194,8 @@
 
     std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");
     for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
-      GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
+      GI.SubGroups.push_back(
+          std::string(SubGroups[j]->getValueAsString("GroupName")));
   }
 
   // Assign unique ID numbers to the groups.
@@ -219,7 +222,8 @@
     ArrayRef<const Record *> GroupDiags = (*I)->DiagsInGroup;
 
     if ((*I)->ExplicitDef) {
-      std::string Name = (*I)->ExplicitDef->getValueAsString("GroupName");
+      std::string Name =
+          std::string((*I)->ExplicitDef->getValueAsString("GroupName"));
       for (ArrayRef<const Record *>::const_iterator DI = GroupDiags.begin(),
                                                     DE = GroupDiags.end();
            DI != DE; ++DI) {
@@ -244,7 +248,8 @@
 
       const DefInit *GroupInit = cast<DefInit>((*DI)->getValueInit("Group"));
       const Record *NextDiagGroup = GroupInit->getDef();
-      std::string Name = NextDiagGroup->getValueAsString("GroupName");
+      std::string Name =
+          std::string(NextDiagGroup->getValueAsString("GroupName"));
 
       SrcMgr.PrintMessage((*DI)->getLoc().front(),
                           SourceMgr::DK_Error,
@@ -315,8 +320,8 @@
 
 bool InferPedantic::isSubGroupOfGroup(const Record *Group,
                                       llvm::StringRef GName) {
-
-  const std::string &GroupName = Group->getValueAsString("GroupName");
+  const std::string &GroupName =
+      std::string(Group->getValueAsString("GroupName"));
   if (GName == GroupName)
     return true;
 
@@ -330,13 +335,14 @@
 
 /// Determine if the diagnostic is an extension.
 bool InferPedantic::isExtension(const Record *Diag) {
-  const std::string &ClsName = Diag->getValueAsDef("Class")->getName();
+  const std::string &ClsName =
+      std::string(Diag->getValueAsDef("Class")->getName());
   return ClsName == "CLASS_EXTENSION";
 }
 
 bool InferPedantic::isOffByDefault(const Record *Diag) {
-  const std::string &DefSeverity =
-      Diag->getValueAsDef("DefaultSeverity")->getValueAsString("Name");
+  const std::string &DefSeverity = std::string(
+      Diag->getValueAsDef("DefaultSeverity")->getValueAsString("Name"));
   return DefSeverity == "Ignored";
 }
 
@@ -344,7 +350,8 @@
   GMap::mapped_type &V = GroupCount[Group];
   // Lazily compute the threshold value for the group count.
   if (!V.second.hasValue()) {
-    const GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];
+    const GroupInfo &GI =
+        DiagsInGroup[std::string(Group->getValueAsString("GroupName"))];
     V.second = GI.SubGroups.size() + GI.DiagsInGroup.size();
   }
 
@@ -1176,12 +1183,14 @@
 //===----------------------------------------------------------------------===//
 
 static bool isError(const Record &Diag) {
-  const std::string &ClsName = Diag.getValueAsDef("Class")->getName();
+  const std::string &ClsName =
+      std::string(Diag.getValueAsDef("Class")->getName());
   return ClsName == "CLASS_ERROR";
 }
 
 static bool isRemark(const Record &Diag) {
-  const std::string &ClsName = Diag.getValueAsDef("Class")->getName();
+  const std::string &ClsName =
+      std::string(Diag.getValueAsDef("Class")->getName());
   return ClsName == "CLASS_REMARK";
 }
 
@@ -1226,7 +1235,8 @@
     if (isError(R)) {
       if (DefInit *Group = dyn_cast<DefInit>(R.getValueInit("Group"))) {
         const Record *GroupRec = Group->getDef();
-        const std::string &GroupName = GroupRec->getValueAsString("GroupName");
+        const std::string &GroupName =
+            std::string(GroupRec->getValueAsString("GroupName"));
         PrintFatalError(R.getLoc(), "Error " + R.getName() +
                       " cannot be in a warning group [" + GroupName + "]");
       }
@@ -1256,8 +1266,8 @@
     // Warning associated with the diagnostic. This is stored as an index into
     // the alphabetically sorted warning table.
     if (DefInit *DI = dyn_cast<DefInit>(R.getValueInit("Group"))) {
-      std::map<std::string, GroupInfo>::iterator I =
-          DiagsInGroup.find(DI->getDef()->getValueAsString("GroupName"));
+      std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.find(
+          std::string(DI->getDef()->getValueAsString("GroupName")));
       assert(I != DiagsInGroup.end());
       OS << ", " << I->second.IDNo;
     } else if (DiagsInPedantic.count(&R)) {
@@ -1299,7 +1309,7 @@
   SmallString<256> enumName = llvm::StringRef("DiagCat_");
   for (llvm::StringRef::iterator I = name.begin(), E = name.end(); I != E; ++I)
     enumName += isalnum(*I) ? *I : '_';
-  return enumName.str();
+  return std::string(enumName.str());
 }
 
 /// Emit the array of diagnostic subgroups.
@@ -1335,7 +1345,8 @@
       // Emit the groups implicitly in "pedantic".
       if (IsPedantic) {
         for (auto const &Group : GroupsInPedantic) {
-          const std::string &GroupName = Group->getValueAsString("GroupName");
+          const std::string &GroupName =
+              std::string(Group->getValueAsString("GroupName"));
           std::map<std::string, GroupInfo>::const_iterator RI =
               DiagsInGroup.find(GroupName);
           assert(RI != DiagsInGroup.end() && "Referenced without existing?");
@@ -1572,8 +1583,8 @@
 struct RecordIndexElement
 {
   RecordIndexElement() {}
-  explicit RecordIndexElement(Record const &R):
-    Name(R.getName()) {}
+  explicit RecordIndexElement(Record const &R)
+      : Name(std::string(R.getName())) {}
 
   std::string Name;
 };
@@ -1614,7 +1625,7 @@
   bool AnyRemarks = false, AnyNonRemarks = false;
 
   std::function<void(StringRef)> Visit = [&](StringRef GroupName) {
-    auto &GroupInfo = DiagsInGroup.find(GroupName)->second;
+    auto &GroupInfo = DiagsInGroup.find(std::string(GroupName))->second;
     for (const Record *Diag : GroupInfo.DiagsInGroup)
       (isRemark(*Diag) ? AnyRemarks : AnyNonRemarks) = true;
     for (const auto &Name : GroupInfo.SubGroups)
@@ -1630,7 +1641,8 @@
 }
 
 std::string getDefaultSeverity(const Record *Diag) {
-  return Diag->getValueAsDef("DefaultSeverity")->getValueAsString("Name");
+  return std::string(
+      Diag->getValueAsDef("DefaultSeverity")->getValueAsString("Name"));
 }
 
 std::set<std::string>
@@ -1639,7 +1651,7 @@
   std::set<std::string> States;
 
   std::function<void(StringRef)> Visit = [&](StringRef GroupName) {
-    auto &GroupInfo = DiagsInGroup.find(GroupName)->second;
+    auto &GroupInfo = DiagsInGroup.find(std::string(GroupName))->second;
     for (const Record *Diag : GroupInfo.DiagsInGroup)
       States.insert(getDefaultSeverity(Diag));
     for (const auto &Name : GroupInfo.SubGroups)
@@ -1714,7 +1726,8 @@
                                  DiagsInPedantic.begin(),
                                  DiagsInPedantic.end());
     for (auto *Group : GroupsInPedantic)
-      PedDiags.SubGroups.push_back(Group->getValueAsString("GroupName"));
+      PedDiags.SubGroups.push_back(
+          std::string(Group->getValueAsString("GroupName")));
   }
 
   // FIXME: Write diagnostic categories and link to diagnostic groups in each.
@@ -1722,7 +1735,8 @@
   // Write out the diagnostic groups.
   for (const Record *G : DiagGroups) {
     bool IsRemarkGroup = isRemarkGroup(G, DiagsInGroup);
-    auto &GroupInfo = DiagsInGroup[G->getValueAsString("GroupName")];
+    auto &GroupInfo =
+        DiagsInGroup[std::string(G->getValueAsString("GroupName"))];
     bool IsSynonym = GroupInfo.DiagsInGroup.empty() &&
                      GroupInfo.SubGroups.size() == 1;
 
diff --git a/clang/utils/TableGen/ClangOptionDocEmitter.cpp b/clang/utils/TableGen/ClangOptionDocEmitter.cpp
index b944ad9..23aa31c 100644
--- a/clang/utils/TableGen/ClangOptionDocEmitter.cpp
+++ b/clang/utils/TableGen/ClangOptionDocEmitter.cpp
@@ -48,7 +48,7 @@
 
   std::map<std::string, Record*> OptionsByName;
   for (Record *R : Records.getAllDerivedDefinitions("Option"))
-    OptionsByName[R->getValueAsString("Name")] = R;
+    OptionsByName[std::string(R->getValueAsString("Name"))] = R;
 
   auto Flatten = [](Record *R) {
     return R->getValue("DocFlatten") && R->getValueAsBit("DocFlatten");
@@ -81,7 +81,7 @@
     }
 
     // Pretend no-X and Xno-Y options are aliases of X and XY.
-    std::string Name = R->getValueAsString("Name");
+    std::string Name = std::string(R->getValueAsString("Name"));
     if (Name.size() >= 4) {
       if (Name.substr(0, 3) == "no-" && OptionsByName[Name.substr(3)]) {
         Aliases[OptionsByName[Name.substr(3)]].push_back(R);
@@ -223,7 +223,7 @@
         return Field == Primary ? Value.str() : escapeRST(Value);
     }
   }
-  return StringRef();
+  return std::string(StringRef());
 }
 
 void emitOptionWithArgs(StringRef Prefix, const Record *Option,
@@ -247,7 +247,7 @@
 
   std::vector<std::string> Args;
   if (HasMetaVarName)
-    Args.push_back(Option->getValueAsString("MetaVarName"));
+    Args.push_back(std::string(Option->getValueAsString("MetaVarName")));
   else if (NumArgs == 1)
     Args.push_back("<arg>");
 
@@ -316,8 +316,8 @@
   std::vector<std::string> SphinxOptionIDs;
   forEachOptionName(Option, DocInfo, [&](const Record *Option) {
     for (auto &Prefix : Option->getValueAsListOfStrings("Prefixes"))
-      SphinxOptionIDs.push_back(
-          getSphinxOptionID((Prefix + Option->getValueAsString("Name")).str()));
+      SphinxOptionIDs.push_back(std::string(getSphinxOptionID(
+          (Prefix + Option->getValueAsString("Name")).str())));
   });
   assert(!SphinxOptionIDs.empty() && "no flags for option");
   static std::map<std::string, int> NextSuffix;
diff --git a/clang/utils/TableGen/ClangSACheckersEmitter.cpp b/clang/utils/TableGen/ClangSACheckersEmitter.cpp
index feefbeb..50725ae 100644
--- a/clang/utils/TableGen/ClangSACheckersEmitter.cpp
+++ b/clang/utils/TableGen/ClangSACheckersEmitter.cpp
@@ -53,7 +53,7 @@
 
 static std::string getStringValue(const Record &R, StringRef field) {
   if (StringInit *SI = dyn_cast<StringInit>(R.getValueInit(field)))
-    return SI->getValue();
+    return std::string(SI->getValue());
   return std::string();
 }
 
diff --git a/clang/utils/TableGen/MveEmitter.cpp b/clang/utils/TableGen/MveEmitter.cpp
index 664787f..d3af74f 100644
--- a/clang/utils/TableGen/MveEmitter.cpp
+++ b/clang/utils/TableGen/MveEmitter.cpp
@@ -242,7 +242,7 @@
                .Case("u", ScalarTypeKind::UnsignedInt)
                .Case("f", ScalarTypeKind::Float);
     Bits = Record->getValueAsInt("size");
-    NameOverride = Record->getValueAsString("nameOverride");
+    NameOverride = std::string(Record->getValueAsString("nameOverride"));
   }
   unsigned sizeInBits() const override { return Bits; }
   ScalarTypeKind kind() const { return Kind; }
@@ -423,16 +423,16 @@
       // variable we should be keeping things in.
       int MapValue = (*ParamNumberMap)[nparams++];
       if (MapValue < 0)
-        return Value;
+        return std::string(Value);
       ParamNumber = MapValue;
     }
 
     // If we've allocated a new parameter variable for the first time, store
     // its type and value to be retrieved after codegen.
     if (ParamTypes && ParamTypes->size() == ParamNumber)
-      ParamTypes->push_back(Type);
+      ParamTypes->push_back(std::string(Type));
     if (ParamValues && ParamValues->size() == ParamNumber)
-      ParamValues->push_back(Value);
+      ParamValues->push_back(std::string(Value));
 
     // Unimaginative naming scheme for parameter variables.
     return "Param" + utostr(ParamNumber);
@@ -515,7 +515,7 @@
     VarNameUsed = true;
     return VarName;
   }
-  void setVarname(const StringRef s) { VarName = s; }
+  void setVarname(const StringRef s) { VarName = std::string(s); }
   bool varnameUsed() const { return VarNameUsed; }
 
   // Emit code to generate this result as a Value *.
@@ -714,7 +714,8 @@
   std::vector<Ptr> Args;
   IRIntrinsicResult(StringRef IntrinsicID, std::vector<const Type *> ParamTypes,
                     std::vector<Ptr> Args)
-      : IntrinsicID(IntrinsicID), ParamTypes(ParamTypes), Args(Args) {}
+      : IntrinsicID(std::string(IntrinsicID)), ParamTypes(ParamTypes),
+        Args(Args) {}
   void genCode(raw_ostream &OS,
                CodeGenParamAllocator &ParamAlloc) const override {
     std::string IntNo = ParamAlloc.allocParam(
@@ -866,7 +867,7 @@
     llvm::APInt i = iOrig.trunc(64);
     SmallString<40> s;
     i.toString(s, 16, true, true);
-    return s.str();
+    return std::string(s.str());
   }
 
   std::string genSema() const {
@@ -955,7 +956,7 @@
   // maps stored in this object.
   const VoidType *getVoidType() { return &Void; }
   const ScalarType *getScalarType(StringRef Name) {
-    return ScalarTypes[Name].get();
+    return ScalarTypes[std::string(Name)].get();
   }
   const ScalarType *getScalarType(Record *R) {
     return getScalarType(R->getName());
@@ -1132,7 +1133,7 @@
           getCodeForDag(cast<DagInit>(D->getArg(i)), SubScope, Param);
       StringRef ArgName = D->getArgNameStr(i);
       if (!ArgName.empty())
-        SubScope[ArgName] = V;
+        SubScope[std::string(ArgName)] = V;
       if (PrevV)
         V->setPredecessor(PrevV);
       PrevV = V;
@@ -1190,7 +1191,7 @@
         if (sp->isSubClassOf("IRBuilderAddrParam")) {
           AddressArgs.insert(Index);
         } else if (sp->isSubClassOf("IRBuilderIntParam")) {
-          IntegerArgs[Index] = sp->getValueAsString("type");
+          IntegerArgs[Index] = std::string(sp->getValueAsString("type"));
         }
       }
       return std::make_shared<IRBuilderResult>(Op->getValueAsString("prefix"),
@@ -1199,7 +1200,7 @@
       std::vector<const Type *> ParamTypes;
       for (Record *RParam : Op->getValueAsListOfDefs("params"))
         ParamTypes.push_back(getType(RParam, Param));
-      std::string IntName = Op->getValueAsString("intname");
+      std::string IntName = std::string(Op->getValueAsString("intname"));
       if (Op->getValueAsBit("appendKind"))
         IntName += "_" + toLetter(cast<ScalarType>(Param)->kind());
       return std::make_shared<IRIntrinsicResult>(IntName, ParamTypes, Args);
@@ -1219,7 +1220,7 @@
     if (!isa<UnsetInit>(Arg))
       PrintFatalError(
           "dag operator argument should not have both a value and a name");
-    auto it = Scope.find(Name);
+    auto it = Scope.find(std::string(Name));
     if (it == Scope.end())
       PrintFatalError("unrecognized variable name '" + Name + "'");
     return it->second;
@@ -1274,7 +1275,8 @@
       (R->isSubClassOf("NameOverride") ? R->getValueAsString("basename")
                                        : R->getName());
   StringRef overrideLetter = R->getValueAsString("overrideKindLetter");
-  FullName = (Twine(BaseName) + Param->acleSuffix(overrideLetter)).str();
+  FullName =
+      (Twine(BaseName) + Param->acleSuffix(std::string(overrideLetter))).str();
 
   // Derive the intrinsic's polymorphic name, by removing components from the
   // full name as specified by its 'pnt' member ('polymorphic name type'),
@@ -1364,7 +1366,8 @@
     // into the variable-name scope that the code gen will refer to.
     StringRef ArgName = ArgsDag->getArgNameStr(i);
     if (!ArgName.empty())
-      Scope[ArgName] = ME.getCodeForArg(i, ArgType, Promote, Immediate);
+      Scope[std::string(ArgName)] =
+          ME.getCodeForArg(i, ArgType, Promote, Immediate);
   }
 
   // Finally, go through the codegen dag and translate it into a Result object
@@ -1382,9 +1385,9 @@
       if (Name.empty()) {
         PrintFatalError("Operands to CustomCodegen should have names");
       } else if (auto *II = dyn_cast<IntInit>(CodeDag->getArg(i))) {
-        CustomCodeGenArgs[Name] = itostr(II->getValue());
+        CustomCodeGenArgs[std::string(Name)] = itostr(II->getValue());
       } else if (auto *SI = dyn_cast<StringInit>(CodeDag->getArg(i))) {
-        CustomCodeGenArgs[Name] = SI->getValue();
+        CustomCodeGenArgs[std::string(Name)] = std::string(SI->getValue());
       } else {
         PrintFatalError("Operands to CustomCodegen should be integers");
       }
@@ -1403,7 +1406,7 @@
   // use it for operations such as 'find the unsigned version of this signed
   // integer type'.
   for (Record *R : Records.getAllDerivedDefinitions("PrimitiveType"))
-    ScalarTypes[R->getName()] = std::make_unique<ScalarType>(R);
+    ScalarTypes[std::string(R->getName())] = std::make_unique<ScalarType>(R);
 
   // Now go through the instances of Intrinsic, and for each one, iterate
   // through its list of type parameters making an ACLEIntrinsic for each one.
@@ -1645,12 +1648,12 @@
     const ACLEIntrinsic &Int = *kv.second;
     if (Int.polymorphic()) {
       StringRef Name = Int.shortName();
-      if (ShortNamesSeen.find(Name) == ShortNamesSeen.end()) {
+      if (ShortNamesSeen.find(std::string(Name)) == ShortNamesSeen.end()) {
         OS << "BUILTIN(__builtin_arm_mve_" << Name << ", \"vi.\", \"nt";
         if (Int.nonEvaluating())
           OS << "u"; // indicate that this builtin doesn't evaluate its args
         OS << "\")\n";
-        ShortNamesSeen.insert(Name);
+        ShortNamesSeen.insert(std::string(Name));
       }
     }
   }
diff --git a/clang/utils/TableGen/NeonEmitter.cpp b/clang/utils/TableGen/NeonEmitter.cpp
index a0f3fb2..59ea154 100644
--- a/clang/utils/TableGen/NeonEmitter.cpp
+++ b/clang/utils/TableGen/NeonEmitter.cpp
@@ -1257,7 +1257,7 @@
   if (!getReturnType().isVoid() && !SRet)
     S += "(" + RetVar.getType().str() + ") ";
 
-  S += "__builtin_neon_" + mangleName(N, LocalCK) + "(";
+  S += "__builtin_neon_" + mangleName(std::string(N), LocalCK) + "(";
 
   if (SRet)
     S += "&" + RetVar.getName() + ", ";
@@ -1398,14 +1398,14 @@
   if (DI->getNumArgs() == 2) {
     // Unary op.
     std::pair<Type, std::string> R =
-        emitDagArg(DI->getArg(1), DI->getArgNameStr(1));
+        emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
     return std::make_pair(R.first, Op + R.second);
   } else {
     assert(DI->getNumArgs() == 3 && "Can only handle unary and binary ops!");
     std::pair<Type, std::string> R1 =
-        emitDagArg(DI->getArg(1), DI->getArgNameStr(1));
+        emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
     std::pair<Type, std::string> R2 =
-        emitDagArg(DI->getArg(2), DI->getArgNameStr(2));
+        emitDagArg(DI->getArg(2), std::string(DI->getArgNameStr(2)));
     assert_with_loc(R1.first == R2.first, "Argument type mismatch!");
     return std::make_pair(R1.first, R1.second + " " + Op + " " + R2.second);
   }
@@ -1416,7 +1416,7 @@
   std::vector<std::string> Values;
   for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
     std::pair<Type, std::string> R =
-        emitDagArg(DI->getArg(I + 1), DI->getArgNameStr(I + 1));
+        emitDagArg(DI->getArg(I + 1), std::string(DI->getArgNameStr(I + 1)));
     Types.push_back(R.first);
     Values.push_back(R.second);
   }
@@ -1451,9 +1451,9 @@
 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCast(DagInit *DI,
                                                                 bool IsBitCast){
   // (cast MOD* VAL) -> cast VAL to type given by MOD.
-  std::pair<Type, std::string> R = emitDagArg(
-      DI->getArg(DI->getNumArgs() - 1),
-      DI->getArgNameStr(DI->getNumArgs() - 1));
+  std::pair<Type, std::string> R =
+      emitDagArg(DI->getArg(DI->getNumArgs() - 1),
+                 std::string(DI->getArgNameStr(DI->getNumArgs() - 1)));
   Type castToType = R.first;
   for (unsigned ArgIdx = 0; ArgIdx < DI->getNumArgs() - 1; ++ArgIdx) {
 
@@ -1465,10 +1465,11 @@
     //   5. The value "H" or "D" to half or double the bitwidth.
     //   6. The value "8" to convert to 8-bit (signed) integer lanes.
     if (!DI->getArgNameStr(ArgIdx).empty()) {
-      assert_with_loc(Intr.Variables.find(DI->getArgNameStr(ArgIdx)) !=
-                      Intr.Variables.end(),
+      assert_with_loc(Intr.Variables.find(std::string(
+                          DI->getArgNameStr(ArgIdx))) != Intr.Variables.end(),
                       "Variable not found");
-      castToType = Intr.Variables[DI->getArgNameStr(ArgIdx)].getType();
+      castToType =
+          Intr.Variables[std::string(DI->getArgNameStr(ArgIdx))].getType();
     } else {
       StringInit *SI = dyn_cast<StringInit>(DI->getArg(ArgIdx));
       assert_with_loc(SI, "Expected string type or $Name for cast type");
@@ -1583,9 +1584,9 @@
 
   // (shuffle arg1, arg2, sequence)
   std::pair<Type, std::string> Arg1 =
-      emitDagArg(DI->getArg(0), DI->getArgNameStr(0));
+      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
   std::pair<Type, std::string> Arg2 =
-      emitDagArg(DI->getArg(1), DI->getArgNameStr(1));
+      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
   assert_with_loc(Arg1.first == Arg2.first,
                   "Different types in arguments to shuffle!");
 
@@ -1627,8 +1628,8 @@
 
 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDup(DagInit *DI) {
   assert_with_loc(DI->getNumArgs() == 1, "dup() expects one argument");
-  std::pair<Type, std::string> A = emitDagArg(DI->getArg(0),
-                                              DI->getArgNameStr(0));
+  std::pair<Type, std::string> A =
+      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
   assert_with_loc(A.first.isScalar(), "dup() expects a scalar argument");
 
   Type T = Intr.getBaseType();
@@ -1646,10 +1647,10 @@
 
 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDupTyped(DagInit *DI) {
   assert_with_loc(DI->getNumArgs() == 2, "dup_typed() expects two arguments");
-  std::pair<Type, std::string> A = emitDagArg(DI->getArg(0),
-                                              DI->getArgNameStr(0));
-  std::pair<Type, std::string> B = emitDagArg(DI->getArg(1),
-                                              DI->getArgNameStr(1));
+  std::pair<Type, std::string> A =
+      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
+  std::pair<Type, std::string> B =
+      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
   assert_with_loc(B.first.isScalar(),
                   "dup_typed() requires a scalar as the second argument");
 
@@ -1668,10 +1669,10 @@
 
 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSplat(DagInit *DI) {
   assert_with_loc(DI->getNumArgs() == 2, "splat() expects two arguments");
-  std::pair<Type, std::string> A = emitDagArg(DI->getArg(0),
-                                              DI->getArgNameStr(0));
-  std::pair<Type, std::string> B = emitDagArg(DI->getArg(1),
-                                              DI->getArgNameStr(1));
+  std::pair<Type, std::string> A =
+      emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
+  std::pair<Type, std::string> B =
+      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
 
   assert_with_loc(B.first.isScalar(),
                   "splat() requires a scalar int as the second argument");
@@ -1687,13 +1688,13 @@
 
 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSaveTemp(DagInit *DI) {
   assert_with_loc(DI->getNumArgs() == 2, "save_temp() expects two arguments");
-  std::pair<Type, std::string> A = emitDagArg(DI->getArg(1),
-                                              DI->getArgNameStr(1));
+  std::pair<Type, std::string> A =
+      emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
 
   assert_with_loc(!A.first.isVoid(),
                   "Argument to save_temp() must have non-void type!");
 
-  std::string N = DI->getArgNameStr(0);
+  std::string N = std::string(DI->getArgNameStr(0));
   assert_with_loc(!N.empty(),
                   "save_temp() expects a name as the first argument");
 
@@ -1883,13 +1884,13 @@
 
 void NeonEmitter::createIntrinsic(Record *R,
                                   SmallVectorImpl<Intrinsic *> &Out) {
-  std::string Name = R->getValueAsString("Name");
-  std::string Proto = R->getValueAsString("Prototype");
-  std::string Types = R->getValueAsString("Types");
+  std::string Name = std::string(R->getValueAsString("Name"));
+  std::string Proto = std::string(R->getValueAsString("Prototype"));
+  std::string Types = std::string(R->getValueAsString("Types"));
   Record *OperationRec = R->getValueAsDef("Operation");
   bool CartesianProductOfTypes = R->getValueAsBit("CartesianProductOfTypes");
   bool BigEndianSafe  = R->getValueAsBit("BigEndianSafe");
-  std::string Guard = R->getValueAsString("ArchGuard");
+  std::string Guard = std::string(R->getValueAsString("ArchGuard"));
   bool IsUnavailable = OperationRec->getValueAsBit("Unavailable");
 
   // Set the global current record. This allows assert_with_loc to produce