1 //===-- llvm-lto: a simple command-line program to link modules with LTO --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program takes in a list of bitcode files, links them, performs link-time
11 // optimization, and outputs an object file.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/StringSet.h"
16 #include "llvm/Bitcode/ReaderWriter.h"
17 #include "llvm/CodeGen/CommandFlags.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/LTO/LTOCodeGenerator.h"
20 #include "llvm/LTO/LTOModule.h"
21 #include "llvm/Object/FunctionIndexObjectFile.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/TargetSelect.h"
28 #include "llvm/Support/ToolOutputFile.h"
29 #include "llvm/Support/raw_ostream.h"
36 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
42 static cl::opt<bool> DisableVerify(
43 "disable-verify", cl::init(false),
44 cl::desc("Do not run the verifier during the optimization pipeline"));
47 DisableInline("disable-inlining", cl::init(false),
48 cl::desc("Do not run the inliner pass"));
51 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
52 cl::desc("Do not run the GVN load PRE pass"));
55 DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
56 cl::desc("Do not run loop or slp vectorization during LTO"));
59 UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
60 cl::desc("Use a diagnostic handler to test the handler interface"));
63 ThinLTO("thinlto", cl::init(false),
64 cl::desc("Only write combined global index for ThinLTO backends"));
66 static cl::list<std::string>
67 InputFilenames(cl::Positional, cl::OneOrMore,
68 cl::desc("<input bitcode files>"));
70 static cl::opt<std::string>
71 OutputFilename("o", cl::init(""),
72 cl::desc("Override output filename"),
73 cl::value_desc("filename"));
75 static cl::list<std::string>
76 ExportedSymbols("exported-symbol",
77 cl::desc("Symbol to export from the resulting object file"),
80 static cl::list<std::string>
81 DSOSymbols("dso-symbol",
82 cl::desc("Symbol to put in the symtab in the resulting dso"),
85 static cl::opt<bool> ListSymbolsOnly(
86 "list-symbols-only", cl::init(false),
87 cl::desc("Instead of running LTO, list the symbols in each IR file"));
89 static cl::opt<bool> SetMergedModule(
90 "set-merged-module", cl::init(false),
91 cl::desc("Use the first input module as the merged module"));
93 static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
94 cl::desc("Number of backend threads"));
98 std::vector<bool> CanBeHidden;
102 static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
103 const char *Msg, void *) {
104 errs() << "llvm-lto: ";
110 errs() << "remark: ";
116 errs() << "warning: ";
119 errs() << Msg << "\n";
122 static std::unique_ptr<LTOModule>
123 getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
124 const TargetOptions &Options, std::string &Error) {
125 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
126 MemoryBuffer::getFile(Path);
127 if (std::error_code EC = BufferOrErr.getError()) {
128 Error = EC.message();
131 Buffer = std::move(BufferOrErr.get());
132 return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
133 Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
136 /// \brief List symbols in each IR file.
138 /// The main point here is to provide lit-testable coverage for the LTOModule
139 /// functionality that's exposed by the C API to list symbols. Moreover, this
140 /// provides testing coverage for modules that have been created in their own
142 static int listSymbols(StringRef Command, const TargetOptions &Options) {
143 for (auto &Filename : InputFilenames) {
145 std::unique_ptr<MemoryBuffer> Buffer;
146 std::unique_ptr<LTOModule> Module =
147 getLocalLTOModule(Filename, Buffer, Options, Error);
149 errs() << Command << ": error loading file '" << Filename
150 << "': " << Error << "\n";
155 outs() << Filename << ":\n";
156 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
157 outs() << Module->getSymbolName(I) << "\n";
162 /// Parse the function index out of an IR file and return the function
163 /// index object if found, or nullptr if not.
164 static std::unique_ptr<FunctionInfoIndex>
165 getFunctionIndexForFile(StringRef Path, std::string &Error,
166 LLVMContext &Context) {
167 std::unique_ptr<MemoryBuffer> Buffer;
168 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
169 MemoryBuffer::getFile(Path);
170 if (std::error_code EC = BufferOrErr.getError()) {
171 Error = EC.message();
174 Buffer = std::move(BufferOrErr.get());
175 ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
176 object::FunctionIndexObjectFile::create(Buffer->getMemBufferRef(),
178 if (std::error_code EC = ObjOrErr.getError()) {
179 Error = EC.message();
182 return (*ObjOrErr)->takeIndex();
185 /// Create a combined index file from the input IR files and write it.
187 /// This is meant to enable testing of ThinLTO combined index generation,
188 /// currently available via the gold plugin via -thinlto.
189 static int createCombinedFunctionIndex(StringRef Command) {
191 FunctionInfoIndex CombinedIndex;
192 uint64_t NextModuleId = 0;
193 for (auto &Filename : InputFilenames) {
195 std::unique_ptr<FunctionInfoIndex> Index =
196 getFunctionIndexForFile(Filename, Error, Context);
198 errs() << Command << ": error loading file '" << Filename
199 << "': " << Error << "\n";
202 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
205 assert(!OutputFilename.empty());
206 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
207 sys::fs::OpenFlags::F_None);
209 errs() << Command << ": error opening the file '" << OutputFilename
210 << ".thinlto.bc': " << EC.message() << "\n";
213 WriteFunctionSummaryToFile(CombinedIndex, OS);
218 int main(int argc, char **argv) {
219 // Print a stack trace if we signal out.
220 sys::PrintStackTraceOnErrorSignal();
221 PrettyStackTraceProgram X(argc, argv);
223 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
224 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
226 if (OptLevel < '0' || OptLevel > '3') {
227 errs() << argv[0] << ": optimization level must be between 0 and 3\n";
231 // Initialize the configured targets.
232 InitializeAllTargets();
233 InitializeAllTargetMCs();
234 InitializeAllAsmPrinters();
235 InitializeAllAsmParsers();
237 // set up the TargetOptions for the machine
238 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
241 return listSymbols(argv[0], Options);
244 return createCombinedFunctionIndex(argv[0]);
246 unsigned BaseArg = 0;
248 LTOCodeGenerator CodeGen;
250 if (UseDiagnosticHandler)
251 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
253 CodeGen.setCodePICModel(RelocModel);
255 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
256 CodeGen.setTargetOptions(Options);
258 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
259 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
260 DSOSymbolsSet.insert(DSOSymbols[i]);
262 std::vector<std::string> KeptDSOSyms;
264 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
266 std::unique_ptr<LTOModule> Module(
267 LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
268 if (!error.empty()) {
269 errs() << argv[0] << ": error loading file '" << InputFilenames[i]
270 << "': " << error << "\n";
274 unsigned NumSyms = Module->getSymbolCount();
275 for (unsigned I = 0; I < NumSyms; ++I) {
276 StringRef Name = Module->getSymbolName(I);
277 if (!DSOSymbolsSet.count(Name))
279 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
280 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
281 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
282 KeptDSOSyms.push_back(Name);
285 // We use the first input module as the destination module when
286 // SetMergedModule is true.
287 if (SetMergedModule && i == BaseArg) {
288 // Transfer ownership to the code generator.
289 CodeGen.setModule(std::move(Module));
290 } else if (!CodeGen.addModule(Module.get())) {
291 // Print a message here so that we know addModule() did not abort.
292 errs() << argv[0] << ": error adding file '" << InputFilenames[i] << "'\n";
297 // Add all the exported symbols to the table of symbols to preserve.
298 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
299 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
301 // Add all the dso symbols to the table of symbols to expose.
302 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
303 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
305 // Set cpu and attrs strings for the default target/subtarget.
306 CodeGen.setCpu(MCPU.c_str());
308 CodeGen.setOptLevel(OptLevel - '0');
311 for (unsigned i = 0; i < MAttrs.size(); ++i) {
314 attrs.append(MAttrs[i]);
318 CodeGen.setAttr(attrs.c_str());
320 if (!OutputFilename.empty()) {
321 std::string ErrorInfo;
322 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
323 DisableLTOVectorization, ErrorInfo)) {
324 errs() << argv[0] << ": error optimizing the code: " << ErrorInfo << "\n";
328 std::list<tool_output_file> OSs;
329 std::vector<raw_pwrite_stream *> OSPtrs;
330 for (unsigned I = 0; I != Parallelism; ++I) {
331 std::string PartFilename = OutputFilename;
332 if (Parallelism != 1)
333 PartFilename += "." + utostr(I);
335 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
337 errs() << argv[0] << ": error opening the file '" << PartFilename
338 << "': " << EC.message() << "\n";
341 OSPtrs.push_back(&OSs.back().os());
344 if (!CodeGen.compileOptimized(OSPtrs, ErrorInfo)) {
345 errs() << argv[0] << ": error compiling the code: " << ErrorInfo << "\n";
349 for (tool_output_file &OS : OSs)
352 if (Parallelism != 1) {
353 errs() << argv[0] << ": -j must be specified together with -o\n";
357 std::string ErrorInfo;
358 const char *OutputName = nullptr;
359 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
360 DisableGVNLoadPRE, DisableLTOVectorization,
363 << ": error compiling the code: " << ErrorInfo
368 outs() << "Wrote native object file '" << OutputName << "'\n";