blob: ee9c70126b83526cb4a83602791a10bfa6b0e79f [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"
Davide Italiano690ed9d2017-02-10 23:49:38 +000038#include "llvm/LTO/LTO.h"
Peter Collingbourne5c732202016-07-14 21:21:16 +000039#include "llvm/LTO/legacy/LTOModule.h"
40#include "llvm/LTO/legacy/UpdateCompilerUsed.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000041#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000042#include "llvm/MC/MCAsmInfo.h"
43#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000044#include "llvm/MC/SubtargetFeature.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000045#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000046#include "llvm/Support/FileSystem.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000047#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000048#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000049#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000050#include "llvm/Support/TargetRegistry.h"
51#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000052#include "llvm/Support/ToolOutputFile.h"
Adam Nemete9bd0222016-11-18 18:06:28 +000053#include "llvm/Support/YAMLTraits.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000054#include "llvm/Support/raw_ostream.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000055#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000056#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000057#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000058#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000059#include "llvm/Transforms/IPO.h"
Mehdi Aminice23e972016-04-13 06:32:46 +000060#include "llvm/Transforms/IPO/Internalize.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000061#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000062#include "llvm/Transforms/ObjCARC.h"
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +000063#include "llvm/Transforms/Utils/ModuleUtils.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000064#include <system_error>
Shuxin Yang76d082b2013-08-12 18:29:43 +000065using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000066
Bill Wendling534a6582012-03-31 10:49:43 +000067const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000068#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000069 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000070#else
Bill Wendling534a6582012-03-31 10:49:43 +000071 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000072#endif
73}
74
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000075namespace llvm {
76cl::opt<bool> LTODiscardValueNames(
Mehdi Amini1592cb92016-03-10 17:06:52 +000077 "lto-discard-value-names",
78 cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000079#ifdef NDEBUG
80 cl::init(true),
81#else
82 cl::init(false),
83#endif
84 cl::Hidden);
Adrian Prantlfe7a3822016-05-09 19:57:15 +000085
86cl::opt<bool> LTOStripInvalidDebugInfo(
87 "lto-strip-invalid-debug-info",
88 cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
89#ifdef NDEBUG
90 cl::init(true),
91#else
92 cl::init(false),
93#endif
94 cl::Hidden);
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000095
Mehdi Amini19f176b2016-11-19 18:20:05 +000096cl::opt<std::string>
Adam Nemetde336512016-11-22 07:35:14 +000097 LTORemarksFilename("lto-pass-remarks-output",
Mehdi Amini19f176b2016-11-19 18:20:05 +000098 cl::desc("Output filename for pass remarks"),
99 cl::value_desc("filename"));
Adam Nemet4c207a62016-12-02 17:53:56 +0000100
101cl::opt<bool> LTOPassRemarksWithHotness(
102 "lto-pass-remarks-with-hotness",
103 cl::desc("With PGO, include profile count in optimization remarks"),
104 cl::Hidden);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000105}
Adam Nemete9bd0222016-11-18 18:06:28 +0000106
Rafael Espindola7b8a24e2015-12-04 02:42:28 +0000107LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
Rafael Espindolaf49a38f2015-12-04 22:08:53 +0000108 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
Teresa Johnsonbef54362015-12-18 19:28:59 +0000109 TheLinker(new Linker(*MergedModule)) {
Mehdi Amini09b4a8d2016-03-10 01:28:54 +0000110 Context.setDiscardValueNames(LTODiscardValueNames);
Duncan P. N. Exon Smithed8fdb22016-04-19 04:55:25 +0000111 Context.enableDebugTypeODRUniquing();
Duncan P. N. Exon Smith7832e0a2015-04-27 23:19:26 +0000112 initializeLTOPasses();
Duncan P. N. Exon Smithde5e32b2014-11-11 23:03:29 +0000113}
114
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000115LTOCodeGenerator::~LTOCodeGenerator() {}
Nick Kledzik07b4a622008-02-26 20:26:43 +0000116
Yaron Keren55f5c3d2015-09-01 10:13:49 +0000117// Initialize LTO passes. Please keep this function in sync with
Shuxin Yangca760852013-07-23 06:44:34 +0000118// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000119// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000120void LTOCodeGenerator::initializeLTOPasses() {
121 PassRegistry &R = *PassRegistry::getPassRegistry();
122
Justin Bogner4563a062016-04-26 20:15:52 +0000123 initializeInternalizeLegacyPassPass(R);
Davide Italianof54f2f02016-05-05 21:05:36 +0000124 initializeIPSCCPLegacyPassPass(R);
Justin Bogner1a075012016-04-26 00:28:01 +0000125 initializeGlobalOptLegacyPassPass(R);
Davide Italiano164b9bc2016-05-05 00:51:09 +0000126 initializeConstantMergeLegacyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000127 initializeDAHPass(R);
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000128 initializeInstructionCombiningPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000129 initializeSimpleInlinerPass(R);
130 initializePruneEHPass(R);
Davide Italiano66228c42016-05-03 19:39:15 +0000131 initializeGlobalDCELegacyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000132 initializeArgPromotionPass(R);
133 initializeJumpThreadingPass(R);
Chandler Carruth29a18a42015-09-12 09:09:14 +0000134 initializeSROALegacyPassPass(R);
Chandler Carruth9c4ed172016-02-18 11:03:11 +0000135 initializePostOrderFunctionAttrsLegacyPassPass(R);
Sean Silvaf5080192016-06-12 07:48:51 +0000136 initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000137 initializeGlobalsAAWrapperPassPass(R);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000138 initializeLegacyLICMPassPass(R);
Davide Italianob49aa5c2016-06-17 19:10:09 +0000139 initializeMergedLoadStoreMotionLegacyPassPass(R);
Chandler Carruth89c45a12016-03-11 08:50:55 +0000140 initializeGVNLegacyPassPass(R);
Sean Silva6347df02016-06-14 02:44:55 +0000141 initializeMemCpyOptLegacyPassPass(R);
Justin Bogner395c2122016-04-22 19:40:41 +0000142 initializeDCELegacyPassPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000143 initializeCFGSimplifyPassPass(R);
Joerg Sonnenbergerfa736742017-03-26 06:44:08 +0000144 initializeLateCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000145}
146
Davide Italianofc4430e2016-08-23 12:32:57 +0000147void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
Mehdi Aminidc5a5072016-10-07 19:05:14 +0000148 const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
Davide Italianofc4430e2016-08-23 12:32:57 +0000149 for (int i = 0, e = undefs.size(); i != e; ++i)
150 AsmUndefinedRefs[undefs[i]] = 1;
151}
152
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000153bool LTOCodeGenerator::addModule(LTOModule *Mod) {
154 assert(&Mod->getModule().getContext() == &Context &&
Duncan P. N. Exon Smith94198632014-11-11 23:13:10 +0000155 "Expected module in same context");
156
Teresa Johnsonbef54362015-12-18 19:28:59 +0000157 bool ret = TheLinker->linkInModule(Mod->takeModule());
Davide Italianofc4430e2016-08-23 12:32:57 +0000158 setAsmUndefinedRefs(Mod);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000159
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000160 // We've just changed the input, so let's make sure we verify it.
161 HasVerifiedInput = false;
162
Shuxin Yangb6696a92013-08-07 05:19:23 +0000163 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000164}
Bill Wendling39d942b2012-03-31 10:50:14 +0000165
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000166void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
Manman Ren6487ce92015-02-24 00:45:56 +0000167 assert(&Mod->getModule().getContext() == &Context &&
168 "Expected module in same context");
169
Manman Ren6487ce92015-02-24 00:45:56 +0000170 AsmUndefinedRefs.clear();
171
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000172 MergedModule = Mod->takeModule();
Teresa Johnsonbef54362015-12-18 19:28:59 +0000173 TheLinker = make_unique<Linker>(*MergedModule);
Davide Italianofc4430e2016-08-23 12:32:57 +0000174 setAsmUndefinedRefs(&*Mod);
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000175
176 // We've just changed the input, so let's make sure we verify it.
177 HasVerifiedInput = false;
Manman Ren6487ce92015-02-24 00:45:56 +0000178}
179
Benjamin Kramerc321e532016-06-08 19:09:22 +0000180void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000181 this->Options = Options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000182}
183
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000184void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
185 switch (Debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000186 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000187 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000188 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000189
Bill Wendling0e1824c2012-03-31 11:15:43 +0000190 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000191 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000192 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000193 }
194 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000195}
196
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000197void LTOCodeGenerator::setOptLevel(unsigned Level) {
198 OptLevel = Level;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000199 switch (OptLevel) {
200 case 0:
201 CGOptLevel = CodeGenOpt::None;
Davide Italianof8014f82016-08-26 15:22:59 +0000202 return;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000203 case 1:
204 CGOptLevel = CodeGenOpt::Less;
Davide Italianof8014f82016-08-26 15:22:59 +0000205 return;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000206 case 2:
207 CGOptLevel = CodeGenOpt::Default;
Davide Italianof8014f82016-08-26 15:22:59 +0000208 return;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000209 case 3:
210 CGOptLevel = CodeGenOpt::Aggressive;
Davide Italianof8014f82016-08-26 15:22:59 +0000211 return;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000212 }
Davide Italianof8014f82016-08-26 15:22:59 +0000213 llvm_unreachable("Unknown optimization level!");
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000214}
215
Mehdi Amini4cc259a2016-10-01 01:18:23 +0000216bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000217 if (!determineTarget())
Shuxin Yangb6696a92013-08-07 05:19:23 +0000218 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000219
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000220 // We always run the verifier once on the merged module.
221 verifyMergedModuleOnce();
222
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000223 // mark which symbols can not be internalized
224 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000225
Chris Lattner69733952009-08-23 07:49:08 +0000226 // create output file
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000227 std::error_code EC;
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000228 tool_output_file Out(Path, EC, sys::fs::F_None);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000229 if (EC) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000230 std::string ErrMsg = "could not open bitcode file for writing: ";
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000231 ErrMsg += Path;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000232 emitError(ErrMsg);
Shuxin Yangb6696a92013-08-07 05:19:23 +0000233 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000234 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000235
Chris Lattner69733952009-08-23 07:49:08 +0000236 // write bitcode to it
Mehdi Aminic7b95012016-04-27 05:11:44 +0000237 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
Dan Gohmana2233f22010-09-01 14:20:41 +0000238 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000239
Dan Gohmana2233f22010-09-01 14:20:41 +0000240 if (Out.os().has_error()) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000241 std::string ErrMsg = "could not write bitcode file: ";
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000242 ErrMsg += Path;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000243 emitError(ErrMsg);
Dan Gohmana2233f22010-09-01 14:20:41 +0000244 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000245 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000246 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000247
Dan Gohman8525fe72010-08-20 16:59:15 +0000248 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000249 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000250}
251
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000252bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000253 // make unique temp output file to put generated code
Shuxin Yang1826ae22013-08-12 21:07:31 +0000254 SmallString<128> Filename;
255 int FD;
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000256
Mehdi Amini4cc259a2016-10-01 01:18:23 +0000257 StringRef Extension
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000258 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
259
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000260 std::error_code EC =
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000261 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000262 if (EC) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000263 emitError(EC.message());
Shuxin Yangb6696a92013-08-07 05:19:23 +0000264 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000265 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000266
Shuxin Yang1826ae22013-08-12 21:07:31 +0000267 // generate object file
Mehdi Amini4cc259a2016-10-01 01:18:23 +0000268 tool_output_file objFile(Filename, FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000269
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000270 bool genResult = compileOptimized(&objFile.os());
Shuxin Yang1826ae22013-08-12 21:07:31 +0000271 objFile.os().close();
272 if (objFile.os().has_error()) {
Eli Friedman06025cf2016-11-08 19:43:56 +0000273 emitError((Twine("could not write object file: ") + Filename).str());
Shuxin Yang1826ae22013-08-12 21:07:31 +0000274 objFile.os().clear_error();
275 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000276 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000277 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000278
Shuxin Yang1826ae22013-08-12 21:07:31 +0000279 objFile.keep();
280 if (!genResult) {
281 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000282 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000283 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000284
Rafael Espindolac80c9692013-09-04 17:44:24 +0000285 NativeObjectPath = Filename.c_str();
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000286 *Name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000287 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000288}
289
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000290std::unique_ptr<MemoryBuffer>
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000291LTOCodeGenerator::compileOptimized() {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000292 const char *name;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000293 if (!compileOptimizedToFile(&name))
Craig Topper2617dcc2014-04-15 06:32:26 +0000294 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000295
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000296 // read .o file into memory buffer
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000297 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
298 MemoryBuffer::getFile(name, -1, false);
299 if (std::error_code EC = BufferOrErr.getError()) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000300 emitError(EC.message());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000301 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000302 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000303 }
Rafael Espindolafac373c2011-02-24 21:04:06 +0000304
Shuxin Yang1826ae22013-08-12 21:07:31 +0000305 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000306 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000307
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000308 return std::move(*BufferOrErr);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000309}
310
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000311bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
312 bool DisableInline,
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000313 bool DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000314 bool DisableVectorization) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000315 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000316 DisableVectorization))
Manman Ren8121e1d2015-02-03 18:39:15 +0000317 return false;
318
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000319 return compileOptimizedToFile(Name);
Manman Ren8121e1d2015-02-03 18:39:15 +0000320}
321
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000322std::unique_ptr<MemoryBuffer>
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000323LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000324 bool DisableGVNLoadPRE, bool DisableVectorization) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000325 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000326 DisableVectorization))
Manman Ren8121e1d2015-02-03 18:39:15 +0000327 return nullptr;
328
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000329 return compileOptimized();
Manman Ren8121e1d2015-02-03 18:39:15 +0000330}
331
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000332bool LTOCodeGenerator::determineTarget() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000333 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000334 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000335
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000336 TripleStr = MergedModule->getTargetTriple();
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000337 if (TripleStr.empty()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000338 TripleStr = sys::getDefaultTargetTriple();
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000339 MergedModule->setTargetTriple(TripleStr);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000340 }
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000341 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000342
Bill Wendling45f74e32012-08-06 22:52:45 +0000343 // create target machine from info for merged modules
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000344 std::string ErrMsg;
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000345 MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
346 if (!MArch) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000347 emitError(ErrMsg);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000348 return false;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000349 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000350
Tom Roederfd1bc602014-04-25 21:46:51 +0000351 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
352 // the default set of features.
353 SubtargetFeatures Features(MAttr);
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000354 Features.getDefaultSubtargetFeatures(Triple);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000355 FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000356 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000357 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000358 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000359 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000360 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000361 MCpu = "yonah";
Tim Northovere19bed72014-07-23 12:32:47 +0000362 else if (Triple.getArch() == llvm::Triple::aarch64)
Tim Northover00ed9962014-03-29 10:18:08 +0000363 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000364 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000365
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000366 TargetMach = createTargetMachine();
Shuxin Yang95866fa2013-08-06 21:51:21 +0000367 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000368}
369
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000370std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
Rafael Espindola79e238a2017-08-03 02:16:21 +0000371 return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
372 TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000373}
374
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000375// If a linkonce global is present in the MustPreserveSymbols, we need to make
376// sure we honor this. To force the compiler to not drop it, we add it to the
377// "llvm.compiler.used" global.
Mehdi Amini8eb33972016-05-05 20:05:33 +0000378void LTOCodeGenerator::preserveDiscardableGVs(
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000379 Module &TheModule,
380 llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000381 std::vector<GlobalValue *> Used;
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000382 auto mayPreserveGlobal = [&](GlobalValue &GV) {
Davide Italiano41bfd6b2016-09-02 16:37:31 +0000383 if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000384 !mustPreserveGV(GV))
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000385 return;
Davide Italiano41bfd6b2016-09-02 16:37:31 +0000386 if (GV.hasAvailableExternallyLinkage())
387 return emitWarning(
Mehdi Amini8eb33972016-05-05 20:05:33 +0000388 (Twine("Linker asked to preserve available_externally global: '") +
389 GV.getName() + "'").str());
Davide Italiano41bfd6b2016-09-02 16:37:31 +0000390 if (GV.hasInternalLinkage())
391 return emitWarning((Twine("Linker asked to preserve internal global: '") +
Mehdi Amini8eb33972016-05-05 20:05:33 +0000392 GV.getName() + "'").str());
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000393 Used.push_back(&GV);
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000394 };
395 for (auto &GV : TheModule)
396 mayPreserveGlobal(GV);
397 for (auto &GV : TheModule.globals())
398 mayPreserveGlobal(GV);
399 for (auto &GV : TheModule.aliases())
400 mayPreserveGlobal(GV);
401
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000402 if (Used.empty())
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000403 return;
404
Evgeniy Stepanovea6d49d2016-10-25 23:53:31 +0000405 appendToCompilerUsed(TheModule, Used);
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000406}
407
Chris Lattner2eff5052010-03-12 18:44:54 +0000408void LTOCodeGenerator::applyScopeRestrictions() {
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000409 if (ScopeRestrictionsDone)
410 return;
411
412 // Declare a callback for the internalize pass that will ask for every
413 // candidate GlobalValue if it can be internalized or not.
Peter Collingbourne46aafc12016-10-12 20:12:19 +0000414 Mangler Mang;
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000415 SmallString<64> MangledName;
416 auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
417 // Unnamed globals can't be mangled, but they can't be preserved either.
418 if (!GV.hasName())
419 return false;
420
421 // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
422 // with the linker supplied name, which on Darwin includes a leading
423 // underscore.
424 MangledName.clear();
425 MangledName.reserve(GV.getName().size() + 1);
Peter Collingbourne46aafc12016-10-12 20:12:19 +0000426 Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000427 return MustPreserveSymbols.count(MangledName);
428 };
429
430 // Preserve linkonce value on linker request
431 preserveDiscardableGVs(*MergedModule, mustPreserveGV);
432
433 if (!ShouldInternalize)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000434 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000435
Mehdi Aminideee0032016-04-13 05:36:06 +0000436 if (ShouldRestoreGlobalsLinkage) {
437 // Record the linkage type of non-local symbols so they can be restored
Mehdi Amini752ffe92016-05-05 05:14:20 +0000438 // prior
439 // to module splitting.
Mehdi Aminideee0032016-04-13 05:36:06 +0000440 auto RecordLinkage = [&](const GlobalValue &GV) {
441 if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
442 GV.hasName())
443 ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
444 };
445 for (auto &GV : *MergedModule)
446 RecordLinkage(GV);
447 for (auto &GV : MergedModule->globals())
448 RecordLinkage(GV);
449 for (auto &GV : MergedModule->aliases())
450 RecordLinkage(GV);
451 }
452
Mehdi Aminice23e972016-04-13 06:32:46 +0000453 // Update the llvm.compiler_used globals to force preserving libcalls and
454 // symbols referenced from asm
Davide Italiano53d457c2016-06-22 19:50:42 +0000455 updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
Mehdi Aminice23e972016-04-13 06:32:46 +0000456
Mehdi Amini022b5bc2016-05-05 05:14:24 +0000457 internalizeModule(*MergedModule, mustPreserveGV);
Bill Wendling39d942b2012-03-31 10:50:14 +0000458
Rafael Espindolac80c9692013-09-04 17:44:24 +0000459 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000460}
461
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000462/// Restore original linkage for symbols that may have been internalized
463void LTOCodeGenerator::restoreLinkageForExternals() {
464 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
465 return;
466
467 assert(ScopeRestrictionsDone &&
468 "Cannot externalize without internalization!");
469
470 if (ExternalSymbols.empty())
471 return;
472
473 auto externalize = [this](GlobalValue &GV) {
474 if (!GV.hasLocalLinkage() || !GV.hasName())
475 return;
476
477 auto I = ExternalSymbols.find(GV.getName());
478 if (I == ExternalSymbols.end())
479 return;
480
481 GV.setLinkage(I->second);
482 };
483
484 std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
485 std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
486 externalize);
487 std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
488 externalize);
489}
490
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000491void LTOCodeGenerator::verifyMergedModuleOnce() {
492 // Only run on the first call.
493 if (HasVerifiedInput)
494 return;
495 HasVerifiedInput = true;
496
Adrian Prantl1fa362f2017-05-12 21:38:32 +0000497 bool BrokenDebugInfo = false;
498 if (verifyModule(*MergedModule, &dbgs(),
499 LTOStripInvalidDebugInfo ? &BrokenDebugInfo : nullptr))
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000500 report_fatal_error("Broken module found, compilation aborted!");
Adrian Prantl1fa362f2017-05-12 21:38:32 +0000501 if (BrokenDebugInfo) {
502 emitWarning("Invalid debug info found, debug info will be stripped");
503 StripDebugInfo(*MergedModule);
504 }
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000505}
506
Adam Nemete9bd0222016-11-18 18:06:28 +0000507void LTOCodeGenerator::finishOptimizationRemarks() {
508 if (DiagnosticOutputFile) {
509 DiagnosticOutputFile->keep();
510 // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
511 DiagnosticOutputFile->os().flush();
512 }
513}
514
Nick Kledzik07b4a622008-02-26 20:26:43 +0000515/// Optimize merged modules using various IPO passes
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000516bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
517 bool DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000518 bool DisableVectorization) {
519 if (!this->determineTarget())
Shuxin Yang95866fa2013-08-06 21:51:21 +0000520 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000521
Davide Italiano690ed9d2017-02-10 23:49:38 +0000522 auto DiagFileOrErr = lto::setupOptimizationRemarks(
523 Context, LTORemarksFilename, LTOPassRemarksWithHotness);
Davide Italiano46d72b12017-02-10 22:16:17 +0000524 if (!DiagFileOrErr) {
525 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
526 report_fatal_error("Can't get an output file for the remarks");
527 }
528 DiagnosticOutputFile = std::move(*DiagFileOrErr);
Adam Nemete9bd0222016-11-18 18:06:28 +0000529
Mehdi Aminif59f2bb12016-04-12 06:34:10 +0000530 // We always run the verifier once on the merged module, the `DisableVerify`
531 // parameter only applies to subsequent verify.
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000532 verifyMergedModuleOnce();
Mehdi Aminif59f2bb12016-04-12 06:34:10 +0000533
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000534 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000535 this->applyScopeRestrictions();
536
Bill Wendling0e1824c2012-03-31 11:15:43 +0000537 // Instantiate the pass manager to organize the passes.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000538 legacy::PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000539
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000540 // Add an appropriate DataLayout instance for this module...
Peter Collingbournee34034c2015-08-24 21:15:35 +0000541 MergedModule->setDataLayout(TargetMach->createDataLayout());
Bill Wendling39d942b2012-03-31 10:50:14 +0000542
Chandler Carruth5ec2b1d2015-02-01 12:26:09 +0000543 passes.add(
544 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000545
Rafael Espindola216e0c02014-08-21 18:49:52 +0000546 Triple TargetTriple(TargetMach->getTargetTriple());
Rafael Espindola7cebf362014-08-21 20:03:44 +0000547 PassManagerBuilder PMB;
548 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000549 PMB.LoopVectorize = !DisableVectorization;
550 PMB.SLPVectorize = !DisableVectorization;
Rafael Espindola7cebf362014-08-21 20:03:44 +0000551 if (!DisableInline)
552 PMB.Inliner = createFunctionInliningPass();
Chandler Carruthc0291862015-01-24 02:06:09 +0000553 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000554 if (Freestanding)
555 PMB.LibraryInfo->disableAllFunctions();
Peter Collingbourne070843d2015-03-19 22:01:00 +0000556 PMB.OptLevel = OptLevel;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000557 PMB.VerifyInput = !DisableVerify;
558 PMB.VerifyOutput = !DisableVerify;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000559
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000560 PMB.populateLTOPassManager(passes);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000561
Manman Ren8121e1d2015-02-03 18:39:15 +0000562 // Run our queue of passes all at once now, efficiently.
Peter Collingbournee34034c2015-08-24 21:15:35 +0000563 passes.run(*MergedModule);
Manman Ren8121e1d2015-02-03 18:39:15 +0000564
565 return true;
566}
567
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000568bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
569 if (!this->determineTarget())
Manman Ren8121e1d2015-02-03 18:39:15 +0000570 return false;
571
Duncan P. N. Exon Smithb011ad72016-04-20 17:48:22 +0000572 // We always run the verifier once on the merged module. If it has already
573 // been called in optimize(), this call will return early.
574 verifyMergedModuleOnce();
575
Peter Collingbournec269ed52015-08-27 23:37:36 +0000576 legacy::PassManager preCodeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000577
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000578 // If the bitcode files contain ARC code and were compiled with optimization,
579 // the ObjCARCContractPass must be run, so do it unconditionally here.
Peter Collingbournec269ed52015-08-27 23:37:36 +0000580 preCodeGenPasses.add(createObjCARCContractPass());
581 preCodeGenPasses.run(*MergedModule);
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000582
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000583 // Re-externalize globals that may have been internalized to increase scope
584 // for splitting
585 restoreLinkageForExternals();
586
Peter Collingbournec269ed52015-08-27 23:37:36 +0000587 // Do code generation. We need to preserve the module in case the client calls
588 // writeMergedModules() after compilation, but we only need to allow this at
589 // parallelism level 1. This is achieved by having splitCodeGen return the
590 // original module at parallelism level 1 which we then assign back to
591 // MergedModule.
Rafael Espindola3c1c9872016-04-17 18:42:27 +0000592 MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
593 [&]() { return createTargetMachine(); }, FileType,
594 ShouldRestoreGlobalsLinkage);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000595
Adam Nemet106feda2016-02-16 21:41:51 +0000596 // If statistics were requested, print them out after codegen.
597 if (llvm::AreStatisticsEnabled())
598 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +0000599 reportAndResetTimings();
Adam Nemet106feda2016-02-16 21:41:51 +0000600
Adam Nemet58951d32016-11-28 16:51:49 +0000601 finishOptimizationRemarks();
602
Shuxin Yang95866fa2013-08-06 21:51:21 +0000603 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000604}
605
Bill Wendling534a6582012-03-31 10:49:43 +0000606/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
607/// LTO problems.
Mehdi Amini4cc259a2016-10-01 01:18:23 +0000608void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000609 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
610 o = getToken(o.second))
Peter Collingbourne22575122015-08-21 04:45:55 +0000611 CodegenOptions.push_back(o.first);
Nick Kledzikc2323472008-07-08 21:14:10 +0000612}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000613
614void LTOCodeGenerator::parseCodeGenDebugOptions() {
615 // if options were requested, set them
Peter Collingbourne22575122015-08-21 04:45:55 +0000616 if (!CodegenOptions.empty()) {
617 // ParseCommandLineOptions() expects argv[0] to be program name.
618 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
619 for (std::string &Arg : CodegenOptions)
620 CodegenArgv.push_back(Arg.c_str());
621 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
622 }
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000623}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000624
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000625
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000626void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000627 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
628 lto_codegen_diagnostic_severity_t Severity;
629 switch (DI.getSeverity()) {
630 case DS_Error:
631 Severity = LTO_DS_ERROR;
632 break;
633 case DS_Warning:
634 Severity = LTO_DS_WARNING;
635 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000636 case DS_Remark:
637 Severity = LTO_DS_REMARK;
638 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000639 case DS_Note:
640 Severity = LTO_DS_NOTE;
641 break;
642 }
643 // Create the string that will be reported to the external diagnostic handler.
Alp Tokere69170a2014-06-26 22:52:05 +0000644 std::string MsgStorage;
645 raw_string_ostream Stream(MsgStorage);
646 DiagnosticPrinterRawOStream DP(Stream);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000647 DI.print(DP);
Alp Tokere69170a2014-06-26 22:52:05 +0000648 Stream.flush();
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000649
650 // If this method has been called it means someone has set up an external
651 // diagnostic handler. Assert on that.
652 assert(DiagHandler && "Invalid diagnostic handler");
Alp Tokere69170a2014-06-26 22:52:05 +0000653 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000654}
655
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000656namespace {
657struct LTODiagnosticHandler : public DiagnosticHandler {
658 LTOCodeGenerator *CodeGenerator;
659 LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
660 : CodeGenerator(CodeGenPtr) {}
661 bool handleDiagnostics(const DiagnosticInfo &DI) override {
662 CodeGenerator->DiagnosticHandler(DI);
663 return true;
664 }
665};
666}
667
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000668void
669LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
670 void *Ctxt) {
671 this->DiagHandler = DiagHandler;
672 this->DiagContext = Ctxt;
673 if (!DiagHandler)
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000674 return Context.setDiagnosticHandler(nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000675 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
676 // diagnostic to the external DiagHandler.
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000677 Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
678 true);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000679}
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000680
681namespace {
682class LTODiagnosticInfo : public DiagnosticInfo {
683 const Twine &Msg;
684public:
685 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
686 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
687 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
688};
689}
690
691void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
692 if (DiagHandler)
693 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
694 else
695 Context.diagnose(LTODiagnosticInfo(ErrMsg));
696}
Mehdi Amini8eb33972016-05-05 20:05:33 +0000697
698void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
699 if (DiagHandler)
700 (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
701 else
702 Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
703}