blob: d2f964e4d246fd14a00a83b87130772642ad63fc [file] [log] [blame]
Nick Kledzik07b4a622008-02-26 20:26:43 +00001//===-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.
Bill Wendling39d942b2012-03-31 10:50:14 +00007//
Nick Kledzik07b4a622008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Bill Wendling39d942b2012-03-31 10:50:14 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik07b4a622008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne5c732202016-07-14 21:21:16 +000015#include "llvm/LTO/legacy/LTOCodeGenerator.h"
Mehdi Aminif59f2bb12016-04-12 06:34:10 +000016
Adam Nemet106feda2016-02-16 21:41:51 +000017#include "llvm/ADT/Statistic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ADT/StringExtras.h"
Nick Lewycky510dae32009-06-17 06:52:10 +000019#include "llvm/Analysis/Passes.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth93dcdc42015-01-31 11:17:59 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000022#include "llvm/Bitcode/BitcodeWriter.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000023#include "llvm/CodeGen/ParallelCG.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000024#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000025#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
Adrian Prantlfe7a3822016-05-09 19:57:15 +000028#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000030#include "llvm/IR/DiagnosticInfo.h"
31#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000033#include "llvm/IR/LegacyPassManager.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000034#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000037#include "llvm/InitializePasses.h"
Peter Collingbourne5c732202016-07-14 21:21:16 +000038#include "llvm/LTO/legacy/LTOModule.h"
39#include "llvm/LTO/legacy/UpdateCompilerUsed.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000040#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000041#include "llvm/MC/MCAsmInfo.h"
42#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000043#include "llvm/MC/SubtargetFeature.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000044#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000045#include "llvm/Support/FileSystem.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000046#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000047#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000048#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000049#include "llvm/Support/TargetRegistry.h"
50#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000051#include "llvm/Support/ToolOutputFile.h"
Adam Nemete9bd0222016-11-18 18:06:28 +000052#include "llvm/Support/YAMLTraits.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000053#include "llvm/Support/raw_ostream.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000054#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000055#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000056#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000057#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000058#include "llvm/Transforms/IPO.h"
Mehdi Aminice23e972016-04-13 06:32:46 +000059#include "llvm/Transforms/IPO/Internalize.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000060#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000061#include "llvm/Transforms/ObjCARC.h"
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +000062#include "llvm/Transforms/Utils/ModuleUtils.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000063#include <system_error>
Shuxin Yang76d082b2013-08-12 18:29:43 +000064using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000065
Bill Wendling534a6582012-03-31 10:49:43 +000066const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000067#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000068 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000069#else
Bill Wendling534a6582012-03-31 10:49:43 +000070 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000071#endif
72}
73
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000074namespace llvm {
75cl::opt<bool> LTODiscardValueNames(
Mehdi Amini1592cb92016-03-10 17:06:52 +000076 "lto-discard-value-names",
77 cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000078#ifdef NDEBUG
79 cl::init(true),
80#else
81 cl::init(false),
82#endif
83 cl::Hidden);
Adrian Prantlfe7a3822016-05-09 19:57:15 +000084
85cl::opt<bool> LTOStripInvalidDebugInfo(
86 "lto-strip-invalid-debug-info",
87 cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
88#ifdef NDEBUG
89 cl::init(true),
90#else
91 cl::init(false),
92#endif
93 cl::Hidden);
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000094}
95
Adam Nemete9bd0222016-11-18 18:06:28 +000096static cl::opt<std::string>
97 RemarksFilename("pass-remarks-output",
98 cl::desc("Output filename for pass remarks"),
99 cl::value_desc("filename"));
100
Rafael Espindola7b8a24e2015-12-04 02:42:28 +0000101LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
Rafael Espindolaf49a38f2015-12-04 22:08:53 +0000102 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
Teresa Johnsonbef54362015-12-18 19:28:59 +0000103 TheLinker(new Linker(*MergedModule)) {
Mehdi Amini09b4a8d2016-03-10 01:28:54 +0000104 Context.setDiscardValueNames(LTODiscardValueNames);
Duncan P. N. Exon Smithed8fdb22016-04-19 04:55:25 +0000105 Context.enableDebugTypeODRUniquing();
Duncan P. N. Exon Smith7832e0a2015-04-27 23:19:26 +0000106 initializeLTOPasses();
Duncan P. N. Exon Smithde5e32b2014-11-11 23:03:29 +0000107}
108
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000109LTOCodeGenerator::~LTOCodeGenerator() {}
Nick Kledzik07b4a622008-02-26 20:26:43 +0000110
Yaron Keren55f5c3d2015-09-01 10:13:49 +0000111// Initialize LTO passes. Please keep this function in sync with
Shuxin Yangca760852013-07-23 06:44:34 +0000112// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000113// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000114void LTOCodeGenerator::initializeLTOPasses() {
115 PassRegistry &R = *PassRegistry::getPassRegistry();
116
Justin Bogner4563a062016-04-26 20:15:52 +0000117 initializeInternalizeLegacyPassPass(R);
Davide Italianof54f2f02016-05-05 21:05:36 +0000118 initializeIPSCCPLegacyPassPass(R);
Justin Bogner1a075012016-04-26 00:28:01 +0000119 initializeGlobalOptLegacyPassPass(R);
Davide Italiano164b9bc2016-05-05 00:51:09 +0000120 initializeConstantMergeLegacyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000121 initializeDAHPass(R);
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000122 initializeInstructionCombiningPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000123 initializeSimpleInlinerPass(R);
124 initializePruneEHPass(R);
Davide Italiano66228c42016-05-03 19:39:15 +0000125 initializeGlobalDCELegacyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000126 initializeArgPromotionPass(R);
127 initializeJumpThreadingPass(R);
Chandler Carruth29a18a42015-09-12 09:09:14 +0000128 initializeSROALegacyPassPass(R);
Chandler Carruth9c4ed172016-02-18 11:03:11 +0000129 initializePostOrderFunctionAttrsLegacyPassPass(R);
Sean Silvaf5080192016-06-12 07:48:51 +0000130 initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000131 initializeGlobalsAAWrapperPassPass(R);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000132 initializeLegacyLICMPassPass(R);
Davide Italianob49aa5c2016-06-17 19:10:09 +0000133 initializeMergedLoadStoreMotionLegacyPassPass(R);
Chandler Carruth89c45a12016-03-11 08:50:55 +0000134 initializeGVNLegacyPassPass(R);
Sean Silva6347df02016-06-14 02:44:55 +0000135 initializeMemCpyOptLegacyPassPass(R);
Justin Bogner395c2122016-04-22 19:40:41 +0000136 initializeDCELegacyPassPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000137 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000138}
139
Davide Italianofc4430e2016-08-23 12:32:57 +0000140void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
Mehdi Aminidc5a5072016-10-07 19:05:14 +0000141 const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
Davide Italianofc4430e2016-08-23 12:32:57 +0000142 for (int i = 0, e = undefs.size(); i != e; ++i)
143 AsmUndefinedRefs[undefs[i]] = 1;
144}
145
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000146bool LTOCodeGenerator::addModule(LTOModule *Mod) {
147 assert(&Mod->getModule().getContext() == &Context &&
Duncan P. N. Exon Smith94198632014-11-11 23:13:10 +0000148 "Expected module in same context");
149
Teresa Johnsonbef54362015-12-18 19:28:59 +0000150 bool ret = TheLinker->linkInModule(Mod->takeModule());
Davide Italianofc4430e2016-08-23 12:32:57 +0000151 setAsmUndefinedRefs(Mod);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000152
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000153 // We've just changed the input, so let's make sure we verify it.
154 HasVerifiedInput = false;
155
Shuxin Yangb6696a92013-08-07 05:19:23 +0000156 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000157}
Bill Wendling39d942b2012-03-31 10:50:14 +0000158
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000159void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
Manman Ren6487ce92015-02-24 00:45:56 +0000160 assert(&Mod->getModule().getContext() == &Context &&
161 "Expected module in same context");
162
Manman Ren6487ce92015-02-24 00:45:56 +0000163 AsmUndefinedRefs.clear();
164
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000165 MergedModule = Mod->takeModule();
Teresa Johnsonbef54362015-12-18 19:28:59 +0000166 TheLinker = make_unique<Linker>(*MergedModule);
Davide Italianofc4430e2016-08-23 12:32:57 +0000167 setAsmUndefinedRefs(&*Mod);
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000168
169 // We've just changed the input, so let's make sure we verify it.
170 HasVerifiedInput = false;
Manman Ren6487ce92015-02-24 00:45:56 +0000171}
172
Benjamin Kramerc321e532016-06-08 19:09:22 +0000173void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000174 this->Options = Options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000175}
176
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000177void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
178 switch (Debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000179 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000180 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000181 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000182
Bill Wendling0e1824c2012-03-31 11:15:43 +0000183 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000184 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000185 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000186 }
187 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000188}
189
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000190void LTOCodeGenerator::setOptLevel(unsigned Level) {
191 OptLevel = Level;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000192 switch (OptLevel) {
193 case 0:
194 CGOptLevel = CodeGenOpt::None;
Davide Italianof8014f82016-08-26 15:22:59 +0000195 return;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000196 case 1:
197 CGOptLevel = CodeGenOpt::Less;
Davide Italianof8014f82016-08-26 15:22:59 +0000198 return;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000199 case 2:
200 CGOptLevel = CodeGenOpt::Default;
Davide Italianof8014f82016-08-26 15:22:59 +0000201 return;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000202 case 3:
203 CGOptLevel = CodeGenOpt::Aggressive;
Davide Italianof8014f82016-08-26 15:22:59 +0000204 return;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000205 }
Davide Italianof8014f82016-08-26 15:22:59 +0000206 llvm_unreachable("Unknown optimization level!");
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000207}
208
Mehdi Amini4cc259a2016-10-01 01:18:23 +0000209bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000210 if (!determineTarget())
Shuxin Yangb6696a92013-08-07 05:19:23 +0000211 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000212
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000213 // We always run the verifier once on the merged module.
214 verifyMergedModuleOnce();
215
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000216 // mark which symbols can not be internalized
217 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000218
Chris Lattner69733952009-08-23 07:49:08 +0000219 // create output file
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000220 std::error_code EC;
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000221 tool_output_file Out(Path, EC, sys::fs::F_None);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000222 if (EC) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000223 std::string ErrMsg = "could not open bitcode file for writing: ";
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000224 ErrMsg += Path;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000225 emitError(ErrMsg);
Shuxin Yangb6696a92013-08-07 05:19:23 +0000226 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000227 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000228
Chris Lattner69733952009-08-23 07:49:08 +0000229 // write bitcode to it
Mehdi Aminic7b95012016-04-27 05:11:44 +0000230 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
Dan Gohmana2233f22010-09-01 14:20:41 +0000231 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000232
Dan Gohmana2233f22010-09-01 14:20:41 +0000233 if (Out.os().has_error()) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000234 std::string ErrMsg = "could not write bitcode file: ";
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000235 ErrMsg += Path;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000236 emitError(ErrMsg);
Dan Gohmana2233f22010-09-01 14:20:41 +0000237 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000238 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000239 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000240
Dan Gohman8525fe72010-08-20 16:59:15 +0000241 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000242 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000243}
244
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000245bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000246 // make unique temp output file to put generated code
Shuxin Yang1826ae22013-08-12 21:07:31 +0000247 SmallString<128> Filename;
248 int FD;
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000249
Mehdi Amini4cc259a2016-10-01 01:18:23 +0000250 StringRef Extension
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000251 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
252
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000253 std::error_code EC =
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000254 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000255 if (EC) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000256 emitError(EC.message());
Shuxin Yangb6696a92013-08-07 05:19:23 +0000257 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000258 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000259
Shuxin Yang1826ae22013-08-12 21:07:31 +0000260 // generate object file
Mehdi Amini4cc259a2016-10-01 01:18:23 +0000261 tool_output_file objFile(Filename, FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000262
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000263 bool genResult = compileOptimized(&objFile.os());
Shuxin Yang1826ae22013-08-12 21:07:31 +0000264 objFile.os().close();
265 if (objFile.os().has_error()) {
Eli Friedman06025cf2016-11-08 19:43:56 +0000266 emitError((Twine("could not write object file: ") + Filename).str());
Shuxin Yang1826ae22013-08-12 21:07:31 +0000267 objFile.os().clear_error();
268 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000269 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000270 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000271
Shuxin Yang1826ae22013-08-12 21:07:31 +0000272 objFile.keep();
273 if (!genResult) {
274 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000275 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000276 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000277
Rafael Espindolac80c9692013-09-04 17:44:24 +0000278 NativeObjectPath = Filename.c_str();
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000279 *Name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000280 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000281}
282
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000283std::unique_ptr<MemoryBuffer>
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000284LTOCodeGenerator::compileOptimized() {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000285 const char *name;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000286 if (!compileOptimizedToFile(&name))
Craig Topper2617dcc2014-04-15 06:32:26 +0000287 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000288
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000289 // read .o file into memory buffer
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000290 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
291 MemoryBuffer::getFile(name, -1, false);
292 if (std::error_code EC = BufferOrErr.getError()) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000293 emitError(EC.message());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000294 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000295 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000296 }
Rafael Espindolafac373c2011-02-24 21:04:06 +0000297
Shuxin Yang1826ae22013-08-12 21:07:31 +0000298 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000299 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000300
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000301 return std::move(*BufferOrErr);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000302}
303
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000304bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
305 bool DisableInline,
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000306 bool DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000307 bool DisableVectorization) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000308 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000309 DisableVectorization))
Manman Ren8121e1d2015-02-03 18:39:15 +0000310 return false;
311
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000312 return compileOptimizedToFile(Name);
Manman Ren8121e1d2015-02-03 18:39:15 +0000313}
314
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000315std::unique_ptr<MemoryBuffer>
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000316LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000317 bool DisableGVNLoadPRE, bool DisableVectorization) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000318 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000319 DisableVectorization))
Manman Ren8121e1d2015-02-03 18:39:15 +0000320 return nullptr;
321
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000322 return compileOptimized();
Manman Ren8121e1d2015-02-03 18:39:15 +0000323}
324
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000325bool LTOCodeGenerator::determineTarget() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000326 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000327 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000328
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000329 TripleStr = MergedModule->getTargetTriple();
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000330 if (TripleStr.empty()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000331 TripleStr = sys::getDefaultTargetTriple();
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000332 MergedModule->setTargetTriple(TripleStr);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000333 }
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000334 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000335
Bill Wendling45f74e32012-08-06 22:52:45 +0000336 // create target machine from info for merged modules
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000337 std::string ErrMsg;
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000338 MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
339 if (!MArch) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000340 emitError(ErrMsg);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000341 return false;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000342 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000343
Tom Roederfd1bc602014-04-25 21:46:51 +0000344 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
345 // the default set of features.
346 SubtargetFeatures Features(MAttr);
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000347 Features.getDefaultSubtargetFeatures(Triple);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000348 FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000349 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000350 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000351 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000352 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000353 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000354 MCpu = "yonah";
Tim Northovere19bed72014-07-23 12:32:47 +0000355 else if (Triple.getArch() == llvm::Triple::aarch64)
Tim Northover00ed9962014-03-29 10:18:08 +0000356 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000357 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000358
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000359 TargetMach = createTargetMachine();
Shuxin Yang95866fa2013-08-06 21:51:21 +0000360 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000361}
362
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000363std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
364 return std::unique_ptr<TargetMachine>(
365 MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
366 RelocModel, CodeModel::Default, CGOptLevel));
367}
368
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000369// If a linkonce global is present in the MustPreserveSymbols, we need to make
370// sure we honor this. To force the compiler to not drop it, we add it to the
371// "llvm.compiler.used" global.
Mehdi Amini8eb33972016-05-05 20:05:33 +0000372void LTOCodeGenerator::preserveDiscardableGVs(
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000373 Module &TheModule,
374 llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000375 std::vector<GlobalValue *> Used;
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000376 auto mayPreserveGlobal = [&](GlobalValue &GV) {
Davide Italiano41bfd6b2016-09-02 16:37:31 +0000377 if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000378 !mustPreserveGV(GV))
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000379 return;
Davide Italiano41bfd6b2016-09-02 16:37:31 +0000380 if (GV.hasAvailableExternallyLinkage())
381 return emitWarning(
Mehdi Amini8eb33972016-05-05 20:05:33 +0000382 (Twine("Linker asked to preserve available_externally global: '") +
383 GV.getName() + "'").str());
Davide Italiano41bfd6b2016-09-02 16:37:31 +0000384 if (GV.hasInternalLinkage())
385 return emitWarning((Twine("Linker asked to preserve internal global: '") +
Mehdi Amini8eb33972016-05-05 20:05:33 +0000386 GV.getName() + "'").str());
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000387 Used.push_back(&GV);
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000388 };
389 for (auto &GV : TheModule)
390 mayPreserveGlobal(GV);
391 for (auto &GV : TheModule.globals())
392 mayPreserveGlobal(GV);
393 for (auto &GV : TheModule.aliases())
394 mayPreserveGlobal(GV);
395
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000396 if (Used.empty())
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000397 return;
398
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000399 appendToCompilerUsed(TheModule, Used);
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000400}
401
Chris Lattner2eff5052010-03-12 18:44:54 +0000402void LTOCodeGenerator::applyScopeRestrictions() {
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000403 if (ScopeRestrictionsDone)
404 return;
405
406 // Declare a callback for the internalize pass that will ask for every
407 // candidate GlobalValue if it can be internalized or not.
Peter Collingbourne46aafc12016-10-12 20:12:19 +0000408 Mangler Mang;
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000409 SmallString<64> MangledName;
410 auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
411 // Unnamed globals can't be mangled, but they can't be preserved either.
412 if (!GV.hasName())
413 return false;
414
415 // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
416 // with the linker supplied name, which on Darwin includes a leading
417 // underscore.
418 MangledName.clear();
419 MangledName.reserve(GV.getName().size() + 1);
Peter Collingbourne46aafc12016-10-12 20:12:19 +0000420 Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000421 return MustPreserveSymbols.count(MangledName);
422 };
423
424 // Preserve linkonce value on linker request
425 preserveDiscardableGVs(*MergedModule, mustPreserveGV);
426
427 if (!ShouldInternalize)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000428 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000429
Mehdi Aminideee0032016-04-13 05:36:06 +0000430 if (ShouldRestoreGlobalsLinkage) {
431 // Record the linkage type of non-local symbols so they can be restored
Mehdi Amini752ffe92016-05-05 05:14:20 +0000432 // prior
433 // to module splitting.
Mehdi Aminideee0032016-04-13 05:36:06 +0000434 auto RecordLinkage = [&](const GlobalValue &GV) {
435 if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
436 GV.hasName())
437 ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
438 };
439 for (auto &GV : *MergedModule)
440 RecordLinkage(GV);
441 for (auto &GV : MergedModule->globals())
442 RecordLinkage(GV);
443 for (auto &GV : MergedModule->aliases())
444 RecordLinkage(GV);
445 }
446
Mehdi Aminice23e972016-04-13 06:32:46 +0000447 // Update the llvm.compiler_used globals to force preserving libcalls and
448 // symbols referenced from asm
Davide Italiano53d457c2016-06-22 19:50:42 +0000449 updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
Mehdi Aminice23e972016-04-13 06:32:46 +0000450
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000451 internalizeModule(*MergedModule, mustPreserveGV);
Bill Wendling39d942b2012-03-31 10:50:14 +0000452
Rafael Espindolac80c9692013-09-04 17:44:24 +0000453 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000454}
455
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000456/// Restore original linkage for symbols that may have been internalized
457void LTOCodeGenerator::restoreLinkageForExternals() {
458 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
459 return;
460
461 assert(ScopeRestrictionsDone &&
462 "Cannot externalize without internalization!");
463
464 if (ExternalSymbols.empty())
465 return;
466
467 auto externalize = [this](GlobalValue &GV) {
468 if (!GV.hasLocalLinkage() || !GV.hasName())
469 return;
470
471 auto I = ExternalSymbols.find(GV.getName());
472 if (I == ExternalSymbols.end())
473 return;
474
475 GV.setLinkage(I->second);
476 };
477
478 std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
479 std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
480 externalize);
481 std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
482 externalize);
483}
484
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000485void LTOCodeGenerator::verifyMergedModuleOnce() {
486 // Only run on the first call.
487 if (HasVerifiedInput)
488 return;
489 HasVerifiedInput = true;
490
Adrian Prantlfe7a3822016-05-09 19:57:15 +0000491 if (LTOStripInvalidDebugInfo) {
492 bool BrokenDebugInfo = false;
493 if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
494 report_fatal_error("Broken module found, compilation aborted!");
495 if (BrokenDebugInfo) {
496 emitWarning("Invalid debug info found, debug info will be stripped");
497 StripDebugInfo(*MergedModule);
498 }
499 }
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000500 if (verifyModule(*MergedModule, &dbgs()))
501 report_fatal_error("Broken module found, compilation aborted!");
502}
503
Adam Nemete9bd0222016-11-18 18:06:28 +0000504bool LTOCodeGenerator::setupOptimizationRemarks() {
505 if (RemarksFilename != "") {
506 std::error_code EC;
507 DiagnosticOutputFile = llvm::make_unique<tool_output_file>(
508 RemarksFilename, EC, sys::fs::F_None);
509 if (EC) {
510 emitError(EC.message());
511 return false;
512 }
513 Context.setDiagnosticsOutputFile(
514 new yaml::Output(DiagnosticOutputFile->os()));
515 }
516 return true;
517}
518
519void LTOCodeGenerator::finishOptimizationRemarks() {
520 if (DiagnosticOutputFile) {
521 DiagnosticOutputFile->keep();
522 // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
523 DiagnosticOutputFile->os().flush();
524 }
525}
526
Nick Kledzik07b4a622008-02-26 20:26:43 +0000527/// Optimize merged modules using various IPO passes
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000528bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
529 bool DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000530 bool DisableVectorization) {
531 if (!this->determineTarget())
Shuxin Yang95866fa2013-08-06 21:51:21 +0000532 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000533
Adam Nemete9bd0222016-11-18 18:06:28 +0000534 if (!setupOptimizationRemarks())
535 return false;
536
Mehdi Aminif59f2bb12016-04-12 06:34:10 +0000537 // We always run the verifier once on the merged module, the `DisableVerify`
538 // parameter only applies to subsequent verify.
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000539 verifyMergedModuleOnce();
Mehdi Aminif59f2bb12016-04-12 06:34:10 +0000540
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000541 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000542 this->applyScopeRestrictions();
543
Bill Wendling0e1824c2012-03-31 11:15:43 +0000544 // Instantiate the pass manager to organize the passes.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000545 legacy::PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000546
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000547 // Add an appropriate DataLayout instance for this module...
Peter Collingbournee34034c2015-08-24 21:15:35 +0000548 MergedModule->setDataLayout(TargetMach->createDataLayout());
Bill Wendling39d942b2012-03-31 10:50:14 +0000549
Chandler Carruth5ec2b1d2015-02-01 12:26:09 +0000550 passes.add(
551 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000552
Rafael Espindola216e0c02014-08-21 18:49:52 +0000553 Triple TargetTriple(TargetMach->getTargetTriple());
Rafael Espindola7cebf362014-08-21 20:03:44 +0000554 PassManagerBuilder PMB;
555 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000556 PMB.LoopVectorize = !DisableVectorization;
557 PMB.SLPVectorize = !DisableVectorization;
Rafael Espindola7cebf362014-08-21 20:03:44 +0000558 if (!DisableInline)
559 PMB.Inliner = createFunctionInliningPass();
Chandler Carruthc0291862015-01-24 02:06:09 +0000560 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
Peter Collingbourne070843d2015-03-19 22:01:00 +0000561 PMB.OptLevel = OptLevel;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000562 PMB.VerifyInput = !DisableVerify;
563 PMB.VerifyOutput = !DisableVerify;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000564
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000565 PMB.populateLTOPassManager(passes);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000566
Manman Ren8121e1d2015-02-03 18:39:15 +0000567 // Run our queue of passes all at once now, efficiently.
Peter Collingbournee34034c2015-08-24 21:15:35 +0000568 passes.run(*MergedModule);
Manman Ren8121e1d2015-02-03 18:39:15 +0000569
Adam Nemete9bd0222016-11-18 18:06:28 +0000570 finishOptimizationRemarks();
571
Manman Ren8121e1d2015-02-03 18:39:15 +0000572 return true;
573}
574
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000575bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
576 if (!this->determineTarget())
Manman Ren8121e1d2015-02-03 18:39:15 +0000577 return false;
578
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000579 // We always run the verifier once on the merged module. If it has already
580 // been called in optimize(), this call will return early.
581 verifyMergedModuleOnce();
582
Peter Collingbournec269ed52015-08-27 23:37:36 +0000583 legacy::PassManager preCodeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000584
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000585 // If the bitcode files contain ARC code and were compiled with optimization,
586 // the ObjCARCContractPass must be run, so do it unconditionally here.
Peter Collingbournec269ed52015-08-27 23:37:36 +0000587 preCodeGenPasses.add(createObjCARCContractPass());
588 preCodeGenPasses.run(*MergedModule);
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000589
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000590 // Re-externalize globals that may have been internalized to increase scope
591 // for splitting
592 restoreLinkageForExternals();
593
Peter Collingbournec269ed52015-08-27 23:37:36 +0000594 // Do code generation. We need to preserve the module in case the client calls
595 // writeMergedModules() after compilation, but we only need to allow this at
596 // parallelism level 1. This is achieved by having splitCodeGen return the
597 // original module at parallelism level 1 which we then assign back to
598 // MergedModule.
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000599 MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
600 [&]() { return createTargetMachine(); }, FileType,
601 ShouldRestoreGlobalsLinkage);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000602
Adam Nemet106feda2016-02-16 21:41:51 +0000603 // If statistics were requested, print them out after codegen.
604 if (llvm::AreStatisticsEnabled())
605 llvm::PrintStatistics();
606
Shuxin Yang95866fa2013-08-06 21:51:21 +0000607 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000608}
609
Bill Wendling534a6582012-03-31 10:49:43 +0000610/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
611/// LTO problems.
Mehdi Amini4cc259a2016-10-01 01:18:23 +0000612void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000613 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
614 o = getToken(o.second))
Peter Collingbourne22575122015-08-21 04:45:55 +0000615 CodegenOptions.push_back(o.first);
Nick Kledzikc2323472008-07-08 21:14:10 +0000616}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000617
618void LTOCodeGenerator::parseCodeGenDebugOptions() {
619 // if options were requested, set them
Peter Collingbourne22575122015-08-21 04:45:55 +0000620 if (!CodegenOptions.empty()) {
621 // ParseCommandLineOptions() expects argv[0] to be program name.
622 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
623 for (std::string &Arg : CodegenOptions)
624 CodegenArgv.push_back(Arg.c_str());
625 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
626 }
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000627}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000628
629void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
630 void *Context) {
631 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
632}
633
634void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
635 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
636 lto_codegen_diagnostic_severity_t Severity;
637 switch (DI.getSeverity()) {
638 case DS_Error:
639 Severity = LTO_DS_ERROR;
640 break;
641 case DS_Warning:
642 Severity = LTO_DS_WARNING;
643 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000644 case DS_Remark:
645 Severity = LTO_DS_REMARK;
646 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000647 case DS_Note:
648 Severity = LTO_DS_NOTE;
649 break;
650 }
651 // Create the string that will be reported to the external diagnostic handler.
Alp Tokere69170a2014-06-26 22:52:05 +0000652 std::string MsgStorage;
653 raw_string_ostream Stream(MsgStorage);
654 DiagnosticPrinterRawOStream DP(Stream);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000655 DI.print(DP);
Alp Tokere69170a2014-06-26 22:52:05 +0000656 Stream.flush();
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000657
658 // If this method has been called it means someone has set up an external
659 // diagnostic handler. Assert on that.
660 assert(DiagHandler && "Invalid diagnostic handler");
Alp Tokere69170a2014-06-26 22:52:05 +0000661 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000662}
663
664void
665LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
666 void *Ctxt) {
667 this->DiagHandler = DiagHandler;
668 this->DiagContext = Ctxt;
669 if (!DiagHandler)
Craig Topper2617dcc2014-04-15 06:32:26 +0000670 return Context.setDiagnosticHandler(nullptr, nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000671 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
672 // diagnostic to the external DiagHandler.
Duncan P. N. Exon Smithf02fe702014-10-02 21:11:04 +0000673 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
674 /* RespectFilters */ true);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000675}
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000676
677namespace {
678class LTODiagnosticInfo : public DiagnosticInfo {
679 const Twine &Msg;
680public:
681 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
682 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
683 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
684};
685}
686
687void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
688 if (DiagHandler)
689 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
690 else
691 Context.diagnose(LTODiagnosticInfo(ErrMsg));
692}
Mehdi Amini8eb33972016-05-05 20:05:33 +0000693
694void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
695 if (DiagHandler)
696 (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
697 else
698 Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
699}