Update the error handling of lib/Linker.
[oota-llvm.git] / tools / llvm-lto / llvm-lto.cpp
1 //===-- llvm-lto: a simple command-line program to link modules with LTO --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This program takes in a list of bitcode files, links them, performs link-time
11 // optimization, and outputs an object file.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ADT/StringSet.h"
16 #include "llvm/CodeGen/CommandFlags.h"
17 #include "llvm/LTO/LTOCodeGenerator.h"
18 #include "llvm/LTO/LTOModule.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/PrettyStackTrace.h"
23 #include "llvm/Support/Signals.h"
24 #include "llvm/Support/TargetSelect.h"
25 #include "llvm/Support/raw_ostream.h"
26
27 using namespace llvm;
28
29 static cl::opt<bool>
30 DisableOpt("disable-opt", cl::init(false),
31   cl::desc("Do not run any optimization passes"));
32
33 static cl::opt<bool>
34 DisableInline("disable-inlining", cl::init(false),
35   cl::desc("Do not run the inliner pass"));
36
37 static cl::opt<bool>
38 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
39   cl::desc("Do not run the GVN load PRE pass"));
40
41 static cl::opt<bool>
42 UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
43   cl::desc("Use a diagnostic handler to test the handler interface"));
44
45 static cl::list<std::string>
46 InputFilenames(cl::Positional, cl::OneOrMore,
47   cl::desc("<input bitcode files>"));
48
49 static cl::opt<std::string>
50 OutputFilename("o", cl::init(""),
51   cl::desc("Override output filename"),
52   cl::value_desc("filename"));
53
54 static cl::list<std::string>
55 ExportedSymbols("exported-symbol",
56   cl::desc("Symbol to export from the resulting object file"),
57   cl::ZeroOrMore);
58
59 static cl::list<std::string>
60 DSOSymbols("dso-symbol",
61   cl::desc("Symbol to put in the symtab in the resulting dso"),
62   cl::ZeroOrMore);
63
64 namespace {
65 struct ModuleInfo {
66   std::vector<bool> CanBeHidden;
67 };
68 }
69
70 void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
71                        const char *Msg, void *) {
72   switch (Severity) {
73   case LTO_DS_NOTE:
74     errs() << "note: ";
75     break;
76   case LTO_DS_REMARK:
77     errs() << "remark: ";
78     break;
79   case LTO_DS_ERROR:
80     errs() << "error: ";
81     break;
82   case LTO_DS_WARNING:
83     errs() << "warning: ";
84     break;
85   }
86   errs() << Msg << "\n";
87 }
88
89 int main(int argc, char **argv) {
90   // Print a stack trace if we signal out.
91   sys::PrintStackTraceOnErrorSignal();
92   PrettyStackTraceProgram X(argc, argv);
93
94   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
95   cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
96
97   // Initialize the configured targets.
98   InitializeAllTargets();
99   InitializeAllTargetMCs();
100   InitializeAllAsmPrinters();
101   InitializeAllAsmParsers();
102
103   // set up the TargetOptions for the machine
104   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
105
106   unsigned BaseArg = 0;
107
108   LTOCodeGenerator CodeGen;
109
110   if (UseDiagnosticHandler)
111     CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
112
113   switch (RelocModel) {
114   case Reloc::Static:
115     CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_STATIC);
116     break;
117   case Reloc::PIC_:
118     CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC);
119     break;
120   case Reloc::DynamicNoPIC:
121     CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC);
122     break;
123   default:
124     CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DEFAULT);
125   }
126
127   CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
128   CodeGen.setTargetOptions(Options);
129
130   llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
131   for (unsigned i = 0; i < DSOSymbols.size(); ++i)
132     DSOSymbolsSet.insert(DSOSymbols[i]);
133
134   std::vector<std::string> KeptDSOSyms;
135
136   for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
137     std::string error;
138     std::unique_ptr<LTOModule> Module(
139         LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
140     if (!error.empty()) {
141       errs() << argv[0] << ": error loading file '" << InputFilenames[i]
142              << "': " << error << "\n";
143       return 1;
144     }
145
146     if (!CodeGen.addModule(Module.get()))
147       return 1;
148
149     unsigned NumSyms = Module->getSymbolCount();
150     for (unsigned I = 0; I < NumSyms; ++I) {
151       StringRef Name = Module->getSymbolName(I);
152       if (!DSOSymbolsSet.count(Name))
153         continue;
154       lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
155       unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
156       if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
157         KeptDSOSyms.push_back(Name);
158     }
159   }
160
161   // Add all the exported symbols to the table of symbols to preserve.
162   for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
163     CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
164
165   // Add all the dso symbols to the table of symbols to expose.
166   for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
167     CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
168
169   std::string attrs;
170   for (unsigned i = 0; i < MAttrs.size(); ++i) {
171     if (i > 0)
172       attrs.append(",");
173     attrs.append(MAttrs[i]);
174   }
175
176   if (!attrs.empty())
177     CodeGen.setAttr(attrs.c_str());
178
179   if (!OutputFilename.empty()) {
180     size_t len = 0;
181     std::string ErrorInfo;
182     const void *Code = CodeGen.compile(&len, DisableOpt, DisableInline,
183                                        DisableGVNLoadPRE, ErrorInfo);
184     if (!Code) {
185       errs() << argv[0]
186              << ": error compiling the code: " << ErrorInfo << "\n";
187       return 1;
188     }
189
190     std::error_code EC;
191     raw_fd_ostream FileStream(OutputFilename, EC, sys::fs::F_None);
192     if (EC) {
193       errs() << argv[0] << ": error opening the file '" << OutputFilename
194              << "': " << EC.message() << "\n";
195       return 1;
196     }
197
198     FileStream.write(reinterpret_cast<const char *>(Code), len);
199   } else {
200     std::string ErrorInfo;
201     const char *OutputName = nullptr;
202     if (!CodeGen.compile_to_file(&OutputName, DisableOpt, DisableInline,
203                                  DisableGVNLoadPRE, ErrorInfo)) {
204       errs() << argv[0]
205              << ": error compiling the code: " << ErrorInfo
206              << "\n";
207       return 1;
208     }
209
210     outs() << "Wrote native object file '" << OutputName << "'\n";
211   }
212
213   return 0;
214 }