Introduce a string_ostream string builder facilty
authorAlp Toker <alp@nuanti.com>
Thu, 26 Jun 2014 00:00:48 +0000 (00:00 +0000)
committerAlp Toker <alp@nuanti.com>
Thu, 26 Jun 2014 00:00:48 +0000 (00:00 +0000)
string_ostream is a safe and efficient string builder that combines opaque
stack storage with a built-in ostream interface.

small_string_ostream<bytes> additionally permits an explicit stack storage size
other than the default 128 bytes to be provided. Beyond that, storage is
transferred to the heap.

This convenient class can be used in most places an
std::string+raw_string_ostream pair or SmallString<>+raw_svector_ostream pair
would previously have been used, in order to guarantee consistent access
without byte truncation.

The patch also converts much of LLVM to use the new facility. These changes
include several probable bug fixes for truncated output, a programming error
that's no longer possible with the new interface.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@211749 91177308-0d34-0410-b5e6-96231b3b80d8

57 files changed:
include/llvm/Analysis/CFGPrinter.h
include/llvm/ExecutionEngine/ObjectBuffer.h
include/llvm/Support/GraphWriter.h
include/llvm/Support/YAMLTraits.h
include/llvm/Support/raw_ostream.h
include/llvm/TableGen/StringToOffsetTable.h
lib/Analysis/Analysis.cpp
lib/Analysis/BlockFrequencyInfo.cpp
lib/Analysis/Lint.cpp
lib/AsmParser/LLParser.cpp
lib/CodeGen/AsmPrinter/AsmPrinter.cpp
lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp
lib/CodeGen/MachineBlockFrequencyInfo.cpp
lib/CodeGen/MachineBlockPlacement.cpp
lib/CodeGen/MachineFunction.cpp
lib/CodeGen/MachineScheduler.cpp
lib/CodeGen/ScheduleDAGInstrs.cpp
lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
lib/CodeGen/TargetSchedule.cpp
lib/DebugInfo/DWARFDebugFrame.cpp
lib/IR/Core.cpp
lib/IR/DataLayout.cpp
lib/IR/LLVMContext.cpp
lib/IRReader/IRReader.cpp
lib/LTO/LTOCodeGenerator.cpp
lib/MC/MCAsmStreamer.cpp
lib/MC/MCContext.cpp
lib/MC/MCDisassembler/Disassembler.cpp
lib/MC/MCDwarf.cpp
lib/MC/MCParser/AsmParser.cpp
lib/Object/MachOObjectFile.cpp
lib/Option/Arg.cpp
lib/Support/CommandLine.cpp
lib/Support/raw_ostream.cpp
lib/TableGen/SetTheory.cpp
lib/TableGen/TGParser.cpp
lib/Target/NVPTX/NVPTXAsmPrinter.cpp
lib/Target/TargetMachineC.cpp
lib/Target/X86/AsmParser/X86AsmParser.cpp
lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
lib/Target/X86/X86AsmPrinter.cpp
lib/Target/XCore/XCoreAsmPrinter.cpp
lib/Transforms/Instrumentation/DebugIR.cpp
lib/Transforms/Instrumentation/GCOVProfiling.cpp
lib/Transforms/Instrumentation/MemorySanitizer.cpp
lib/Transforms/ObjCARC/ObjCARCOpts.cpp
lib/Transforms/Utils/ASanStackFrameLayout.cpp
lib/Transforms/Vectorize/LoopVectorize.cpp
tools/llvm-ar/llvm-ar.cpp
tools/llvm-objdump/llvm-objdump.cpp
tools/llvm-readobj/ARMWinEHPrinter.cpp
tools/llvm-readobj/Win64EHDumper.cpp
unittests/ExecutionEngine/JIT/JITTest.cpp
utils/FileCheck/FileCheck.cpp
utils/TableGen/CodeEmitterGen.cpp
utils/yaml-bench/YAMLBench.cpp

index e6d2ed1a68647383b916174e0b6d6d29008aaec2..759afcaee13277bb2ec8f8590e31ef737e1703db 100644 (file)
@@ -36,9 +36,7 @@ struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits {
     if (!Node->getName().empty())
       return Node->getName().str();
 
     if (!Node->getName().empty())
       return Node->getName().str();
 
-    std::string Str;
-    raw_string_ostream OS(Str);
-
+    string_ostream OS;
     Node->printAsOperand(OS, false);
     return OS.str();
   }
     Node->printAsOperand(OS, false);
     return OS.str();
   }
@@ -46,8 +44,7 @@ struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits {
   static std::string getCompleteNodeLabel(const BasicBlock *Node,
                                           const Function *) {
     enum { MaxColumns = 80 };
   static std::string getCompleteNodeLabel(const BasicBlock *Node,
                                           const Function *) {
     enum { MaxColumns = 80 };
-    std::string Str;
-    raw_string_ostream OS(Str);
+    string_ostream OS;
 
     if (Node->getName().empty()) {
       Node->printAsOperand(OS, false);
 
     if (Node->getName().empty()) {
       Node->printAsOperand(OS, false);
@@ -109,8 +106,7 @@ struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits {
 
       if (SuccNo == 0) return "def";
 
 
       if (SuccNo == 0) return "def";
 
-      std::string Str;
-      raw_string_ostream OS(Str);
+      string_ostream OS;
       SwitchInst::ConstCaseIt Case =
           SwitchInst::ConstCaseIt::fromSuccessorIndex(SI, SuccNo);
       OS << Case.getCaseValue()->getValue();
       SwitchInst::ConstCaseIt Case =
           SwitchInst::ConstCaseIt::fromSuccessorIndex(SI, SuccNo);
       OS << Case.getCaseValue()->getValue();
index 071a42b6b76843015dd0f937a0c3955863fc7d71..81dc88dcd01a1524e67abd9c47d4ce1d9473cce5 100644 (file)
@@ -58,23 +58,18 @@ protected:
 class ObjectBufferStream : public ObjectBuffer {
   void anchor() override;
 public:
 class ObjectBufferStream : public ObjectBuffer {
   void anchor() override;
 public:
-  ObjectBufferStream() : OS(SV) {}
+  ObjectBufferStream() {}
   virtual ~ObjectBufferStream() {}
 
   raw_ostream &getOStream() { return OS; }
   void flush()
   {
   virtual ~ObjectBufferStream() {}
 
   raw_ostream &getOStream() { return OS; }
   void flush()
   {
-    OS.flush();
-
     // Make the data accessible via the ObjectBuffer::Buffer
     // Make the data accessible via the ObjectBuffer::Buffer
-    Buffer.reset(MemoryBuffer::getMemBuffer(StringRef(SV.data(), SV.size()),
-                                            "",
-                                            false));
+    Buffer.reset(MemoryBuffer::getMemBuffer(OS.str(), "", false));
   }
 
 protected:
   }
 
 protected:
-  SmallVector<char, 4096> SV; // Working buffer into which we JIT.
-  raw_svector_ostream     OS; // streaming wrapper
+  small_string_ostream<4096> OS; // Working buffer into which we JIT.
 };
 
 } // namespace llvm
 };
 
 } // namespace llvm
index 2f02aa7a1c19ade821014e0a78f2cbc748572f09..a6bd1afa16322c396dbe7a00f14bab5dc8ecab80 100644 (file)
@@ -184,8 +184,7 @@ public:
         O << "|" << DOT::EscapeString(NodeDesc);
     }
 
         O << "|" << DOT::EscapeString(NodeDesc);
     }
 
-    std::string edgeSourceLabels;
-    raw_string_ostream EdgeSourceLabels(edgeSourceLabels);
+    string_ostream EdgeSourceLabels;
     bool hasEdgeSourceLabels = getEdgeSourceLabels(EdgeSourceLabels, Node);
 
     if (hasEdgeSourceLabels) {
     bool hasEdgeSourceLabels = getEdgeSourceLabels(EdgeSourceLabels, Node);
 
     if (hasEdgeSourceLabels) {
index a23faf65bb596f8f873b60d4e304d49a1b7b2086..14ca2db9326e3a95224ad9aea5a9221fcfef4c7f 100644 (file)
@@ -612,8 +612,7 @@ template<typename T>
 typename std::enable_if<has_ScalarTraits<T>::value,void>::type
 yamlize(IO &io, T &Val, bool) {
   if ( io.outputting() ) {
 typename std::enable_if<has_ScalarTraits<T>::value,void>::type
 yamlize(IO &io, T &Val, bool) {
   if ( io.outputting() ) {
-    std::string Storage;
-    llvm::raw_string_ostream Buffer(Storage);
+    llvm::string_ostream Buffer;
     ScalarTraits<T>::output(Val, io.getContext(), Buffer);
     StringRef Str = Buffer.str();
     io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
     ScalarTraits<T>::output(Val, io.getContext(), Buffer);
     StringRef Str = Buffer.str();
     io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
index 34fbe082cda804178647039e0d00b9c30f6bd048..77e473f2f6f03c353ff049edaa270309217c1bcf 100644 (file)
@@ -15,6 +15,7 @@
 #define LLVM_SUPPORT_RAW_OSTREAM_H
 
 #include "llvm/ADT/StringRef.h"
 #define LLVM_SUPPORT_RAW_OSTREAM_H
 
 #include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/DataTypes.h"
 
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/DataTypes.h"
 
@@ -461,6 +462,14 @@ class raw_svector_ostream : public raw_ostream {
   /// current_pos - Return the current position within the stream, not
   /// counting the bytes currently in the buffer.
   uint64_t current_pos() const override;
   /// current_pos - Return the current position within the stream, not
   /// counting the bytes currently in the buffer.
   uint64_t current_pos() const override;
+
+protected:
+  // This constructor is specified not to access \p O provided for storage as it
+  // may not yet be initialized at construction time.
+  explicit raw_svector_ostream(SmallVectorImpl<char> &O, std::nullptr_t)
+      : OS(O){};
+  void init();
+
 public:
   /// Construct a new raw_svector_ostream.
   ///
 public:
   /// Construct a new raw_svector_ostream.
   ///
@@ -493,6 +502,25 @@ public:
   ~raw_null_ostream();
 };
 
   ~raw_null_ostream();
 };
 
+/// string_ostream - A raw_ostream that builds a string.  This is a
+/// raw_svector_ostream with storage.
+template <unsigned InternalLen>
+class small_string_ostream : public raw_svector_ostream {
+  SmallVector<char, InternalLen> Buffer;
+  // There's no need to flush explicitly.
+  using raw_svector_ostream::flush;
+
+public:
+  small_string_ostream() : raw_svector_ostream(Buffer, nullptr) { init(); }
+
+  void clear() {
+    flush();
+    Buffer.clear();
+  }
+};
+
+typedef small_string_ostream<128> string_ostream;
+
 } // end llvm namespace
 
 #endif
 } // end llvm namespace
 
 #endif
index c924bd8ec57df304a7cb6e8ae6528c111dc1dfe5..01829a10b2ef07477f0c1e6ce1baed15df70b644 100644 (file)
@@ -42,8 +42,8 @@ public:
 
   void EmitString(raw_ostream &O) {
     // Escape the string.
 
   void EmitString(raw_ostream &O) {
     // Escape the string.
-    SmallString<256> Str;
-    raw_svector_ostream(Str).write_escaped(AggregateString);
+    small_string_ostream<256> Str;
+    Str.write_escaped(AggregateString);
     AggregateString = Str.str();
 
     O << "    \"";
     AggregateString = Str.str();
 
     O << "    \"";
index ade940a7d300c9cca8689dd43e3f6f5aeaafed46..7b6397679d76ae86f48fb285ec193a97d6aa7bcf 100644 (file)
@@ -75,8 +75,7 @@ void LLVMInitializeAnalysis(LLVMPassRegistryRef R) {
 LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action,
                           char **OutMessages) {
   raw_ostream *DebugOS = Action != LLVMReturnStatusAction ? &errs() : nullptr;
 LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action,
                           char **OutMessages) {
   raw_ostream *DebugOS = Action != LLVMReturnStatusAction ? &errs() : nullptr;
-  std::string Messages;
-  raw_string_ostream MsgsOS(Messages);
+  string_ostream MsgsOS;
 
   LLVMBool Result = verifyModule(*unwrap(M), OutMessages ? &MsgsOS : DebugOS);
 
 
   LLVMBool Result = verifyModule(*unwrap(M), OutMessages ? &MsgsOS : DebugOS);
 
@@ -88,7 +87,7 @@ LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action,
     report_fatal_error("Broken module found, compilation aborted!");
 
   if (OutMessages)
     report_fatal_error("Broken module found, compilation aborted!");
 
   if (OutMessages)
-    *OutMessages = strdup(MsgsOS.str().c_str());
+    *OutMessages = strndup(MsgsOS.str().data(), MsgsOS.str().size());
 
   return Result;
 }
 
   return Result;
 }
index 8ed8e3e4c2e01dca2cecdce7a6db7e9736da53b9..7e702c31435bcf2a9bdfadfe66886fa21b775d6e 100644 (file)
@@ -82,10 +82,9 @@ struct DOTGraphTraits<BlockFrequencyInfo*> : public DefaultDOTGraphTraits {
 
   std::string getNodeLabel(const BasicBlock *Node,
                            const BlockFrequencyInfo *Graph) {
 
   std::string getNodeLabel(const BasicBlock *Node,
                            const BlockFrequencyInfo *Graph) {
-    std::string Result;
-    raw_string_ostream OS(Result);
+    string_ostream OS;
 
 
-    OS << Node->getName().str() << ":";
+    OS << Node->getName() << ":";
     switch (ViewBlockFreqPropagationDAG) {
     case GVDT_Fraction:
       Graph->printBlockFreq(OS, Node);
     switch (ViewBlockFreqPropagationDAG) {
     case GVDT_Fraction:
       Graph->printBlockFreq(OS, Node);
@@ -98,7 +97,7 @@ struct DOTGraphTraits<BlockFrequencyInfo*> : public DefaultDOTGraphTraits {
                        "never reach this point.");
     }
 
                        "never reach this point.");
     }
 
-    return Result;
+    return OS.str();
   }
 };
 
   }
 };
 
index b14f3292e90075367cb4db44d38bfbb7b2af6fca..806a1fdee5bdbbec7e83481c758ddeb8c222706c 100644 (file)
@@ -105,11 +105,10 @@ namespace {
     const DataLayout *DL;
     TargetLibraryInfo *TLI;
 
     const DataLayout *DL;
     TargetLibraryInfo *TLI;
 
-    std::string Messages;
-    raw_string_ostream MessagesStr;
+    string_ostream MessagesStr;
 
     static char ID; // Pass identification, replacement for typeid
 
     static char ID; // Pass identification, replacement for typeid
-    Lint() : FunctionPass(ID), MessagesStr(Messages) {
+    Lint() : FunctionPass(ID) {
       initializeLintPass(*PassRegistry::getPassRegistry());
     }
 
       initializeLintPass(*PassRegistry::getPassRegistry());
     }
 
@@ -181,7 +180,7 @@ bool Lint::runOnFunction(Function &F) {
   TLI = &getAnalysis<TargetLibraryInfo>();
   visit(F);
   dbgs() << MessagesStr.str();
   TLI = &getAnalysis<TargetLibraryInfo>();
   visit(F);
   dbgs() << MessagesStr.str();
-  Messages.clear();
+  MessagesStr.clear();
   return false;
 }
 
   return false;
 }
 
index f44420685203c85ae6487d273bd964479af2100f..840f764d3adcad27d2e7ba855756f99caff21b1f 100644 (file)
 using namespace llvm;
 
 static std::string getTypeString(Type *T) {
 using namespace llvm;
 
 static std::string getTypeString(Type *T) {
-  std::string Result;
-  raw_string_ostream Tmp(Result);
-  Tmp << *T;
-  return Tmp.str();
+  string_ostream Result;
+  Result << *T;
+  return Result.str();
 }
 
 /// Run: module ::= toplevelentity*
 }
 
 /// Run: module ::= toplevelentity*
index 799ee92d3ad519075944c1d6ea29811f31cf6117..ebb49c34a73c8139934ba1172f1714ce8c47f4ad 100644 (file)
@@ -1585,8 +1585,7 @@ static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
 
     // Otherwise report the problem to the user.
     {
 
     // Otherwise report the problem to the user.
     {
-      std::string S;
-      raw_string_ostream OS(S);
+      string_ostream OS;
       OS << "Unsupported expression in static initializer: ";
       CE->printAsOperand(OS, /*PrintType=*/false,
                      !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
       OS << "Unsupported expression in static initializer: ";
       CE->printAsOperand(OS, /*PrintType=*/false,
                      !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
index 46ee0c856bda3e5bc1bd0f19c88348e4da20af6f..01f26d0c4ced545c8f2b33688015b0758aa43bb5 100644 (file)
@@ -241,8 +241,7 @@ static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
         }
       }
       if (Error) {
         }
       }
       if (Error) {
-        std::string msg;
-        raw_string_ostream Msg(msg);
+        string_ostream Msg;
         Msg << "invalid operand in inline asm: '" << AsmStr << "'";
         MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
       }
         Msg << "invalid operand in inline asm: '" << AsmStr << "'";
         MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
       }
@@ -413,8 +412,7 @@ static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
           }
         }
         if (Error) {
           }
         }
         if (Error) {
-          std::string msg;
-          raw_string_ostream Msg(msg);
+          string_ostream Msg;
           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
         }
           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
         }
@@ -471,8 +469,7 @@ void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
 
   // Emit the inline asm to a temporary string so we can emit it through
   // EmitInlineAsm.
 
   // Emit the inline asm to a temporary string so we can emit it through
   // EmitInlineAsm.
-  SmallString<256> StringData;
-  raw_svector_ostream OS(StringData);
+  small_string_ostream<256> OS;
 
   // The variant of the current asmprinter.
   int AsmPrinterVariant = MAI->getAssemblerDialect();
 
   // The variant of the current asmprinter.
   int AsmPrinterVariant = MAI->getAssemblerDialect();
@@ -517,8 +514,7 @@ void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
     }
     OS << Counter;
   } else {
     }
     OS << Counter;
   } else {
-    std::string msg;
-    raw_string_ostream Msg(msg);
+    string_ostream Msg;
     Msg << "Unknown special formatter '" << Code
          << "' for machine instr: " << *MI;
     report_fatal_error(Msg.str());
     Msg << "Unknown special formatter '" << Code
          << "' for machine instr: " << *MI;
     report_fatal_error(Msg.str());
index 9151d99089d6b35064f36ecc3a24381e571645f9..35e4a56cec40201ee7da2a27355dbc8ae48a595c 100644 (file)
@@ -89,10 +89,9 @@ struct DOTGraphTraits<MachineBlockFrequencyInfo*> :
 
   std::string getNodeLabel(const MachineBasicBlock *Node,
                            const MachineBlockFrequencyInfo *Graph) {
 
   std::string getNodeLabel(const MachineBasicBlock *Node,
                            const MachineBlockFrequencyInfo *Graph) {
-    std::string Result;
-    raw_string_ostream OS(Result);
+    string_ostream OS;
 
 
-    OS << Node->getName().str() << ":";
+    OS << Node->getName() << ":";
     switch (ViewMachineBlockFreqPropagationDAG) {
     case GVDT_Fraction:
       Graph->printBlockFreq(OS, Node);
     switch (ViewMachineBlockFreqPropagationDAG) {
     case GVDT_Fraction:
       Graph->printBlockFreq(OS, Node);
@@ -105,7 +104,7 @@ struct DOTGraphTraits<MachineBlockFrequencyInfo*> :
                        "never reach this point.");
     }
 
                        "never reach this point.");
     }
 
-    return Result;
+    return OS.str();
   }
 };
 
   }
 };
 
index 74af1e2d64b02d2acc15c0acb98ca05a4378c2cf..891f605e2a1535eb91db9ceca12d7072b38b20a7 100644 (file)
@@ -264,23 +264,19 @@ INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
 ///
 /// Only used by debug logging.
 static std::string getBlockName(MachineBasicBlock *BB) {
 ///
 /// Only used by debug logging.
 static std::string getBlockName(MachineBasicBlock *BB) {
-  std::string Result;
-  raw_string_ostream OS(Result);
+  string_ostream OS;
   OS << "BB#" << BB->getNumber()
      << " (derived from LLVM BB '" << BB->getName() << "')";
   OS << "BB#" << BB->getNumber()
      << " (derived from LLVM BB '" << BB->getName() << "')";
-  OS.flush();
-  return Result;
+  return OS.str();
 }
 
 /// \brief Helper to print the number of a MBB.
 ///
 /// Only used by debug logging.
 static std::string getBlockNum(MachineBasicBlock *BB) {
 }
 
 /// \brief Helper to print the number of a MBB.
 ///
 /// Only used by debug logging.
 static std::string getBlockNum(MachineBasicBlock *BB) {
-  std::string Result;
-  raw_string_ostream OS(Result);
+  string_ostream OS;
   OS << "BB#" << BB->getNumber();
   OS << "BB#" << BB->getNumber();
-  OS.flush();
-  return Result;
+  return OS.str();
 }
 #endif
 
 }
 #endif
 
index 6138aef4adc193231941317bc94b81aa1e75f269..20210adf30f331e59ad530497f7541dd3fa273c4 100644 (file)
@@ -465,9 +465,8 @@ MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
 
   const char *Prefix = isLinkerPrivate ? DL->getLinkerPrivateGlobalPrefix() :
                                          DL->getPrivateGlobalPrefix();
 
   const char *Prefix = isLinkerPrivate ? DL->getLinkerPrivateGlobalPrefix() :
                                          DL->getPrivateGlobalPrefix();
-  SmallString<60> Name;
-  raw_svector_ostream(Name)
-    << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
+  small_string_ostream<60> Name;
+  Name << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
   return Ctx.GetOrCreateSymbol(Name.str());
 }
 
   return Ctx.GetOrCreateSymbol(Name.str());
 }
 
index 0baf2a6c1c2120ac6d0740cebe69ac897a641988..f7459bbf6fc1aec53692109360ee5601a57465f0 100644 (file)
@@ -3235,8 +3235,7 @@ struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
   }
 
   static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
   }
 
   static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
-    std::string Str;
-    raw_string_ostream SS(Str);
+    string_ostream SS;
     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
index 92a9a30f24c23a927e6da4f703a7ba65d4bfc39a..baf4af6abaa7fc0befe659ecb16833a8320693a0 100644 (file)
@@ -1197,8 +1197,7 @@ void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
 }
 
 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
 }
 
 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
-  std::string s;
-  raw_string_ostream oss(s);
+  string_ostream oss;
   if (SU == &EntrySU)
     oss << "<entry>";
   else if (SU == &ExitSU)
   if (SU == &EntrySU)
     oss << "<entry>";
   else if (SU == &ExitSU)
index 57e22e21c3712454df7673ffab9e4b1b72b36b56..a2cc2908167e322a6b2ba9bf370da5f2b684c8e7 100644 (file)
@@ -3245,8 +3245,7 @@ SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
 
 
 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
 
 
 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
-  std::string msg;
-  raw_string_ostream Msg(msg);
+  string_ostream Msg;
   Msg << "Cannot select: ";
 
   if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
   Msg << "Cannot select: ";
 
   if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
index 4df5ede388fc6aed6269ad3d67fcf025da02bc62..680a7ec5dda00de723deaf2c4c153cbb17296c07 100644 (file)
@@ -268,8 +268,7 @@ void SelectionDAG::setSubgraphColor(SDNode *N, const char *Color) {
 }
 
 std::string ScheduleDAGSDNodes::getGraphNodeLabel(const SUnit *SU) const {
 }
 
 std::string ScheduleDAGSDNodes::getGraphNodeLabel(const SUnit *SU) const {
-  std::string s;
-  raw_string_ostream O(s);
+  string_ostream O;
   O << "SU(" << SU->NodeNum << "): ";
   if (SU->getNode()) {
     SmallVector<SDNode *, 4> GluedNodes;
   O << "SU(" << SU->NodeNum << "): ";
   if (SU->getNode()) {
     SmallVector<SDNode *, 4> GluedNodes;
index b0f2ca68884b973920af2071df9bbb09d2a0a751..d18a514a85e79070941955863601812906037324 100644 (file)
@@ -212,11 +212,10 @@ unsigned TargetSchedModel::computeOperandLatency(
   if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit()
       && !DefMI->getDesc().OpInfo[DefOperIdx].isOptionalDef()
       && SchedModel.isComplete()) {
   if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit()
       && !DefMI->getDesc().OpInfo[DefOperIdx].isOptionalDef()
       && SchedModel.isComplete()) {
-    std::string Err;
-    raw_string_ostream ss(Err);
-    ss << "DefIdx " << DefIdx << " exceeds machine model writes for "
-       << *DefMI;
-    report_fatal_error(ss.str());
+    string_ostream Err;
+    Err << "DefIdx " << DefIdx << " exceeds machine model writes for "
+        << *DefMI;
+    report_fatal_error(Err.str());
   }
 #endif
   // FIXME: Automatically giving all implicit defs defaultDefLatency is
   }
 #endif
   // FIXME: Automatically giving all implicit defs defaultDefLatency is
index a33548e95b0b99a700a72ddc800ea8d010deb65f..2227260bb0d1802923111a17a92a021fc9559553 100644 (file)
@@ -353,10 +353,9 @@ void DWARFDebugFrame::parse(DataExtractor Data) {
     Entries.back()->parseInstructions(Data, &Offset, EndStructureOffset);
 
     if (Offset != EndStructureOffset) {
     Entries.back()->parseInstructions(Data, &Offset, EndStructureOffset);
 
     if (Offset != EndStructureOffset) {
-      std::string Str;
-      raw_string_ostream OS(Str);
-      OS << format("Parsing entry instructions at %lx failed", StartOffset);
-      report_fatal_error(Str);
+      string_ostream Str;
+      Str << format("Parsing entry instructions at %lx failed", StartOffset);
+      report_fatal_error(Str.str());
     }
   }
 }
     }
   }
 }
index 2c49d5b949caa71eb7d96c44ecfd6fb4b895c751..bf936d6dc7e3f5d3bb8644db666cf78cb4b29cc0 100644 (file)
@@ -62,6 +62,11 @@ void LLVMShutdown() {
 
 /*===-- Error handling ----------------------------------------------------===*/
 
 
 /*===-- Error handling ----------------------------------------------------===*/
 
+static char *LLVMCreateMessage(StringRef Message) {
+  assert(Message.find('\0') == Message.npos);
+  return strndup(Message.data(), Message.size());
+}
+
 char *LLVMCreateMessage(const char *Message) {
   return strdup(Message);
 }
 char *LLVMCreateMessage(const char *Message) {
   return strdup(Message);
 }
@@ -110,14 +115,10 @@ unsigned LLVMGetMDKindID(const char* Name, unsigned SLen) {
 }
 
 char *LLVMGetDiagInfoDescription(LLVMDiagnosticInfoRef DI) {
 }
 
 char *LLVMGetDiagInfoDescription(LLVMDiagnosticInfoRef DI) {
-  std::string MsgStorage;
-  raw_string_ostream Stream(MsgStorage);
-  DiagnosticPrinterRawOStream DP(Stream);
-
+  string_ostream Msg;
+  DiagnosticPrinterRawOStream DP(Msg);
   unwrap(DI)->print(DP);
   unwrap(DI)->print(DP);
-  Stream.flush();
-
-  return LLVMCreateMessage(MsgStorage.c_str());
+  return LLVMCreateMessage(Msg.str());
 }
 
 LLVMDiagnosticSeverity LLVMGetDiagInfoSeverity(LLVMDiagnosticInfoRef DI){
 }
 
 LLVMDiagnosticSeverity LLVMGetDiagInfoSeverity(LLVMDiagnosticInfoRef DI){
@@ -201,13 +202,9 @@ LLVMBool LLVMPrintModuleToFile(LLVMModuleRef M, const char *Filename,
 }
 
 char *LLVMPrintModuleToString(LLVMModuleRef M) {
 }
 
 char *LLVMPrintModuleToString(LLVMModuleRef M) {
-  std::string buf;
-  raw_string_ostream os(buf);
-
+  string_ostream os;
   unwrap(M)->print(os, nullptr);
   unwrap(M)->print(os, nullptr);
-  os.flush();
-
-  return strdup(buf.c_str());
+  return LLVMCreateMessage(os.str());
 }
 
 /*--.. Operations on inline assembler ......................................--*/
 }
 
 /*--.. Operations on inline assembler ......................................--*/
@@ -278,17 +275,14 @@ void LLVMDumpType(LLVMTypeRef Ty) {
 }
 
 char *LLVMPrintTypeToString(LLVMTypeRef Ty) {
 }
 
 char *LLVMPrintTypeToString(LLVMTypeRef Ty) {
-  std::string buf;
-  raw_string_ostream os(buf);
+  string_ostream os;
 
   if (unwrap(Ty))
     unwrap(Ty)->print(os);
   else
     os << "Printing <null> Type";
 
 
   if (unwrap(Ty))
     unwrap(Ty)->print(os);
   else
     os << "Printing <null> Type";
 
-  os.flush();
-
-  return strdup(buf.c_str());
+  return strndup(os.str().data(), os.str().size());
 }
 
 /*--.. Operations on integer types .........................................--*/
 }
 
 /*--.. Operations on integer types .........................................--*/
@@ -532,17 +526,14 @@ void LLVMDumpValue(LLVMValueRef Val) {
 }
 
 char* LLVMPrintValueToString(LLVMValueRef Val) {
 }
 
 char* LLVMPrintValueToString(LLVMValueRef Val) {
-  std::string buf;
-  raw_string_ostream os(buf);
+  string_ostream os;
 
   if (unwrap(Val))
     unwrap(Val)->print(os);
   else
     os << "Printing <null> Value";
 
 
   if (unwrap(Val))
     unwrap(Val)->print(os);
   else
     os << "Printing <null> Value";
 
-  os.flush();
-
-  return strdup(buf.c_str());
+  return strndup(os.str().data(), os.str().size());
 }
 
 void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal) {
 }
 
 void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal) {
index dea05fbef4ab426756b06805a643078341c6124c..3aa775097dfd0c5399842ab296cc93b9c308c3d6 100644 (file)
@@ -519,8 +519,7 @@ const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
 }
 
 std::string DataLayout::getStringRepresentation() const {
 }
 
 std::string DataLayout::getStringRepresentation() const {
-  std::string Result;
-  raw_string_ostream OS(Result);
+  string_ostream OS;
 
   OS << (LittleEndian ? "e" : "E");
 
 
   OS << (LittleEndian ? "e" : "E");
 
index de825f00b207cf8e0f74496000442bcc7955908a..201b278285ccb674260ef64504a553f04ae3c05d 100644 (file)
@@ -164,23 +164,22 @@ void LLVMContext::diagnose(const DiagnosticInfo &DI) {
   }
 
   // Otherwise, print the message with a prefix based on the severity.
   }
 
   // Otherwise, print the message with a prefix based on the severity.
-  std::string MsgStorage;
-  raw_string_ostream Stream(MsgStorage);
-  DiagnosticPrinterRawOStream DP(Stream);
+  string_ostream Msg;
+  DiagnosticPrinterRawOStream DP(Msg);
   DI.print(DP);
   DI.print(DP);
-  Stream.flush();
+
   switch (DI.getSeverity()) {
   case DS_Error:
   switch (DI.getSeverity()) {
   case DS_Error:
-    errs() << "error: " << MsgStorage << "\n";
+    errs() << "error: " << Msg.str() << "\n";
     exit(1);
   case DS_Warning:
     exit(1);
   case DS_Warning:
-    errs() << "warning: " << MsgStorage << "\n";
+    errs() << "warning: " << Msg.str() << "\n";
     break;
   case DS_Remark:
     break;
   case DS_Remark:
-    errs() << "remark: " << MsgStorage << "\n";
+    errs() << "remark: " << Msg.str() << "\n";
     break;
   case DS_Note:
     break;
   case DS_Note:
-    errs() << "note: " << MsgStorage << "\n";
+    errs() << "note: " << Msg.str() << "\n";
     break;
   }
 }
     break;
   }
 }
index 01aa074abad62f33af2a022cf6a938cf58709eb4..6d389d4dc4571ad22995a8195a113ee67919cdcc 100644 (file)
@@ -108,13 +108,9 @@ LLVMBool LLVMParseIRInContext(LLVMContextRef ContextRef,
 
   if(!*OutM) {
     if (OutMessage) {
 
   if(!*OutM) {
     if (OutMessage) {
-      std::string buf;
-      raw_string_ostream os(buf);
-
+      string_ostream os;
       Diag.print(nullptr, os, false);
       Diag.print(nullptr, os, false);
-      os.flush();
-
-      *OutMessage = strdup(buf.c_str());
+      *OutMessage = strndup(os.str().data(), os.str().size());
     }
     return 1;
   }
     }
     return 1;
   }
index a1709f60fff219adac9c949ac2b79b936ab3ab5d..d87299b5c783ce6f70e42b34cc07570e597ebfaf 100644 (file)
@@ -549,16 +549,17 @@ void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
     break;
   }
   // Create the string that will be reported to the external diagnostic handler.
     break;
   }
   // Create the string that will be reported to the external diagnostic handler.
-  std::string MsgStorage;
-  raw_string_ostream Stream(MsgStorage);
-  DiagnosticPrinterRawOStream DP(Stream);
+  string_ostream Msg;
+  DiagnosticPrinterRawOStream DP(Msg);
   DI.print(DP);
   DI.print(DP);
-  Stream.flush();
+
+  // Null-terminate the C string.
+  Msg << '\0';
 
   // If this method has been called it means someone has set up an external
   // diagnostic handler. Assert on that.
   assert(DiagHandler && "Invalid diagnostic handler");
 
   // If this method has been called it means someone has set up an external
   // diagnostic handler. Assert on that.
   assert(DiagHandler && "Invalid diagnostic handler");
-  (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
+  (*DiagHandler)(Severity, Msg.str().data(), DiagContext);
 }
 
 void
 }
 
 void
index da235ec1d330ca9d6cc1a2aa2dd45db7209b08f2..a3a81a6bc71d5bc6ed03e29d4073cb53f98f7aa2 100644 (file)
@@ -1175,9 +1175,10 @@ void MCAsmStreamer::AddEncodingComment(const MCInst &Inst,
   raw_ostream &OS = GetCommentOS();
   SmallString<256> Code;
   SmallVector<MCFixup, 4> Fixups;
   raw_ostream &OS = GetCommentOS();
   SmallString<256> Code;
   SmallVector<MCFixup, 4> Fixups;
-  raw_svector_ostream VecOS(Code);
-  Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
-  VecOS.flush();
+  {
+    raw_svector_ostream VecOS(Code);
+    Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
+  }
 
   // If we are showing fixups, create symbolic markers in the encoded
   // representation. We do this by making a per-bit map to the fixup item index,
 
   // If we are showing fixups, create symbolic markers in the encoded
   // representation. We do this by making a per-bit map to the fixup item index,
index bd2c4e960ac475b56139617c87ba2db0f615b69f..3a8cfaa947a1dbd0356f288ba0274989c63b4ff5 100644 (file)
@@ -140,17 +140,15 @@ MCSymbol *MCContext::GetOrCreateSymbol(const Twine &Name) {
 }
 
 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
 }
 
 MCSymbol *MCContext::CreateLinkerPrivateTempSymbol() {
-  SmallString<128> NameSV;
-  raw_svector_ostream(NameSV)
-    << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
-  return CreateSymbol(NameSV);
+  small_string_ostream<128> NameSV;
+  NameSV << MAI->getLinkerPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
+  return CreateSymbol(NameSV.str());
 }
 
 MCSymbol *MCContext::CreateTempSymbol() {
 }
 
 MCSymbol *MCContext::CreateTempSymbol() {
-  SmallString<128> NameSV;
-  raw_svector_ostream(NameSV)
-    << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
-  return CreateSymbol(NameSV);
+  small_string_ostream<128> NameSV;
+  NameSV << MAI->getPrivateGlobalPrefix() << "tmp" << NextUniqueID++;
+  return CreateSymbol(NameSV.str());
 }
 
 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
 }
 
 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
index 0530c26369c826114e852f8fd43b8c47a78291b4..e3ec4eb30db54e866a5ecc2da217146852ac0402 100644 (file)
@@ -270,8 +270,7 @@ size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
   const MCDisassembler *DisAsm = DC->getDisAsm();
   MCInstPrinter *IP = DC->getIP();
   MCDisassembler::DecodeStatus S;
   const MCDisassembler *DisAsm = DC->getDisAsm();
   MCInstPrinter *IP = DC->getIP();
   MCDisassembler::DecodeStatus S;
-  SmallVector<char, 64> InsnStr;
-  raw_svector_ostream Annotations(InsnStr);
+  small_string_ostream<64> Annotations;
   S = DisAsm->getInstruction(Inst, Size, MemoryObject, PC,
                              /*REMOVE*/ nulls(), Annotations);
   switch (S) {
   S = DisAsm->getInstruction(Inst, Size, MemoryObject, PC,
                              /*REMOVE*/ nulls(), Annotations);
   switch (S) {
@@ -281,13 +280,10 @@ size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
     return 0;
 
   case MCDisassembler::Success: {
     return 0;
 
   case MCDisassembler::Success: {
-    Annotations.flush();
-    StringRef AnnotationsStr = Annotations.str();
-
     SmallVector<char, 64> InsnStr;
     raw_svector_ostream OS(InsnStr);
     formatted_raw_ostream FormattedOS(OS);
     SmallVector<char, 64> InsnStr;
     raw_svector_ostream OS(InsnStr);
     formatted_raw_ostream FormattedOS(OS);
-    IP->printInst(&Inst, FormattedOS, AnnotationsStr);
+    IP->printInst(&Inst, FormattedOS, Annotations.str());
 
     if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
       emitLatency(DC, Inst);
 
     if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
       emitLatency(DC, Inst);
index bddbf578d806853e58379bb23cb904ce3985057d..eab4d88f253bcb9fbe8655696c3ae8e7bd2f25be 100644 (file)
@@ -420,8 +420,7 @@ unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
                            uint64_t AddrDelta) {
   MCContext &Context = MCOS->getContext();
 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
                            uint64_t AddrDelta) {
   MCContext &Context = MCOS->getContext();
-  SmallString<256> Tmp;
-  raw_svector_ostream OS(Tmp);
+  small_string_ostream<256> OS;
   MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
   MCOS->EmitBytes(OS.str());
 }
   MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
   MCOS->EmitBytes(OS.str());
 }
@@ -1647,8 +1646,7 @@ void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
                                          uint64_t AddrDelta) {
   MCContext &Context = Streamer.getContext();
 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
                                          uint64_t AddrDelta) {
   MCContext &Context = Streamer.getContext();
-  SmallString<256> Tmp;
-  raw_svector_ostream OS(Tmp);
+  small_string_ostream<256> OS;
   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
   Streamer.EmitBytes(OS.str());
 }
   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
   Streamer.EmitBytes(OS.str());
 }
index fa5dfdc9fed6b75cf948eed1efce5f6dfe756755..7bfbbf4932bd4e1c9fc935623df37503b818f68f 100644 (file)
@@ -4580,8 +4580,7 @@ bool AsmParser::parseMSInlineAsm(
   }
 
   // Build the IR assembly string.
   }
 
   // Build the IR assembly string.
-  std::string AsmStringIR;
-  raw_string_ostream OS(AsmStringIR);
+  string_ostream OS;
   const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
   const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
   array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
   const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
   const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
   array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
@@ -4646,8 +4645,7 @@ bool AsmParser::parseMSInlineAsm(
     }
     case AOK_DotOperator:
       // Insert the dot if the user omitted it.
     }
     case AOK_DotOperator:
       // Insert the dot if the user omitted it.
-      OS.flush();
-      if (AsmStringIR.back() != '.')
+      if (OS.str().back() != '.')
         OS << '.';
       OS << AR.Val;
       break;
         OS << '.';
       OS << AR.Val;
       break;
index dbfc07270a642afb3d40aa75c45f024448e0244d..2511a4a3faa0d81450b056ad3076b2665f5a83e3 100644 (file)
@@ -301,7 +301,7 @@ static unsigned getCPUType(const MachOObjectFile *O) {
 
 static void printRelocationTargetName(const MachOObjectFile *O,
                                       const MachO::any_relocation_info &RE,
 
 static void printRelocationTargetName(const MachOObjectFile *O,
                                       const MachO::any_relocation_info &RE,
-                                      raw_string_ostream &fmt) {
+                                      raw_ostream &fmt) {
   bool IsScattered = O->isRelocationScattered(RE);
 
   // Target of a scattered relocation is an address.  In the interest of
   bool IsScattered = O->isRelocationScattered(RE);
 
   // Target of a scattered relocation is an address.  In the interest of
@@ -1010,8 +1010,7 @@ MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
 
   unsigned Arch = this->getArch();
 
 
   unsigned Arch = this->getArch();
 
-  std::string fmtbuf;
-  raw_string_ostream fmt(fmtbuf);
+  string_ostream fmt;
   unsigned Type = this->getAnyRelocationType(RE);
   bool IsPCRel = this->getAnyRelocationPCRel(RE);
 
   unsigned Type = this->getAnyRelocationType(RE);
   bool IsPCRel = this->getAnyRelocationPCRel(RE);
 
@@ -1174,7 +1173,7 @@ MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
   } else
     printRelocationTargetName(this, RE, fmt);
 
   } else
     printRelocationTargetName(this, RE, fmt);
 
-  fmt.flush();
+  StringRef fmtbuf = fmt.str();
   Result.append(fmtbuf.begin(), fmtbuf.end());
   return object_error::success;
 }
   Result.append(fmtbuf.begin(), fmtbuf.end());
   return object_error::success;
 }
index 4c8da58f53689de0cc3347c04292ea54653097f2..30a69229737cdf4ed30b8b39beba18f1e564d5ae 100644 (file)
@@ -62,8 +62,7 @@ void Arg::dump() const {
 }
 
 std::string Arg::getAsString(const ArgList &Args) const {
 }
 
 std::string Arg::getAsString(const ArgList &Args) const {
-  SmallString<256> Res;
-  llvm::raw_svector_ostream OS(Res);
+  small_string_ostream<256> OS;
 
   ArgStringList ASL;
   render(Args, ASL);
 
   ArgStringList ASL;
   render(Args, ASL);
@@ -95,8 +94,7 @@ void Arg::render(const ArgList &Args, ArgStringList &Output) const {
     break;
 
   case Option::RenderCommaJoinedStyle: {
     break;
 
   case Option::RenderCommaJoinedStyle: {
-    SmallString<256> Res;
-    llvm::raw_svector_ostream OS(Res);
+    small_string_ostream<256> OS;
     OS << getSpelling();
     for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
       if (i) OS << ',';
     OS << getSpelling();
     for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
       if (i) OS << ',';
index c2b739fa736004ca4872efa29c99aa65c4cec9c8..e28e1d17638214ef9c76ce988e3d6dafee75ee04 100644 (file)
@@ -1342,25 +1342,21 @@ printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
 
 // printOptionDiff - Specializations for printing basic value types.
 //
 
 // printOptionDiff - Specializations for printing basic value types.
 //
-#define PRINT_OPT_DIFF(T)                                               \
-  void parser<T>::                                                      \
-  printOptionDiff(const Option &O, T V, OptionValue<T> D,               \
-                  size_t GlobalWidth) const {                           \
-    printOptionName(O, GlobalWidth);                                    \
-    std::string Str;                                                    \
-    {                                                                   \
-      raw_string_ostream SS(Str);                                       \
-      SS << V;                                                          \
-    }                                                                   \
-    outs() << "= " << Str;                                              \
-    size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
-    outs().indent(NumSpaces) << " (default: ";                          \
-    if (D.hasValue())                                                   \
-      outs() << D.getValue();                                           \
-    else                                                                \
-      outs() << "*no default*";                                         \
-    outs() << ")\n";                                                    \
-  }                                                                     \
+#define PRINT_OPT_DIFF(T)                                                      \
+  void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
+                                  size_t GlobalWidth) const {                  \
+    printOptionName(O, GlobalWidth);                                           \
+    string_ostream SS;                                                         \
+    SS << V;                                                                   \
+    outs() << "= " << SS.str();                                                \
+    size_t NumSpaces = MaxOptWidth > SS.tell() ? MaxOptWidth - SS.tell() : 0;  \
+    outs().indent(NumSpaces) << " (default: ";                                 \
+    if (D.hasValue())                                                          \
+      outs() << D.getValue();                                                  \
+    else                                                                       \
+      outs() << "*no default*";                                                \
+    outs() << ")\n";                                                           \
+  }
 
 PRINT_OPT_DIFF(bool)
 PRINT_OPT_DIFF(boolOrDefault)
 
 PRINT_OPT_DIFF(bool)
 PRINT_OPT_DIFF(boolOrDefault)
index f7c213ac2b85127ecc63a28cace6d6258163e35a..b3f3056ba6bb1a743524f104ffd2fbad3f4019f6 100644 (file)
@@ -704,6 +704,10 @@ void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
 // and we only need to set the vector size when the data is flushed.
 
 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
 // and we only need to set the vector size when the data is flushed.
 
 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
+  init();
+}
+
+void raw_svector_ostream::init() {
   // Set up the initial external buffer. We make sure that the buffer has at
   // least 128 bytes free; raw_ostream itself only requires 64, but we want to
   // make sure that we don't grow the buffer unnecessarily on destruction (when
   // Set up the initial external buffer. We make sure that the buffer has at
   // least 128 bytes free; raw_ostream itself only requires 64, but we want to
   // make sure that we don't grow the buffer unnecessarily on destruction (when
index c99c2bab45abb991e29ffdea7461947940e9f967..594d4d9a94255e761a6538e35bee5b1754c8016e 100644 (file)
@@ -209,13 +209,12 @@ struct SequenceOp : public SetTheory::Operator {
         break;
       else if (Step < 0 && From < To)
         break;
         break;
       else if (Step < 0 && From < To)
         break;
-      std::string Name;
-      raw_string_ostream OS(Name);
-      OS << format(Format.c_str(), unsigned(From));
-      Record *Rec = Records.getDef(OS.str());
+      string_ostream Name;
+      Name << format(Format.c_str(), unsigned(From));
+      Record *Rec = Records.getDef(Name.str());
       if (!Rec)
       if (!Rec)
-        PrintFatalError(Loc, "No def named '" + Name + "': " +
-          Expr->getAsString());
+        PrintFatalError(Loc, "No def named '" + Name.str() + "': " +
+                                 Expr->getAsString());
       // Try to reevaluate Rec in case it is a set.
       if (const RecVec *Result = ST.expand(Rec))
         Elts.insert(Result->begin(), Result->end());
       // Try to reevaluate Rec in case it is a set.
       if (const RecVec *Result = ST.expand(Rec))
         Elts.insert(Result->begin(), Result->end());
index 0550692ebce7ff40f9d2c9084dd5dc42e518c7f7..76ef696c68c2fa3fb5a05cab76e56eb51682c29c 100644 (file)
@@ -1307,8 +1307,7 @@ Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
     if (ItemType) {
       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
       if (!ListType) {
     if (ItemType) {
       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
       if (!ListType) {
-        std::string s;
-        raw_string_ostream ss(s);
+        string_ostream ss;
         ss << "Type mismatch for list, expected list type, got "
            << ItemType->getAsString();
         TokError(ss.str());
         ss << "Type mismatch for list, expected list type, got "
            << ItemType->getAsString();
         TokError(ss.str());
index 195b3c0fe9ed38a377f6098c370ffd0295d0835e..eee2f9264fc8c8c0b552c5220c48721165855c28 100644 (file)
@@ -146,8 +146,7 @@ const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
 
     // Otherwise report the problem to the user.
     {
 
     // Otherwise report the problem to the user.
     {
-      std::string S;
-      raw_string_ostream OS(S);
+      string_ostream OS;
       OS << "Unsupported expression in static initializer: ";
       CE->printAsOperand(OS, /*PrintType=*/ false,
                          !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
       OS << "Unsupported expression in static initializer: ";
       CE->printAsOperand(OS, /*PrintType=*/ false,
                          !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
index 20923c97ec8815c79a55b71d4becb84ec4def8c7..0b0a09a0ad7453deed6b02bf266e1294b2305671 100644 (file)
@@ -237,15 +237,13 @@ LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
 LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T,
   LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
   LLVMMemoryBufferRef *OutMemBuf) {
 LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T,
   LLVMModuleRef M, LLVMCodeGenFileType codegen, char** ErrorMessage,
   LLVMMemoryBufferRef *OutMemBuf) {
-  std::string CodeString;
-  raw_string_ostream OStream(CodeString);
-  formatted_raw_ostream Out(OStream);
+  string_ostream Code;
+  formatted_raw_ostream Out(Code);
   bool Result = LLVMTargetMachineEmit(T, M, Out, codegen, ErrorMessage);
   bool Result = LLVMTargetMachineEmit(T, M, Out, codegen, ErrorMessage);
-  OStream.flush();
 
 
-  std::string &Data = OStream.str();
-  *OutMemBuf = LLVMCreateMemoryBufferWithMemoryRangeCopy(Data.c_str(),
-                                                     Data.length(), "");
+  StringRef Buffer = Code.str();
+  *OutMemBuf = LLVMCreateMemoryBufferWithMemoryRangeCopy(Buffer.data(),
+                                                         Buffer.size(), "");
   return Result;
 }
 
   return Result;
 }
 
index 3e57914f9e941497c5224bee3e8bf1aa891c6e69..7e04608d991d4dc049de27924a265eaa5ff5d749 100644 (file)
@@ -2412,8 +2412,7 @@ bool X86AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
 
     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
 
-    SmallString<126> Msg;
-    raw_svector_ostream OS(Msg);
+    small_string_ostream<128> OS;
     OS << "ambiguous instructions require an explicit suffix (could be ";
     for (unsigned i = 0; i != NumMatches; ++i) {
       if (i != 0)
     OS << "ambiguous instructions require an explicit suffix (could be ";
     for (unsigned i = 0; i != NumMatches; ++i) {
       if (i != 0)
index 78403424da63f627b4a077a2ea7c44cc621ef83a..3f9eb07d83de556c1a3588944236d0e755fd6ce8 100644 (file)
@@ -281,8 +281,7 @@ void X86AsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) const {
   unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
 
   if (RelaxedOp == Inst.getOpcode()) {
   unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
 
   if (RelaxedOp == Inst.getOpcode()) {
-    SmallString<256> Tmp;
-    raw_svector_ostream OS(Tmp);
+    small_string_ostream<256> OS;
     Inst.dump_pretty(OS);
     OS << "\n";
     report_fatal_error("unexpected instruction to relax: " + OS.str());
     Inst.dump_pretty(OS);
     OS << "\n";
     report_fatal_error("unexpected instruction to relax: " + OS.str());
index 1dca5689adee0dfeadf28d26aa82f08333a82aad..cdfff821431781e83d8a3f945e1ea50d4b3de85d 100644 (file)
@@ -550,8 +550,7 @@ emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
 }
 
 void X86AsmPrinter::GenerateExportDirective(const MCSymbol *Sym, bool IsData) {
 }
 
 void X86AsmPrinter::GenerateExportDirective(const MCSymbol *Sym, bool IsData) {
-  SmallString<128> Directive;
-  raw_svector_ostream OS(Directive);
+  small_string_ostream<128> OS;
   StringRef Name = Sym->getName();
 
   if (Subtarget->isTargetKnownWindowsMSVC())
   StringRef Name = Sym->getName();
 
   if (Subtarget->isTargetKnownWindowsMSVC())
@@ -572,8 +571,7 @@ void X86AsmPrinter::GenerateExportDirective(const MCSymbol *Sym, bool IsData) {
       OS << ",data";
   }
 
       OS << ",data";
   }
 
-  OS.flush();
-  OutStreamer.EmitBytes(Directive);
+  OutStreamer.EmitBytes(OS.str());
 }
 
 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
 }
 
 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
index e98d4f933dfbde525c747950a066a32045164508..7b5da3349654f5080654ee882f91ef6974edc215 100644 (file)
@@ -267,8 +267,7 @@ PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
 }
 
 void XCoreAsmPrinter::EmitInstruction(const MachineInstr *MI) {
 }
 
 void XCoreAsmPrinter::EmitInstruction(const MachineInstr *MI) {
-  SmallString<128> Str;
-  raw_svector_ostream O(Str);
+  small_string_ostream<128> O;
 
   switch (MI->getOpcode()) {
   case XCore::DBG_VALUE:
 
   switch (MI->getOpcode()) {
   case XCore::DBG_VALUE:
index f2f1738808be89e5174c4fc2e092b937d51b9241..56e60e69849b690e2677a3e208fb9919b3ab7815 100644 (file)
@@ -352,14 +352,12 @@ private:
   }
 
   std::string getTypeName(Type *T) {
   }
 
   std::string getTypeName(Type *T) {
-    std::string TypeName;
-    raw_string_ostream TypeStream(TypeName);
+    string_ostream OS;
     if (T)
     if (T)
-      T->print(TypeStream);
+      T->print(OS);
     else
     else
-      TypeStream << "Printing <null> Type";
-    TypeStream.flush();
-    return TypeName;
+      OS << "Printing <null> Type";
+    return OS.str();
   }
 
   /// Returns the MDNode that represents type T if it is already created, or 0
   }
 
   /// Returns the MDNode that represents type T if it is already created, or 0
index cfeb62eb1f9fc722eb1eb980d4da22a53c9755d3..5af938beaeda35a8116f307d7c5ea73b02eb0973 100644 (file)
@@ -316,11 +316,9 @@ namespace {
       }
       ReturnBlock = new GCOVBlock(i++, os);
 
       }
       ReturnBlock = new GCOVBlock(i++, os);
 
-      std::string FunctionNameAndLine;
-      raw_string_ostream FNLOS(FunctionNameAndLine);
-      FNLOS << getFunctionName(SP) << SP.getLineNumber();
-      FNLOS.flush();
-      FuncChecksum = hash_value(FunctionNameAndLine);
+      string_ostream FnNameLine;
+      FnNameLine << getFunctionName(SP) << SP.getLineNumber();
+      FuncChecksum = hash_value(FnNameLine.str());
     }
 
     ~GCOVFunction() {
     }
 
     ~GCOVFunction() {
@@ -337,15 +335,14 @@ namespace {
     }
 
     std::string getEdgeDestinations() {
     }
 
     std::string getEdgeDestinations() {
-      std::string EdgeDestinations;
-      raw_string_ostream EDOS(EdgeDestinations);
+      string_ostream EdgeDestinations;
       Function *F = Blocks.begin()->first->getParent();
       for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
         GCOVBlock &Block = *Blocks[I];
         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
       Function *F = Blocks.begin()->first->getParent();
       for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
         GCOVBlock &Block = *Blocks[I];
         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
-          EDOS << Block.OutEdges[i]->Number;
+          EdgeDestinations << Block.OutEdges[i]->Number;
       }
       }
-      return EdgeDestinations;
+      return EdgeDestinations.str();
     }
 
     uint32_t getFuncChecksum() {
     }
 
     uint32_t getFuncChecksum() {
index 4ca03238071f11a8fd330f99fe2edad9a3dd8439..bb88bc00badb8bd47b37c00e31318a1d38f720a0 100644 (file)
@@ -2424,8 +2424,7 @@ struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
 
     if (PoisonStack && MS.TrackOrigins) {
       setOrigin(&I, getCleanOrigin());
 
     if (PoisonStack && MS.TrackOrigins) {
       setOrigin(&I, getCleanOrigin());
-      SmallString<2048> StackDescriptionStorage;
-      raw_svector_ostream StackDescription(StackDescriptionStorage);
+      small_string_ostream<2048> StackDescription;
       // We create a string with a description of the stack allocation and
       // pass it into __msan_set_alloca_origin.
       // It will be printed by the run-time if stack-originated UMR is found.
       // We create a string with a description of the stack allocation and
       // pass it into __msan_set_alloca_origin.
       // It will be printed by the run-time if stack-originated UMR is found.
index dd4dd50f0ba597c9b279ff7df7905572cc862a03..744fb24048a867a3866443df4eb495655c9d6a8d 100644 (file)
@@ -835,8 +835,7 @@ static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
       // of line at the module level and to provide a very simple format
       // encoding the information herein. Both of these makes it simpler to
       // parse the annotations by a simple external program.
       // of line at the module level and to provide a very simple format
       // encoding the information herein. Both of these makes it simpler to
       // parse the annotations by a simple external program.
-      std::string Str;
-      raw_string_ostream os(Str);
+      string_ostream os;
       os << "(" << Inst->getParent()->getParent()->getName() << ",%"
          << Inst->getName() << ")";
 
       os << "(" << Inst->getParent()->getParent()->getName() << ",%"
          << Inst->getName() << ")";
 
@@ -849,8 +848,7 @@ static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
       Hash = cast<MDString>(Node->getOperand(0));
     }
   } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
       Hash = cast<MDString>(Node->getOperand(0));
     }
   } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
-    std::string str;
-    raw_string_ostream os(str);
+    string_ostream os;
     os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
        << ")";
     Hash = MDString::get(Arg->getContext(), os.str());
     os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
        << ")";
     Hash = MDString::get(Arg->getContext(), os.str());
@@ -860,8 +858,7 @@ static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
 }
 
 static std::string SequenceToString(Sequence A) {
 }
 
 static std::string SequenceToString(Sequence A) {
-  std::string str;
-  raw_string_ostream os(str);
+  string_ostream os;
   os << A;
   return os.str();
 }
   os << A;
   return os.str();
 }
index cce016aafdda9f798fa67bd437ee73ff9cf0eeff..42fd398d5f3484ae964858adecc4430022296697 100644 (file)
@@ -65,8 +65,7 @@ ComputeASanStackFrameLayout(SmallVectorImpl<ASanStackVariableDescription> &Vars,
     Vars[i].Alignment = std::max(Vars[i].Alignment, kMinAlignment);
 
   std::stable_sort(Vars.begin(), Vars.end(), CompareVars);
     Vars[i].Alignment = std::max(Vars[i].Alignment, kMinAlignment);
 
   std::stable_sort(Vars.begin(), Vars.end(), CompareVars);
-  SmallString<2048> StackDescriptionStorage;
-  raw_svector_ostream StackDescription(StackDescriptionStorage);
+  small_string_ostream<2048> StackDescription;
   StackDescription << NumVars;
   Layout->FrameAlignment = std::max(Granularity, Vars[0].Alignment);
   SmallVector<uint8_t, 64> &SB(Layout->ShadowBytes);
   StackDescription << NumVars;
   Layout->FrameAlignment = std::max(Granularity, Vars[0].Alignment);
   SmallVector<uint8_t, 64> &SB(Layout->ShadowBytes);
index cb8a41dbeab66875bec8fd87dc12c6679456c2d8..2338d296ccfdb88134a85aa0befa06f370ba52bb 100644 (file)
@@ -212,24 +212,23 @@ class LoopVectorizationCostModel;
 /// Optimization analysis message produced during vectorization. Messages inform
 /// the user why vectorization did not occur.
 class Report {
 /// Optimization analysis message produced during vectorization. Messages inform
 /// the user why vectorization did not occur.
 class Report {
-  std::string Message;
-  raw_string_ostream Out;
+  string_ostream Message;
   Instruction *Instr;
 
 public:
   Instruction *Instr;
 
 public:
-  Report(Instruction *I = nullptr) : Out(Message), Instr(I) {
-    Out << "loop not vectorized: ";
+  Report(Instruction *I = nullptr) : Instr(I) {
+    Message << "loop not vectorized: ";
   }
 
   template <typename A> Report &operator<<(const A &Value) {
   }
 
   template <typename A> Report &operator<<(const A &Value) {
-    Out << Value;
+    Message << Value;
     return *this;
   }
 
   Instruction *getInstr() { return Instr; }
 
     return *this;
   }
 
   Instruction *getInstr() { return Instr; }
 
-  std::string &str() { return Out.str(); }
-  operator Twine() { return Out.str(); }
+  StringRef str() { return Message.str(); }
+  operator Twine() { return Message.str(); }
 };
 
 /// InnerLoopVectorizer vectorizes loops which contain only one basic
 };
 
 /// InnerLoopVectorizer vectorizes loops which contain only one basic
@@ -503,18 +502,17 @@ static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
 #ifndef NDEBUG
 /// \return string containing a file name and a line # for the given loop.
 static std::string getDebugLocString(const Loop *L) {
 #ifndef NDEBUG
 /// \return string containing a file name and a line # for the given loop.
 static std::string getDebugLocString(const Loop *L) {
-  std::string Result;
-  if (L) {
-    raw_string_ostream OS(Result);
-    const DebugLoc LoopDbgLoc = L->getStartLoc();
-    if (!LoopDbgLoc.isUnknown())
-      LoopDbgLoc.print(L->getHeader()->getContext(), OS);
-    else
-      // Just print the module name.
-      OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
-    OS.flush();
-  }
-  return Result;
+  if (!L)
+    return std::string();
+
+  string_ostream OS;
+  const DebugLoc LoopDbgLoc = L->getStartLoc();
+  if (!LoopDbgLoc.isUnknown())
+    LoopDbgLoc.print(L->getHeader()->getContext(), OS);
+  else
+    // Just print the module name.
+    OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
+  return OS.str();
 }
 #endif
 
 }
 #endif
 
index 60886bb7b110ec8006cd3fa7398c9ad25925732f..2d7e8df6b4682a845195fb395815d1781df8074e 100644 (file)
@@ -689,8 +689,7 @@ writeSymbolTable(raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
                  std::vector<std::pair<unsigned, unsigned>> &MemberOffsetRefs) {
   unsigned StartOffset = 0;
   unsigned MemberNum = 0;
                  std::vector<std::pair<unsigned, unsigned>> &MemberOffsetRefs) {
   unsigned StartOffset = 0;
   unsigned MemberNum = 0;
-  std::string NameBuf;
-  raw_string_ostream NameOS(NameBuf);
+  string_ostream NameOS;
   unsigned NumSyms = 0;
   LLVMContext &Context = getGlobalContext();
   for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
   unsigned NumSyms = 0;
   LLVMContext &Context = getGlobalContext();
   for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
index d98691b4b044f27b79ebf069e238bd8a00f6d366..d9886c10aeb5e9b932e9ccbcc451ecaeec3fb04a 100644 (file)
@@ -222,8 +222,7 @@ static void emitDOTFile(const char *FileName, const MCFunction &f,
         Out << "<o>";
 
       // Escape special chars and print the instruction in mnemonic form.
         Out << "<o>";
 
       // Escape special chars and print the instruction in mnemonic form.
-      std::string Str;
-      raw_string_ostream OS(Str);
+      string_ostream OS;
       IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
       Out << DOT::EscapeString(OS.str());
     }
       IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
       Out << DOT::EscapeString(OS.str());
     }
@@ -473,9 +472,7 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
     if (Symbols.empty())
       Symbols.push_back(std::make_pair(0, name));
 
     if (Symbols.empty())
       Symbols.push_back(std::make_pair(0, name));
 
-
-    SmallString<40> Comments;
-    raw_svector_ostream CommentStream(Comments);
+    small_string_ostream<40> Comments;
 
     StringRef Bytes;
     if (error(Section.getContents(Bytes)))
 
     StringRef Bytes;
     if (error(Section.getContents(Bytes)))
@@ -513,15 +510,14 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
         MCInst Inst;
 
         if (DisAsm->getInstruction(Inst, Size, memoryObject,
         MCInst Inst;
 
         if (DisAsm->getInstruction(Inst, Size, memoryObject,
-                                   SectionAddr + Index,
-                                   DebugOut, CommentStream)) {
+                                   SectionAddr + Index, DebugOut, Comments)) {
           outs() << format("%8" PRIx64 ":", SectionAddr + Index);
           if (!NoShowRawInsn) {
             outs() << "\t";
             DumpBytes(StringRef(Bytes.data() + Index, Size));
           }
           IP->printInst(&Inst, outs(), "");
           outs() << format("%8" PRIx64 ":", SectionAddr + Index);
           if (!NoShowRawInsn) {
             outs() << "\t";
             DumpBytes(StringRef(Bytes.data() + Index, Size));
           }
           IP->printInst(&Inst, outs(), "");
-          outs() << CommentStream.str();
+          outs() << Comments.str();
           Comments.clear();
           outs() << "\n";
         } else {
           Comments.clear();
           outs() << "\n";
         } else {
index f6675bdcfedf1d6d19b057e2eb442549fd5ed070..7138438ca229f5415046f5bf353e7ec41a3f12d5 100644 (file)
@@ -95,8 +95,7 @@ raw_ostream &operator<<(raw_ostream &OS, const ARM::WinEH::ReturnType &RT) {
 
 static std::string formatSymbol(StringRef Name, uint64_t Address,
                                 uint64_t Offset = 0) {
 
 static std::string formatSymbol(StringRef Name, uint64_t Address,
                                 uint64_t Offset = 0) {
-  std::string Buffer;
-  raw_string_ostream OS(Buffer);
+  string_ostream OS;
 
   if (!Name.empty())
     OS << Name << " ";
 
   if (!Name.empty())
     OS << Name << " ";
index f058632a8ce89e4310fa8321a3cd7d53cc9e193e..2d6784348600af72fe6ee8a9da5b53821b7ecbd0 100644 (file)
@@ -115,8 +115,7 @@ static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
 static std::string formatSymbol(const Dumper::Context &Ctx,
                                 const coff_section *Section, uint64_t Offset,
                                 uint32_t Displacement) {
 static std::string formatSymbol(const Dumper::Context &Ctx,
                                 const coff_section *Section, uint64_t Offset,
                                 uint32_t Displacement) {
-  std::string Buffer;
-  raw_string_ostream OS(Buffer);
+  string_ostream OS;
 
   StringRef Name;
   SymbolRef Symbol;
 
   StringRef Name;
   SymbolRef Symbol;
@@ -131,6 +130,7 @@ static std::string formatSymbol(const Dumper::Context &Ctx,
     OS << format(" +0x%X (0x%" PRIX64 ")", Displacement, Offset);
   else
     OS << format(" (0x%" PRIX64 ")", Offset);
     OS << format(" +0x%X (0x%" PRIX64 ")", Displacement, Offset);
   else
     OS << format(" (0x%" PRIX64 ")", Offset);
+
   return OS.str();
 }
 
   return OS.str();
 }
 
index 817d207c2dca9d49afe5936779d6e05a59d446dd..aa79bdc730155f2448882778f32a85c5471ecd85 100644 (file)
@@ -70,9 +70,9 @@ Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
 }
 
 std::string DumpFunction(const Function *F) {
 }
 
 std::string DumpFunction(const Function *F) {
-  std::string Result;
-  raw_string_ostream(Result) << "" << *F;
-  return Result;
+  string_ostream Result;
+  Result << "" << *F;
+  return Result.str();
 }
 
 class RecordingJITMemoryManager : public JITMemoryManager {
 }
 
 class RecordingJITMemoryManager : public JITMemoryManager {
@@ -170,10 +170,9 @@ bool LoadAssemblyInto(Module *M, const char *assembly) {
   SMDiagnostic Error;
   bool success =
     nullptr != ParseAssemblyString(assembly, M, Error, M->getContext());
   SMDiagnostic Error;
   bool success =
     nullptr != ParseAssemblyString(assembly, M, Error, M->getContext());
-  std::string errMsg;
-  raw_string_ostream os(errMsg);
-  Error.print("", os);
-  EXPECT_TRUE(success) << os.str();
+  string_ostream errMsg;
+  Error.print("", errMsg);
+  EXPECT_TRUE(success) << errMsg.str();
   return success;
 }
 
   return success;
 }
 
index 978e05f4f2ca453d1ff8e131ca4f9b4f91f14156..2c33e6896b762bacf50f65fdf3e84e4f6be8c555 100644 (file)
@@ -458,8 +458,7 @@ void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
   // variable values.
   if (!VariableUses.empty()) {
     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
   // variable values.
   if (!VariableUses.empty()) {
     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
-      SmallString<256> Msg;
-      raw_svector_ostream OS(Msg);
+      small_string_ostream<256> OS;
       StringRef Var = VariableUses[i].first;
       if (Var[0] == '@') {
         std::string Value;
       StringRef Var = VariableUses[i].first;
       if (Var[0] == '@') {
         std::string Value;
index 4d0c0ca8e7019a82e2ade70369492d44d5023b22..5e27d45b156a8f43da29dae173f20752bec5feb9 100644 (file)
@@ -319,8 +319,7 @@ void CodeEmitterGen::run(raw_ostream &o) {
 
   // Default case: unhandled opcode
   o << "  default:\n"
 
   // Default case: unhandled opcode
   o << "  default:\n"
-    << "    std::string msg;\n"
-    << "    raw_string_ostream Msg(msg);\n"
+    << "    string_ostream Msg;\n"
     << "    Msg << \"Not supported instr: \" << MI;\n"
     << "    report_fatal_error(Msg.str());\n"
     << "  }\n"
     << "    Msg << \"Not supported instr: \" << MI;\n"
     << "    report_fatal_error(Msg.str());\n"
     << "  }\n"
index 39b8f72ecc507d8bd6f453ebe3493832509576ab..c3c7c152c2cafebeb7c933a4c6f7b87edc7441c7 100644 (file)
@@ -166,23 +166,21 @@ static void benchmark( llvm::TimerGroup &Group
 }
 
 static std::string createJSONText(size_t MemoryMB, unsigned ValueSize) {
 }
 
 static std::string createJSONText(size_t MemoryMB, unsigned ValueSize) {
-  std::string JSONText;
-  llvm::raw_string_ostream Stream(JSONText);
-  Stream << "[\n";
+  llvm::string_ostream OS;
+  OS << "[\n";
   size_t MemoryBytes = MemoryMB * 1024 * 1024;
   size_t MemoryBytes = MemoryMB * 1024 * 1024;
-  while (JSONText.size() < MemoryBytes) {
-    Stream << " {\n"
-           << "  \"key1\": \"" << std::string(ValueSize, '*') << "\",\n"
-           << "  \"key2\": \"" << std::string(ValueSize, '*') << "\",\n"
-           << "  \"key3\": \"" << std::string(ValueSize, '*') << "\"\n"
-           << " }";
-    Stream.flush();
-    if (JSONText.size() < MemoryBytes) Stream << ",";
-    Stream << "\n";
+  while (OS.tell() < MemoryBytes) {
+    OS << " {\n"
+       << "  \"key1\": \"" << std::string(ValueSize, '*') << "\",\n"
+       << "  \"key2\": \"" << std::string(ValueSize, '*') << "\",\n"
+       << "  \"key3\": \"" << std::string(ValueSize, '*') << "\"\n"
+       << " }";
+    if (OS.tell() < MemoryBytes)
+      OS << ",";
+    OS << "\n";
   }
   }
-  Stream << "]\n";
-  Stream.flush();
-  return JSONText;
+  OS << "]\n";
+  return OS.str();
 }
 
 int main(int argc, char **argv) {
 }
 
 int main(int argc, char **argv) {