diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp @@ -876,10 +876,17 @@ } raw_fd_ostream &llvm::errs() { - // Set standard error to be unbuffered and tied to outs() by default. - static raw_fd_ostream S(STDERR_FILENO, false, true); - S.tie(&outs()); - return S; + // Ensure outs() is constructed before the unbuffered stderr stream so that + // outs() will be destructed after outs() and the TiedStream field of Init.S + // will not become dangling. The tie call is called once, thus the user can + // opt out the behavior. + static struct InitializeAndTie { + raw_fd_ostream S; + InitializeAndTie(raw_ostream &TieTo) : S(STDERR_FILENO, false, true) { + S.tie(&TieTo); + } + } Init(outs()); + return Init.S; } /// nulls() - This returns a reference to a raw_ostream which discards output.