]> git.proxmox.com Git - rustc.git/blob - src/llvm/tools/llc/llc.cpp
Imported Upstream version 0.7
[rustc.git] / src / llvm / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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 is the llc code generator driver. It provides a convenient
11 // command-line interface for generating native assembly-language code
12 // or C code, given LLVM bitcode.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/CommandFlags.h"
20 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/MC/SubtargetFeature.h"
25 #include "llvm/Pass.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/IRReader.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/PluginLoader.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/ToolOutputFile.h"
39 #include "llvm/Target/TargetLibraryInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include <memory>
42 using namespace llvm;
43
44 // General options for llc. Other pass-specific options are specified
45 // within the corresponding llc passes, and target-specific options
46 // and back-end code generation options are specified with the target machine.
47 //
48 static cl::opt<std::string>
49 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
50
51 static cl::opt<std::string>
52 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
53
54 static cl::opt<unsigned>
55 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
56 cl::value_desc("N"),
57 cl::desc("Repeat compilation N times for timing"));
58
59 // Determine optimization level.
60 static cl::opt<char>
61 OptLevel("O",
62 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
63 "(default = '-O2')"),
64 cl::Prefix,
65 cl::ZeroOrMore,
66 cl::init(' '));
67
68 static cl::opt<std::string>
69 TargetTriple("mtriple", cl::desc("Override target triple for module"));
70
71 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
72 cl::desc("Do not verify input module"));
73
74 cl::opt<bool>
75 DisableSimplifyLibCalls("disable-simplify-libcalls",
76 cl::desc("Disable simplify-libcalls"),
77 cl::init(false));
78
79 static int compileModule(char**, LLVMContext&);
80
81 // GetFileNameRoot - Helper function to get the basename of a filename.
82 static inline std::string
83 GetFileNameRoot(const std::string &InputFilename) {
84 std::string IFN = InputFilename;
85 std::string outputFilename;
86 int Len = IFN.length();
87 if ((Len > 2) &&
88 IFN[Len-3] == '.' &&
89 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
90 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
91 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
92 } else {
93 outputFilename = IFN;
94 }
95 return outputFilename;
96 }
97
98 static tool_output_file *GetOutputStream(const char *TargetName,
99 Triple::OSType OS,
100 const char *ProgName) {
101 // If we don't yet have an output filename, make one.
102 if (OutputFilename.empty()) {
103 if (InputFilename == "-")
104 OutputFilename = "-";
105 else {
106 OutputFilename = GetFileNameRoot(InputFilename);
107
108 switch (FileType) {
109 case TargetMachine::CGFT_AssemblyFile:
110 if (TargetName[0] == 'c') {
111 if (TargetName[1] == 0)
112 OutputFilename += ".cbe.c";
113 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
114 OutputFilename += ".cpp";
115 else
116 OutputFilename += ".s";
117 } else
118 OutputFilename += ".s";
119 break;
120 case TargetMachine::CGFT_ObjectFile:
121 if (OS == Triple::Win32)
122 OutputFilename += ".obj";
123 else
124 OutputFilename += ".o";
125 break;
126 case TargetMachine::CGFT_Null:
127 OutputFilename += ".null";
128 break;
129 }
130 }
131 }
132
133 // Decide if we need "binary" output.
134 bool Binary = false;
135 switch (FileType) {
136 case TargetMachine::CGFT_AssemblyFile:
137 break;
138 case TargetMachine::CGFT_ObjectFile:
139 case TargetMachine::CGFT_Null:
140 Binary = true;
141 break;
142 }
143
144 // Open the file.
145 std::string error;
146 unsigned OpenFlags = 0;
147 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
148 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
149 OpenFlags);
150 if (!error.empty()) {
151 errs() << error << '\n';
152 delete FDOut;
153 return 0;
154 }
155
156 return FDOut;
157 }
158
159 // main - Entry point for the llc compiler.
160 //
161 int main(int argc, char **argv) {
162 sys::PrintStackTraceOnErrorSignal();
163 PrettyStackTraceProgram X(argc, argv);
164
165 // Enable debug stream buffering.
166 EnableDebugBuffering = true;
167
168 LLVMContext &Context = getGlobalContext();
169 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
170
171 // Initialize targets first, so that --version shows registered targets.
172 InitializeAllTargets();
173 InitializeAllTargetMCs();
174 InitializeAllAsmPrinters();
175 InitializeAllAsmParsers();
176
177 // Initialize codegen and IR passes used by llc so that the -print-after,
178 // -print-before, and -stop-after options work.
179 PassRegistry *Registry = PassRegistry::getPassRegistry();
180 initializeCore(*Registry);
181 initializeCodeGen(*Registry);
182 initializeLoopStrengthReducePass(*Registry);
183 initializeLowerIntrinsicsPass(*Registry);
184 initializeUnreachableBlockElimPass(*Registry);
185
186 // Register the target printer for --version.
187 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
188
189 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
190
191 // Compile the module TimeCompilations times to give better compile time
192 // metrics.
193 for (unsigned I = TimeCompilations; I; --I)
194 if (int RetVal = compileModule(argv, Context))
195 return RetVal;
196 return 0;
197 }
198
199 static int compileModule(char **argv, LLVMContext &Context) {
200 // Load the module to be compiled...
201 SMDiagnostic Err;
202 std::auto_ptr<Module> M;
203 Module *mod = 0;
204 Triple TheTriple;
205
206 bool SkipModule = MCPU == "help" ||
207 (!MAttrs.empty() && MAttrs.front() == "help");
208
209 // If user just wants to list available options, skip module loading
210 if (!SkipModule) {
211 M.reset(ParseIRFile(InputFilename, Err, Context));
212 mod = M.get();
213 if (mod == 0) {
214 Err.print(argv[0], errs());
215 return 1;
216 }
217
218 // If we are supposed to override the target triple, do so now.
219 if (!TargetTriple.empty())
220 mod->setTargetTriple(Triple::normalize(TargetTriple));
221 TheTriple = Triple(mod->getTargetTriple());
222 } else {
223 TheTriple = Triple(Triple::normalize(TargetTriple));
224 }
225
226 if (TheTriple.getTriple().empty())
227 TheTriple.setTriple(sys::getDefaultTargetTriple());
228
229 // Get the target specific parser.
230 std::string Error;
231 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
232 Error);
233 if (!TheTarget) {
234 errs() << argv[0] << ": " << Error;
235 return 1;
236 }
237
238 // Package up features to be passed to target/subtarget
239 std::string FeaturesStr;
240 if (MAttrs.size()) {
241 SubtargetFeatures Features;
242 for (unsigned i = 0; i != MAttrs.size(); ++i)
243 Features.AddFeature(MAttrs[i]);
244 FeaturesStr = Features.getString();
245 }
246
247 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
248 switch (OptLevel) {
249 default:
250 errs() << argv[0] << ": invalid optimization level.\n";
251 return 1;
252 case ' ': break;
253 case '0': OLvl = CodeGenOpt::None; break;
254 case '1': OLvl = CodeGenOpt::Less; break;
255 case '2': OLvl = CodeGenOpt::Default; break;
256 case '3': OLvl = CodeGenOpt::Aggressive; break;
257 }
258
259 TargetOptions Options;
260 Options.LessPreciseFPMADOption = EnableFPMAD;
261 Options.NoFramePointerElim = DisableFPElim;
262 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
263 Options.AllowFPOpFusion = FuseFPOps;
264 Options.UnsafeFPMath = EnableUnsafeFPMath;
265 Options.NoInfsFPMath = EnableNoInfsFPMath;
266 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
267 Options.HonorSignDependentRoundingFPMathOption =
268 EnableHonorSignDependentRoundingFPMath;
269 Options.UseSoftFloat = GenerateSoftFloatCalls;
270 if (FloatABIForCalls != FloatABI::Default)
271 Options.FloatABIType = FloatABIForCalls;
272 Options.NoZerosInBSS = DontPlaceZerosInBSS;
273 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
274 Options.DisableTailCalls = DisableTailCalls;
275 Options.StackAlignmentOverride = OverrideStackAlignment;
276 Options.RealignStack = EnableRealignStack;
277 Options.TrapFuncName = TrapFuncName;
278 Options.PositionIndependentExecutable = EnablePIE;
279 Options.EnableSegmentedStacks = SegmentedStacks;
280 Options.UseInitArray = UseInitArray;
281 Options.SSPBufferSize = SSPBufferSize;
282
283 std::auto_ptr<TargetMachine>
284 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
285 MCPU, FeaturesStr, Options,
286 RelocModel, CMModel, OLvl));
287 assert(target.get() && "Could not allocate target machine!");
288 assert(mod && "Should have exited after outputting help!");
289 TargetMachine &Target = *target.get();
290
291 if (DisableDotLoc)
292 Target.setMCUseLoc(false);
293
294 if (DisableCFI)
295 Target.setMCUseCFI(false);
296
297 if (EnableDwarfDirectory)
298 Target.setMCUseDwarfDirectory(true);
299
300 if (GenerateSoftFloatCalls)
301 FloatABIForCalls = FloatABI::Soft;
302
303 // Disable .loc support for older OS X versions.
304 if (TheTriple.isMacOSX() &&
305 TheTriple.isMacOSXVersionLT(10, 6))
306 Target.setMCUseLoc(false);
307
308 // Figure out where we are going to send the output.
309 OwningPtr<tool_output_file> Out
310 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
311 if (!Out) return 1;
312
313 // Build up all of the passes that we want to do to the module.
314 PassManager PM;
315
316 // Add an appropriate TargetLibraryInfo pass for the module's triple.
317 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
318 if (DisableSimplifyLibCalls)
319 TLI->disableAllFunctions();
320 PM.add(TLI);
321
322 // Add intenal analysis passes from the target machine.
323 Target.addAnalysisPasses(PM);
324
325 // Add the target data from the target machine, if it exists, or the module.
326 if (const DataLayout *TD = Target.getDataLayout())
327 PM.add(new DataLayout(*TD));
328 else
329 PM.add(new DataLayout(mod));
330
331 // Override default to generate verbose assembly.
332 Target.setAsmVerbosityDefault(true);
333
334 if (RelaxAll) {
335 if (FileType != TargetMachine::CGFT_ObjectFile)
336 errs() << argv[0]
337 << ": warning: ignoring -mc-relax-all because filetype != obj";
338 else
339 Target.setMCRelaxAll(true);
340 }
341
342 {
343 formatted_raw_ostream FOS(Out->os());
344
345 AnalysisID StartAfterID = 0;
346 AnalysisID StopAfterID = 0;
347 const PassRegistry *PR = PassRegistry::getPassRegistry();
348 if (!StartAfter.empty()) {
349 const PassInfo *PI = PR->getPassInfo(StartAfter);
350 if (!PI) {
351 errs() << argv[0] << ": start-after pass is not registered.\n";
352 return 1;
353 }
354 StartAfterID = PI->getTypeInfo();
355 }
356 if (!StopAfter.empty()) {
357 const PassInfo *PI = PR->getPassInfo(StopAfter);
358 if (!PI) {
359 errs() << argv[0] << ": stop-after pass is not registered.\n";
360 return 1;
361 }
362 StopAfterID = PI->getTypeInfo();
363 }
364
365 // Ask the target to add backend passes as necessary.
366 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
367 StartAfterID, StopAfterID)) {
368 errs() << argv[0] << ": target does not support generation of this"
369 << " file type!\n";
370 return 1;
371 }
372
373 // Before executing passes, print the final values of the LLVM options.
374 cl::PrintOptionValues();
375
376 PM.run(*mod);
377 }
378
379 // Declare success.
380 Out->keep();
381
382 return 0;
383 }