Use the cast machinery to remove dummy uses of formatted_raw_ostream.
[oota-llvm.git] / lib / LTO / LTOCodeGenerator.cpp
1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/LTO/LTOCodeGenerator.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/RuntimeLibcalls.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/LTO/LTOModule.h"
35 #include "llvm/Linker/Linker.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include <system_error>
56 using namespace llvm;
57
58 const char* LTOCodeGenerator::getVersionString() {
59 #ifdef LLVM_VERSION_INFO
60   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
61 #else
62   return PACKAGE_NAME " version " PACKAGE_VERSION;
63 #endif
64 }
65
66 LTOCodeGenerator::LTOCodeGenerator()
67     : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
68   initialize();
69 }
70
71 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
72     : OwnedContext(std::move(Context)), Context(*OwnedContext),
73       IRLinker(new Module("ld-temp.o", *OwnedContext)), OptLevel(2) {
74   initialize();
75 }
76
77 void LTOCodeGenerator::initialize() {
78   TargetMach = nullptr;
79   EmitDwarfDebugInfo = false;
80   ScopeRestrictionsDone = false;
81   CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT;
82   DiagHandler = nullptr;
83   DiagContext = nullptr;
84   OwnedModule = nullptr;
85
86   initializeLTOPasses();
87 }
88
89 void LTOCodeGenerator::destroyMergedModule() {
90   if (OwnedModule) {
91     assert(IRLinker.getModule() == &OwnedModule->getModule() &&
92            "The linker's module should be the same as the owned module");
93     delete OwnedModule;
94     OwnedModule = nullptr;
95   } else if (IRLinker.getModule())
96     IRLinker.deleteModule();
97 }
98
99 LTOCodeGenerator::~LTOCodeGenerator() {
100   destroyMergedModule();
101
102   delete TargetMach;
103   TargetMach = nullptr;
104
105   for (std::vector<char *>::iterator I = CodegenOptions.begin(),
106                                      E = CodegenOptions.end();
107        I != E; ++I)
108     free(*I);
109 }
110
111 // Initialize LTO passes. Please keep this funciton in sync with
112 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
113 // passes are initialized.
114 void LTOCodeGenerator::initializeLTOPasses() {
115   PassRegistry &R = *PassRegistry::getPassRegistry();
116
117   initializeInternalizePassPass(R);
118   initializeIPSCCPPass(R);
119   initializeGlobalOptPass(R);
120   initializeConstantMergePass(R);
121   initializeDAHPass(R);
122   initializeInstructionCombiningPassPass(R);
123   initializeSimpleInlinerPass(R);
124   initializePruneEHPass(R);
125   initializeGlobalDCEPass(R);
126   initializeArgPromotionPass(R);
127   initializeJumpThreadingPass(R);
128   initializeSROAPass(R);
129   initializeSROA_DTPass(R);
130   initializeSROA_SSAUpPass(R);
131   initializeFunctionAttrsPass(R);
132   initializeGlobalsModRefPass(R);
133   initializeLICMPass(R);
134   initializeMergedLoadStoreMotionPass(R);
135   initializeGVNPass(R);
136   initializeMemCpyOptPass(R);
137   initializeDCEPass(R);
138   initializeCFGSimplifyPassPass(R);
139 }
140
141 bool LTOCodeGenerator::addModule(LTOModule *mod) {
142   assert(&mod->getModule().getContext() == &Context &&
143          "Expected module in same context");
144
145   bool ret = IRLinker.linkInModule(&mod->getModule());
146
147   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
148   for (int i = 0, e = undefs.size(); i != e; ++i)
149     AsmUndefinedRefs[undefs[i]] = 1;
150
151   return !ret;
152 }
153
154 void LTOCodeGenerator::setModule(LTOModule *Mod) {
155   assert(&Mod->getModule().getContext() == &Context &&
156          "Expected module in same context");
157
158   // Delete the old merged module.
159   destroyMergedModule();
160   AsmUndefinedRefs.clear();
161
162   OwnedModule = Mod;
163   IRLinker.setModule(&Mod->getModule());
164
165   const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
166   for (int I = 0, E = Undefs.size(); I != E; ++I)
167     AsmUndefinedRefs[Undefs[I]] = 1;
168 }
169
170 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
171   Options = options;
172 }
173
174 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
175   switch (debug) {
176   case LTO_DEBUG_MODEL_NONE:
177     EmitDwarfDebugInfo = false;
178     return;
179
180   case LTO_DEBUG_MODEL_DWARF:
181     EmitDwarfDebugInfo = true;
182     return;
183   }
184   llvm_unreachable("Unknown debug format!");
185 }
186
187 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
188   switch (model) {
189   case LTO_CODEGEN_PIC_MODEL_STATIC:
190   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
191   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
192   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
193     CodeModel = model;
194     return;
195   }
196   llvm_unreachable("Unknown PIC model!");
197 }
198
199 bool LTOCodeGenerator::writeMergedModules(const char *path,
200                                           std::string &errMsg) {
201   if (!determineTarget(errMsg))
202     return false;
203
204   // mark which symbols can not be internalized
205   applyScopeRestrictions();
206
207   // create output file
208   std::error_code EC;
209   tool_output_file Out(path, EC, sys::fs::F_None);
210   if (EC) {
211     errMsg = "could not open bitcode file for writing: ";
212     errMsg += path;
213     return false;
214   }
215
216   // write bitcode to it
217   WriteBitcodeToFile(IRLinker.getModule(), Out.os());
218   Out.os().close();
219
220   if (Out.os().has_error()) {
221     errMsg = "could not write bitcode file: ";
222     errMsg += path;
223     Out.os().clear_error();
224     return false;
225   }
226
227   Out.keep();
228   return true;
229 }
230
231 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
232                                               std::string &errMsg) {
233   // make unique temp .o file to put generated object file
234   SmallString<128> Filename;
235   int FD;
236   std::error_code EC =
237       sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
238   if (EC) {
239     errMsg = EC.message();
240     return false;
241   }
242
243   // generate object file
244   tool_output_file objFile(Filename.c_str(), FD);
245
246   bool genResult = compileOptimized(objFile.os(), errMsg);
247   objFile.os().close();
248   if (objFile.os().has_error()) {
249     objFile.os().clear_error();
250     sys::fs::remove(Twine(Filename));
251     return false;
252   }
253
254   objFile.keep();
255   if (!genResult) {
256     sys::fs::remove(Twine(Filename));
257     return false;
258   }
259
260   NativeObjectPath = Filename.c_str();
261   *name = NativeObjectPath.c_str();
262   return true;
263 }
264
265 const void *LTOCodeGenerator::compileOptimized(size_t *length,
266                                                std::string &errMsg) {
267   const char *name;
268   if (!compileOptimizedToFile(&name, errMsg))
269     return nullptr;
270
271   // read .o file into memory buffer
272   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
273       MemoryBuffer::getFile(name, -1, false);
274   if (std::error_code EC = BufferOrErr.getError()) {
275     errMsg = EC.message();
276     sys::fs::remove(NativeObjectPath);
277     return nullptr;
278   }
279   NativeObjectFile = std::move(*BufferOrErr);
280
281   // remove temp files
282   sys::fs::remove(NativeObjectPath);
283
284   // return buffer, unless error
285   if (!NativeObjectFile)
286     return nullptr;
287   *length = NativeObjectFile->getBufferSize();
288   return NativeObjectFile->getBufferStart();
289 }
290
291
292 bool LTOCodeGenerator::compile_to_file(const char **name,
293                                        bool disableInline,
294                                        bool disableGVNLoadPRE,
295                                        bool disableVectorization,
296                                        std::string &errMsg) {
297   if (!optimize(disableInline, disableGVNLoadPRE,
298                 disableVectorization, errMsg))
299     return false;
300
301   return compileOptimizedToFile(name, errMsg);
302 }
303
304 const void* LTOCodeGenerator::compile(size_t *length,
305                                       bool disableInline,
306                                       bool disableGVNLoadPRE,
307                                       bool disableVectorization,
308                                       std::string &errMsg) {
309   if (!optimize(disableInline, disableGVNLoadPRE,
310                 disableVectorization, errMsg))
311     return nullptr;
312
313   return compileOptimized(length, errMsg);
314 }
315
316 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
317   if (TargetMach)
318     return true;
319
320   std::string TripleStr = IRLinker.getModule()->getTargetTriple();
321   if (TripleStr.empty())
322     TripleStr = sys::getDefaultTargetTriple();
323   llvm::Triple Triple(TripleStr);
324
325   // create target machine from info for merged modules
326   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
327   if (!march)
328     return false;
329
330   // The relocation model is actually a static member of TargetMachine and
331   // needs to be set before the TargetMachine is instantiated.
332   Reloc::Model RelocModel = Reloc::Default;
333   switch (CodeModel) {
334   case LTO_CODEGEN_PIC_MODEL_STATIC:
335     RelocModel = Reloc::Static;
336     break;
337   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
338     RelocModel = Reloc::PIC_;
339     break;
340   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
341     RelocModel = Reloc::DynamicNoPIC;
342     break;
343   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
344     // RelocModel is already the default, so leave it that way.
345     break;
346   }
347
348   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
349   // the default set of features.
350   SubtargetFeatures Features(MAttr);
351   Features.getDefaultSubtargetFeatures(Triple);
352   std::string FeatureStr = Features.getString();
353   // Set a default CPU for Darwin triples.
354   if (MCpu.empty() && Triple.isOSDarwin()) {
355     if (Triple.getArch() == llvm::Triple::x86_64)
356       MCpu = "core2";
357     else if (Triple.getArch() == llvm::Triple::x86)
358       MCpu = "yonah";
359     else if (Triple.getArch() == llvm::Triple::aarch64)
360       MCpu = "cyclone";
361   }
362
363   CodeGenOpt::Level CGOptLevel;
364   switch (OptLevel) {
365   case 0:
366     CGOptLevel = CodeGenOpt::None;
367     break;
368   case 1:
369     CGOptLevel = CodeGenOpt::Less;
370     break;
371   case 2:
372     CGOptLevel = CodeGenOpt::Default;
373     break;
374   case 3:
375     CGOptLevel = CodeGenOpt::Aggressive;
376     break;
377   }
378
379   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
380                                           RelocModel, CodeModel::Default,
381                                           CGOptLevel);
382   return true;
383 }
384
385 void LTOCodeGenerator::
386 applyRestriction(GlobalValue &GV,
387                  ArrayRef<StringRef> Libcalls,
388                  std::vector<const char*> &MustPreserveList,
389                  SmallPtrSetImpl<GlobalValue*> &AsmUsed,
390                  Mangler &Mangler) {
391   // There are no restrictions to apply to declarations.
392   if (GV.isDeclaration())
393     return;
394
395   // There is nothing more restrictive than private linkage.
396   if (GV.hasPrivateLinkage())
397     return;
398
399   SmallString<64> Buffer;
400   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
401
402   if (MustPreserveSymbols.count(Buffer))
403     MustPreserveList.push_back(GV.getName().data());
404   if (AsmUndefinedRefs.count(Buffer))
405     AsmUsed.insert(&GV);
406
407   // Conservatively append user-supplied runtime library functions to
408   // llvm.compiler.used.  These could be internalized and deleted by
409   // optimizations like -globalopt, causing problems when later optimizations
410   // add new library calls (e.g., llvm.memset => memset and printf => puts).
411   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
412   if (isa<Function>(GV) &&
413       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
414     AsmUsed.insert(&GV);
415 }
416
417 static void findUsedValues(GlobalVariable *LLVMUsed,
418                            SmallPtrSetImpl<GlobalValue*> &UsedValues) {
419   if (!LLVMUsed) return;
420
421   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
422   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
423     if (GlobalValue *GV =
424         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
425       UsedValues.insert(GV);
426 }
427
428 // Collect names of runtime library functions. User-defined functions with the
429 // same names are added to llvm.compiler.used to prevent them from being
430 // deleted by optimizations.
431 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
432                                       const TargetLibraryInfo& TLI,
433                                       const Module &Mod,
434                                       const TargetMachine &TM) {
435   // TargetLibraryInfo has info on C runtime library calls on the current
436   // target.
437   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
438        I != E; ++I) {
439     LibFunc::Func F = static_cast<LibFunc::Func>(I);
440     if (TLI.has(F))
441       Libcalls.push_back(TLI.getName(F));
442   }
443
444   SmallPtrSet<const TargetLowering *, 1> TLSet;
445
446   for (const Function &F : Mod) {
447     const TargetLowering *Lowering =
448         TM.getSubtargetImpl(F)->getTargetLowering();
449
450     if (Lowering && TLSet.insert(Lowering).second)
451       // TargetLowering has info on library calls that CodeGen expects to be
452       // available, both from the C runtime and compiler-rt.
453       for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
454            I != E; ++I)
455         if (const char *Name =
456                 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
457           Libcalls.push_back(Name);
458   }
459
460   array_pod_sort(Libcalls.begin(), Libcalls.end());
461   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
462                  Libcalls.end());
463 }
464
465 void LTOCodeGenerator::applyScopeRestrictions() {
466   if (ScopeRestrictionsDone)
467     return;
468   Module *mergedModule = IRLinker.getModule();
469
470   // Start off with a verification pass.
471   legacy::PassManager passes;
472   passes.add(createVerifierPass());
473
474   // mark which symbols can not be internalized
475   Mangler Mangler(TargetMach->getDataLayout());
476   std::vector<const char*> MustPreserveList;
477   SmallPtrSet<GlobalValue*, 8> AsmUsed;
478   std::vector<StringRef> Libcalls;
479   TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
480   TargetLibraryInfo TLI(TLII);
481
482   accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
483
484   for (Module::iterator f = mergedModule->begin(),
485          e = mergedModule->end(); f != e; ++f)
486     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
487   for (Module::global_iterator v = mergedModule->global_begin(),
488          e = mergedModule->global_end(); v !=  e; ++v)
489     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
490   for (Module::alias_iterator a = mergedModule->alias_begin(),
491          e = mergedModule->alias_end(); a != e; ++a)
492     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
493
494   GlobalVariable *LLVMCompilerUsed =
495     mergedModule->getGlobalVariable("llvm.compiler.used");
496   findUsedValues(LLVMCompilerUsed, AsmUsed);
497   if (LLVMCompilerUsed)
498     LLVMCompilerUsed->eraseFromParent();
499
500   if (!AsmUsed.empty()) {
501     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
502     std::vector<Constant*> asmUsed2;
503     for (auto *GV : AsmUsed) {
504       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
505       asmUsed2.push_back(c);
506     }
507
508     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
509     LLVMCompilerUsed =
510       new llvm::GlobalVariable(*mergedModule, ATy, false,
511                                llvm::GlobalValue::AppendingLinkage,
512                                llvm::ConstantArray::get(ATy, asmUsed2),
513                                "llvm.compiler.used");
514
515     LLVMCompilerUsed->setSection("llvm.metadata");
516   }
517
518   passes.add(createInternalizePass(MustPreserveList));
519
520   // apply scope restrictions
521   passes.run(*mergedModule);
522
523   ScopeRestrictionsDone = true;
524 }
525
526 /// Optimize merged modules using various IPO passes
527 bool LTOCodeGenerator::optimize(bool DisableInline,
528                                 bool DisableGVNLoadPRE,
529                                 bool DisableVectorization,
530                                 std::string &errMsg) {
531   if (!this->determineTarget(errMsg))
532     return false;
533
534   Module *mergedModule = IRLinker.getModule();
535
536   // Mark which symbols can not be internalized
537   this->applyScopeRestrictions();
538
539   // Instantiate the pass manager to organize the passes.
540   legacy::PassManager passes;
541
542   // Add an appropriate DataLayout instance for this module...
543   mergedModule->setDataLayout(*TargetMach->getDataLayout());
544
545   passes.add(
546       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
547
548   Triple TargetTriple(TargetMach->getTargetTriple());
549   PassManagerBuilder PMB;
550   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
551   PMB.LoopVectorize = !DisableVectorization;
552   PMB.SLPVectorize = !DisableVectorization;
553   if (!DisableInline)
554     PMB.Inliner = createFunctionInliningPass();
555   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
556   PMB.OptLevel = OptLevel;
557   PMB.VerifyInput = true;
558   PMB.VerifyOutput = true;
559
560   PMB.populateLTOPassManager(passes);
561
562   // Run our queue of passes all at once now, efficiently.
563   passes.run(*mergedModule);
564
565   return true;
566 }
567
568 bool LTOCodeGenerator::compileOptimized(raw_ostream &out, std::string &errMsg) {
569   if (!this->determineTarget(errMsg))
570     return false;
571
572   Module *mergedModule = IRLinker.getModule();
573
574   legacy::PassManager codeGenPasses;
575
576   // If the bitcode files contain ARC code and were compiled with optimization,
577   // the ObjCARCContractPass must be run, so do it unconditionally here.
578   codeGenPasses.add(createObjCARCContractPass());
579
580   if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
581                                       TargetMachine::CGFT_ObjectFile)) {
582     errMsg = "target file type not supported";
583     return false;
584   }
585
586   // Run the code generator, and write assembly file
587   codeGenPasses.run(*mergedModule);
588
589   return true;
590 }
591
592 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
593 /// LTO problems.
594 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
595   for (std::pair<StringRef, StringRef> o = getToken(options);
596        !o.first.empty(); o = getToken(o.second)) {
597     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
598     // that.
599     if (CodegenOptions.empty())
600       CodegenOptions.push_back(strdup("libLLVMLTO"));
601     CodegenOptions.push_back(strdup(o.first.str().c_str()));
602   }
603 }
604
605 void LTOCodeGenerator::parseCodeGenDebugOptions() {
606   // if options were requested, set them
607   if (!CodegenOptions.empty())
608     cl::ParseCommandLineOptions(CodegenOptions.size(),
609                                 const_cast<char **>(&CodegenOptions[0]));
610 }
611
612 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
613                                          void *Context) {
614   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
615 }
616
617 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
618   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
619   lto_codegen_diagnostic_severity_t Severity;
620   switch (DI.getSeverity()) {
621   case DS_Error:
622     Severity = LTO_DS_ERROR;
623     break;
624   case DS_Warning:
625     Severity = LTO_DS_WARNING;
626     break;
627   case DS_Remark:
628     Severity = LTO_DS_REMARK;
629     break;
630   case DS_Note:
631     Severity = LTO_DS_NOTE;
632     break;
633   }
634   // Create the string that will be reported to the external diagnostic handler.
635   std::string MsgStorage;
636   raw_string_ostream Stream(MsgStorage);
637   DiagnosticPrinterRawOStream DP(Stream);
638   DI.print(DP);
639   Stream.flush();
640
641   // If this method has been called it means someone has set up an external
642   // diagnostic handler. Assert on that.
643   assert(DiagHandler && "Invalid diagnostic handler");
644   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
645 }
646
647 void
648 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
649                                        void *Ctxt) {
650   this->DiagHandler = DiagHandler;
651   this->DiagContext = Ctxt;
652   if (!DiagHandler)
653     return Context.setDiagnosticHandler(nullptr, nullptr);
654   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
655   // diagnostic to the external DiagHandler.
656   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
657                                /* RespectFilters */ true);
658 }