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/legacy/LTOCodeGenerator.h"
16
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/CodeGen/ParallelCG.h"
24 #include "llvm/CodeGen/RuntimeLibcalls.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/LTO/legacy/LTOModule.h"
39 #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
40 #include "llvm/Linker/Linker.h"
41 #include "llvm/MC/MCAsmInfo.h"
42 #include "llvm/MC/MCContext.h"
43 #include "llvm/MC/SubtargetFeature.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/Signals.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetLowering.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "llvm/Target/TargetRegisterInfo.h"
56 #include "llvm/Target/TargetSubtargetInfo.h"
57 #include "llvm/Transforms/IPO.h"
58 #include "llvm/Transforms/IPO/Internalize.h"
59 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
60 #include "llvm/Transforms/ObjCARC.h"
61 #include <system_error>
62 using namespace llvm;
63
getVersionString()64 const char* LTOCodeGenerator::getVersionString() {
65 #ifdef LLVM_VERSION_INFO
66 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 #else
68 return PACKAGE_NAME " version " PACKAGE_VERSION;
69 #endif
70 }
71
72 namespace llvm {
73 cl::opt<bool> LTODiscardValueNames(
74 "lto-discard-value-names",
75 cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
76 #ifdef NDEBUG
77 cl::init(true),
78 #else
79 cl::init(false),
80 #endif
81 cl::Hidden);
82
83 cl::opt<bool> LTOStripInvalidDebugInfo(
84 "lto-strip-invalid-debug-info",
85 cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
86 #ifdef NDEBUG
87 cl::init(true),
88 #else
89 cl::init(false),
90 #endif
91 cl::Hidden);
92 }
93
LTOCodeGenerator(LLVMContext & Context)94 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
95 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
96 TheLinker(new Linker(*MergedModule)) {
97 Context.setDiscardValueNames(LTODiscardValueNames);
98 Context.enableDebugTypeODRUniquing();
99 initializeLTOPasses();
100 }
101
~LTOCodeGenerator()102 LTOCodeGenerator::~LTOCodeGenerator() {}
103
104 // Initialize LTO passes. Please keep this function in sync with
105 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
106 // passes are initialized.
initializeLTOPasses()107 void LTOCodeGenerator::initializeLTOPasses() {
108 PassRegistry &R = *PassRegistry::getPassRegistry();
109
110 initializeInternalizeLegacyPassPass(R);
111 initializeIPSCCPLegacyPassPass(R);
112 initializeGlobalOptLegacyPassPass(R);
113 initializeConstantMergeLegacyPassPass(R);
114 initializeDAHPass(R);
115 initializeInstructionCombiningPassPass(R);
116 initializeSimpleInlinerPass(R);
117 initializePruneEHPass(R);
118 initializeGlobalDCELegacyPassPass(R);
119 initializeArgPromotionPass(R);
120 initializeJumpThreadingPass(R);
121 initializeSROALegacyPassPass(R);
122 initializePostOrderFunctionAttrsLegacyPassPass(R);
123 initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
124 initializeGlobalsAAWrapperPassPass(R);
125 initializeLegacyLICMPassPass(R);
126 initializeMergedLoadStoreMotionLegacyPassPass(R);
127 initializeGVNLegacyPassPass(R);
128 initializeMemCpyOptLegacyPassPass(R);
129 initializeDCELegacyPassPass(R);
130 initializeCFGSimplifyPassPass(R);
131 }
132
addModule(LTOModule * Mod)133 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
134 assert(&Mod->getModule().getContext() == &Context &&
135 "Expected module in same context");
136
137 bool ret = TheLinker->linkInModule(Mod->takeModule());
138
139 const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
140 for (int i = 0, e = undefs.size(); i != e; ++i)
141 AsmUndefinedRefs[undefs[i]] = 1;
142
143 // We've just changed the input, so let's make sure we verify it.
144 HasVerifiedInput = false;
145
146 return !ret;
147 }
148
setModule(std::unique_ptr<LTOModule> Mod)149 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
150 assert(&Mod->getModule().getContext() == &Context &&
151 "Expected module in same context");
152
153 AsmUndefinedRefs.clear();
154
155 MergedModule = Mod->takeModule();
156 TheLinker = make_unique<Linker>(*MergedModule);
157
158 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
159 for (int I = 0, E = Undefs.size(); I != E; ++I)
160 AsmUndefinedRefs[Undefs[I]] = 1;
161
162 // We've just changed the input, so let's make sure we verify it.
163 HasVerifiedInput = false;
164 }
165
setTargetOptions(const TargetOptions & Options)166 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
167 this->Options = Options;
168 }
169
setDebugInfo(lto_debug_model Debug)170 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
171 switch (Debug) {
172 case LTO_DEBUG_MODEL_NONE:
173 EmitDwarfDebugInfo = false;
174 return;
175
176 case LTO_DEBUG_MODEL_DWARF:
177 EmitDwarfDebugInfo = true;
178 return;
179 }
180 llvm_unreachable("Unknown debug format!");
181 }
182
setOptLevel(unsigned Level)183 void LTOCodeGenerator::setOptLevel(unsigned Level) {
184 OptLevel = Level;
185 switch (OptLevel) {
186 case 0:
187 CGOptLevel = CodeGenOpt::None;
188 break;
189 case 1:
190 CGOptLevel = CodeGenOpt::Less;
191 break;
192 case 2:
193 CGOptLevel = CodeGenOpt::Default;
194 break;
195 case 3:
196 CGOptLevel = CodeGenOpt::Aggressive;
197 break;
198 }
199 }
200
writeMergedModules(const char * Path)201 bool LTOCodeGenerator::writeMergedModules(const char *Path) {
202 if (!determineTarget())
203 return false;
204
205 // We always run the verifier once on the merged module.
206 verifyMergedModuleOnce();
207
208 // mark which symbols can not be internalized
209 applyScopeRestrictions();
210
211 // create output file
212 std::error_code EC;
213 tool_output_file Out(Path, EC, sys::fs::F_None);
214 if (EC) {
215 std::string ErrMsg = "could not open bitcode file for writing: ";
216 ErrMsg += Path;
217 emitError(ErrMsg);
218 return false;
219 }
220
221 // write bitcode to it
222 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
223 Out.os().close();
224
225 if (Out.os().has_error()) {
226 std::string ErrMsg = "could not write bitcode file: ";
227 ErrMsg += Path;
228 emitError(ErrMsg);
229 Out.os().clear_error();
230 return false;
231 }
232
233 Out.keep();
234 return true;
235 }
236
compileOptimizedToFile(const char ** Name)237 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
238 // make unique temp output file to put generated code
239 SmallString<128> Filename;
240 int FD;
241
242 const char *Extension =
243 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
244
245 std::error_code EC =
246 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
247 if (EC) {
248 emitError(EC.message());
249 return false;
250 }
251
252 // generate object file
253 tool_output_file objFile(Filename.c_str(), FD);
254
255 bool genResult = compileOptimized(&objFile.os());
256 objFile.os().close();
257 if (objFile.os().has_error()) {
258 objFile.os().clear_error();
259 sys::fs::remove(Twine(Filename));
260 return false;
261 }
262
263 objFile.keep();
264 if (!genResult) {
265 sys::fs::remove(Twine(Filename));
266 return false;
267 }
268
269 NativeObjectPath = Filename.c_str();
270 *Name = NativeObjectPath.c_str();
271 return true;
272 }
273
274 std::unique_ptr<MemoryBuffer>
compileOptimized()275 LTOCodeGenerator::compileOptimized() {
276 const char *name;
277 if (!compileOptimizedToFile(&name))
278 return nullptr;
279
280 // read .o file into memory buffer
281 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
282 MemoryBuffer::getFile(name, -1, false);
283 if (std::error_code EC = BufferOrErr.getError()) {
284 emitError(EC.message());
285 sys::fs::remove(NativeObjectPath);
286 return nullptr;
287 }
288
289 // remove temp files
290 sys::fs::remove(NativeObjectPath);
291
292 return std::move(*BufferOrErr);
293 }
294
compile_to_file(const char ** Name,bool DisableVerify,bool DisableInline,bool DisableGVNLoadPRE,bool DisableVectorization)295 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
296 bool DisableInline,
297 bool DisableGVNLoadPRE,
298 bool DisableVectorization) {
299 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
300 DisableVectorization))
301 return false;
302
303 return compileOptimizedToFile(Name);
304 }
305
306 std::unique_ptr<MemoryBuffer>
compile(bool DisableVerify,bool DisableInline,bool DisableGVNLoadPRE,bool DisableVectorization)307 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
308 bool DisableGVNLoadPRE, bool DisableVectorization) {
309 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
310 DisableVectorization))
311 return nullptr;
312
313 return compileOptimized();
314 }
315
determineTarget()316 bool LTOCodeGenerator::determineTarget() {
317 if (TargetMach)
318 return true;
319
320 TripleStr = MergedModule->getTargetTriple();
321 if (TripleStr.empty()) {
322 TripleStr = sys::getDefaultTargetTriple();
323 MergedModule->setTargetTriple(TripleStr);
324 }
325 llvm::Triple Triple(TripleStr);
326
327 // create target machine from info for merged modules
328 std::string ErrMsg;
329 MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
330 if (!MArch) {
331 emitError(ErrMsg);
332 return false;
333 }
334
335 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
336 // the default set of features.
337 SubtargetFeatures Features(MAttr);
338 Features.getDefaultSubtargetFeatures(Triple);
339 FeatureStr = Features.getString();
340 // Set a default CPU for Darwin triples.
341 if (MCpu.empty() && Triple.isOSDarwin()) {
342 if (Triple.getArch() == llvm::Triple::x86_64)
343 MCpu = "core2";
344 else if (Triple.getArch() == llvm::Triple::x86)
345 MCpu = "yonah";
346 else if (Triple.getArch() == llvm::Triple::aarch64)
347 MCpu = "cyclone";
348 }
349
350 TargetMach = createTargetMachine();
351 return true;
352 }
353
createTargetMachine()354 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
355 return std::unique_ptr<TargetMachine>(
356 MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
357 RelocModel, CodeModel::Default, CGOptLevel));
358 }
359
360 // If a linkonce global is present in the MustPreserveSymbols, we need to make
361 // sure we honor this. To force the compiler to not drop it, we add it to the
362 // "llvm.compiler.used" global.
preserveDiscardableGVs(Module & TheModule,llvm::function_ref<bool (const GlobalValue &)> mustPreserveGV)363 void LTOCodeGenerator::preserveDiscardableGVs(
364 Module &TheModule,
365 llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
366 SetVector<Constant *> UsedValuesSet;
367 if (GlobalVariable *LLVMUsed =
368 TheModule.getGlobalVariable("llvm.compiler.used")) {
369 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
370 for (auto &V : Inits->operands())
371 UsedValuesSet.insert(cast<Constant>(&V));
372 LLVMUsed->eraseFromParent();
373 }
374 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(TheModule.getContext());
375 auto mayPreserveGlobal = [&](GlobalValue &GV) {
376 if (!GV.isDiscardableIfUnused() || GV.isDeclaration())
377 return;
378 if (!mustPreserveGV(GV))
379 return;
380 if (GV.hasAvailableExternallyLinkage()) {
381 emitWarning(
382 (Twine("Linker asked to preserve available_externally global: '") +
383 GV.getName() + "'").str());
384 return;
385 }
386 if (GV.hasInternalLinkage()) {
387 emitWarning((Twine("Linker asked to preserve internal global: '") +
388 GV.getName() + "'").str());
389 return;
390 }
391 UsedValuesSet.insert(ConstantExpr::getBitCast(&GV, i8PTy));
392 };
393 for (auto &GV : TheModule)
394 mayPreserveGlobal(GV);
395 for (auto &GV : TheModule.globals())
396 mayPreserveGlobal(GV);
397 for (auto &GV : TheModule.aliases())
398 mayPreserveGlobal(GV);
399
400 if (UsedValuesSet.empty())
401 return;
402
403 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedValuesSet.size());
404 auto *LLVMUsed = new llvm::GlobalVariable(
405 TheModule, ATy, false, llvm::GlobalValue::AppendingLinkage,
406 llvm::ConstantArray::get(ATy, UsedValuesSet.getArrayRef()),
407 "llvm.compiler.used");
408 LLVMUsed->setSection("llvm.metadata");
409 }
410
applyScopeRestrictions()411 void LTOCodeGenerator::applyScopeRestrictions() {
412 if (ScopeRestrictionsDone)
413 return;
414
415 // Declare a callback for the internalize pass that will ask for every
416 // candidate GlobalValue if it can be internalized or not.
417 SmallString<64> MangledName;
418 auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
419 // Unnamed globals can't be mangled, but they can't be preserved either.
420 if (!GV.hasName())
421 return false;
422
423 // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
424 // with the linker supplied name, which on Darwin includes a leading
425 // underscore.
426 MangledName.clear();
427 MangledName.reserve(GV.getName().size() + 1);
428 Mangler::getNameWithPrefix(MangledName, GV.getName(),
429 MergedModule->getDataLayout());
430 return MustPreserveSymbols.count(MangledName);
431 };
432
433 // Preserve linkonce value on linker request
434 preserveDiscardableGVs(*MergedModule, mustPreserveGV);
435
436 if (!ShouldInternalize)
437 return;
438
439 if (ShouldRestoreGlobalsLinkage) {
440 // Record the linkage type of non-local symbols so they can be restored
441 // prior
442 // to module splitting.
443 auto RecordLinkage = [&](const GlobalValue &GV) {
444 if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
445 GV.hasName())
446 ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
447 };
448 for (auto &GV : *MergedModule)
449 RecordLinkage(GV);
450 for (auto &GV : MergedModule->globals())
451 RecordLinkage(GV);
452 for (auto &GV : MergedModule->aliases())
453 RecordLinkage(GV);
454 }
455
456 // Update the llvm.compiler_used globals to force preserving libcalls and
457 // symbols referenced from asm
458 updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
459
460 internalizeModule(*MergedModule, mustPreserveGV);
461
462 ScopeRestrictionsDone = true;
463 }
464
465 /// Restore original linkage for symbols that may have been internalized
restoreLinkageForExternals()466 void LTOCodeGenerator::restoreLinkageForExternals() {
467 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
468 return;
469
470 assert(ScopeRestrictionsDone &&
471 "Cannot externalize without internalization!");
472
473 if (ExternalSymbols.empty())
474 return;
475
476 auto externalize = [this](GlobalValue &GV) {
477 if (!GV.hasLocalLinkage() || !GV.hasName())
478 return;
479
480 auto I = ExternalSymbols.find(GV.getName());
481 if (I == ExternalSymbols.end())
482 return;
483
484 GV.setLinkage(I->second);
485 };
486
487 std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
488 std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
489 externalize);
490 std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
491 externalize);
492 }
493
verifyMergedModuleOnce()494 void LTOCodeGenerator::verifyMergedModuleOnce() {
495 // Only run on the first call.
496 if (HasVerifiedInput)
497 return;
498 HasVerifiedInput = true;
499
500 if (LTOStripInvalidDebugInfo) {
501 bool BrokenDebugInfo = false;
502 if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
503 report_fatal_error("Broken module found, compilation aborted!");
504 if (BrokenDebugInfo) {
505 emitWarning("Invalid debug info found, debug info will be stripped");
506 StripDebugInfo(*MergedModule);
507 }
508 }
509 if (verifyModule(*MergedModule, &dbgs()))
510 report_fatal_error("Broken module found, compilation aborted!");
511 }
512
513 /// Optimize merged modules using various IPO passes
optimize(bool DisableVerify,bool DisableInline,bool DisableGVNLoadPRE,bool DisableVectorization)514 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
515 bool DisableGVNLoadPRE,
516 bool DisableVectorization) {
517 if (!this->determineTarget())
518 return false;
519
520 // We always run the verifier once on the merged module, the `DisableVerify`
521 // parameter only applies to subsequent verify.
522 verifyMergedModuleOnce();
523
524 // Mark which symbols can not be internalized
525 this->applyScopeRestrictions();
526
527 // Instantiate the pass manager to organize the passes.
528 legacy::PassManager passes;
529
530 // Add an appropriate DataLayout instance for this module...
531 MergedModule->setDataLayout(TargetMach->createDataLayout());
532
533 passes.add(
534 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
535
536 Triple TargetTriple(TargetMach->getTargetTriple());
537 PassManagerBuilder PMB;
538 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
539 PMB.LoopVectorize = !DisableVectorization;
540 PMB.SLPVectorize = !DisableVectorization;
541 if (!DisableInline)
542 PMB.Inliner = createFunctionInliningPass();
543 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
544 PMB.OptLevel = OptLevel;
545 PMB.VerifyInput = !DisableVerify;
546 PMB.VerifyOutput = !DisableVerify;
547
548 PMB.populateLTOPassManager(passes);
549
550 // Run our queue of passes all at once now, efficiently.
551 passes.run(*MergedModule);
552
553 return true;
554 }
555
compileOptimized(ArrayRef<raw_pwrite_stream * > Out)556 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
557 if (!this->determineTarget())
558 return false;
559
560 // We always run the verifier once on the merged module. If it has already
561 // been called in optimize(), this call will return early.
562 verifyMergedModuleOnce();
563
564 legacy::PassManager preCodeGenPasses;
565
566 // If the bitcode files contain ARC code and were compiled with optimization,
567 // the ObjCARCContractPass must be run, so do it unconditionally here.
568 preCodeGenPasses.add(createObjCARCContractPass());
569 preCodeGenPasses.run(*MergedModule);
570
571 // Re-externalize globals that may have been internalized to increase scope
572 // for splitting
573 restoreLinkageForExternals();
574
575 // Do code generation. We need to preserve the module in case the client calls
576 // writeMergedModules() after compilation, but we only need to allow this at
577 // parallelism level 1. This is achieved by having splitCodeGen return the
578 // original module at parallelism level 1 which we then assign back to
579 // MergedModule.
580 MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
581 [&]() { return createTargetMachine(); }, FileType,
582 ShouldRestoreGlobalsLinkage);
583
584 // If statistics were requested, print them out after codegen.
585 if (llvm::AreStatisticsEnabled())
586 llvm::PrintStatistics();
587
588 return true;
589 }
590
591 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
592 /// LTO problems.
setCodeGenDebugOptions(const char * Options)593 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
594 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
595 o = getToken(o.second))
596 CodegenOptions.push_back(o.first);
597 }
598
parseCodeGenDebugOptions()599 void LTOCodeGenerator::parseCodeGenDebugOptions() {
600 // if options were requested, set them
601 if (!CodegenOptions.empty()) {
602 // ParseCommandLineOptions() expects argv[0] to be program name.
603 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
604 for (std::string &Arg : CodegenOptions)
605 CodegenArgv.push_back(Arg.c_str());
606 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
607 }
608 }
609
DiagnosticHandler(const DiagnosticInfo & DI,void * Context)610 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
611 void *Context) {
612 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
613 }
614
DiagnosticHandler2(const DiagnosticInfo & DI)615 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
616 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
617 lto_codegen_diagnostic_severity_t Severity;
618 switch (DI.getSeverity()) {
619 case DS_Error:
620 Severity = LTO_DS_ERROR;
621 break;
622 case DS_Warning:
623 Severity = LTO_DS_WARNING;
624 break;
625 case DS_Remark:
626 Severity = LTO_DS_REMARK;
627 break;
628 case DS_Note:
629 Severity = LTO_DS_NOTE;
630 break;
631 }
632 // Create the string that will be reported to the external diagnostic handler.
633 std::string MsgStorage;
634 raw_string_ostream Stream(MsgStorage);
635 DiagnosticPrinterRawOStream DP(Stream);
636 DI.print(DP);
637 Stream.flush();
638
639 // If this method has been called it means someone has set up an external
640 // diagnostic handler. Assert on that.
641 assert(DiagHandler && "Invalid diagnostic handler");
642 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
643 }
644
645 void
setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,void * Ctxt)646 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
647 void *Ctxt) {
648 this->DiagHandler = DiagHandler;
649 this->DiagContext = Ctxt;
650 if (!DiagHandler)
651 return Context.setDiagnosticHandler(nullptr, nullptr);
652 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
653 // diagnostic to the external DiagHandler.
654 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
655 /* RespectFilters */ true);
656 }
657
658 namespace {
659 class LTODiagnosticInfo : public DiagnosticInfo {
660 const Twine &Msg;
661 public:
LTODiagnosticInfo(const Twine & DiagMsg,DiagnosticSeverity Severity=DS_Error)662 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
663 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
print(DiagnosticPrinter & DP) const664 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
665 };
666 }
667
emitError(const std::string & ErrMsg)668 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
669 if (DiagHandler)
670 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
671 else
672 Context.diagnose(LTODiagnosticInfo(ErrMsg));
673 }
674
emitWarning(const std::string & ErrMsg)675 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
676 if (DiagHandler)
677 (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
678 else
679 Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
680 }
681