1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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 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.
14 //===----------------------------------------------------------------------===//
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Pass.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/PluginLoader.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetMachine.h"
46 // General options for llc. Other pass-specific options are specified
47 // within the corresponding llc passes, and target-specific options
48 // and back-end code generation options are specified with the target machine.
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
53 static cl::opt<std::string>
54 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
56 static cl::opt<unsigned>
57 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
59 cl::desc("Repeat compilation N times for timing"));
61 // Determine optimization level.
64 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
70 static cl::opt<std::string>
71 TargetTriple("mtriple", cl::desc("Override target triple for module"));
73 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
74 cl::desc("Do not verify input module"));
77 DisableSimplifyLibCalls("disable-simplify-libcalls",
78 cl::desc("Disable simplify-libcalls"),
81 static int compileModule(char**, LLVMContext&);
83 // GetFileNameRoot - Helper function to get the basename of a filename.
84 static inline std::string
85 GetFileNameRoot(const std::string &InputFilename) {
86 std::string IFN = InputFilename;
87 std::string outputFilename;
88 int Len = IFN.length();
91 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
92 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
93 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
97 return outputFilename;
100 static tool_output_file *GetOutputStream(const char *TargetName,
102 const char *ProgName) {
103 // If we don't yet have an output filename, make one.
104 if (OutputFilename.empty()) {
105 if (InputFilename == "-")
106 OutputFilename = "-";
108 OutputFilename = GetFileNameRoot(InputFilename);
111 case TargetMachine::CGFT_AssemblyFile:
112 if (TargetName[0] == 'c') {
113 if (TargetName[1] == 0)
114 OutputFilename += ".cbe.c";
115 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
116 OutputFilename += ".cpp";
118 OutputFilename += ".s";
120 OutputFilename += ".s";
122 case TargetMachine::CGFT_ObjectFile:
123 if (OS == Triple::Win32)
124 OutputFilename += ".obj";
126 OutputFilename += ".o";
128 case TargetMachine::CGFT_Null:
129 OutputFilename += ".null";
135 // Decide if we need "binary" output.
138 case TargetMachine::CGFT_AssemblyFile:
140 case TargetMachine::CGFT_ObjectFile:
141 case TargetMachine::CGFT_Null:
148 unsigned OpenFlags = 0;
149 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
150 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
152 if (!error.empty()) {
153 errs() << error << '\n';
161 // main - Entry point for the llc compiler.
163 int main(int argc, char **argv) {
164 sys::PrintStackTraceOnErrorSignal();
165 PrettyStackTraceProgram X(argc, argv);
167 // Enable debug stream buffering.
168 EnableDebugBuffering = true;
170 LLVMContext &Context = getGlobalContext();
171 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
173 // Initialize targets first, so that --version shows registered targets.
174 InitializeAllTargets();
175 InitializeAllTargetMCs();
176 InitializeAllAsmPrinters();
177 InitializeAllAsmParsers();
179 // Initialize codegen and IR passes used by llc so that the -print-after,
180 // -print-before, and -stop-after options work.
181 PassRegistry *Registry = PassRegistry::getPassRegistry();
182 initializeCore(*Registry);
183 initializeCodeGen(*Registry);
184 initializeLoopStrengthReducePass(*Registry);
185 initializeLowerIntrinsicsPass(*Registry);
186 initializeUnreachableBlockElimPass(*Registry);
188 // Register the target printer for --version.
189 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
191 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
193 // Compile the module TimeCompilations times to give better compile time
195 for (unsigned I = TimeCompilations; I; --I)
196 if (int RetVal = compileModule(argv, Context))
201 static int compileModule(char **argv, LLVMContext &Context) {
202 // Load the module to be compiled...
208 bool SkipModule = MCPU == "help" ||
209 (!MAttrs.empty() && MAttrs.front() == "help");
211 // If user just wants to list available options, skip module loading
213 M.reset(ParseIRFile(InputFilename, Err, Context));
216 Err.print(argv[0], errs());
220 // If we are supposed to override the target triple, do so now.
221 if (!TargetTriple.empty())
222 mod->setTargetTriple(Triple::normalize(TargetTriple));
223 TheTriple = Triple(mod->getTargetTriple());
225 TheTriple = Triple(Triple::normalize(TargetTriple));
228 if (TheTriple.getTriple().empty())
229 TheTriple.setTriple(sys::getDefaultTargetTriple());
231 // Get the target specific parser.
233 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
236 errs() << argv[0] << ": " << Error;
240 // Package up features to be passed to target/subtarget
241 std::string FeaturesStr;
243 SubtargetFeatures Features;
244 for (unsigned i = 0; i != MAttrs.size(); ++i)
245 Features.AddFeature(MAttrs[i]);
246 FeaturesStr = Features.getString();
249 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
252 errs() << argv[0] << ": invalid optimization level.\n";
255 case '0': OLvl = CodeGenOpt::None; break;
256 case '1': OLvl = CodeGenOpt::Less; break;
257 case '2': OLvl = CodeGenOpt::Default; break;
258 case '3': OLvl = CodeGenOpt::Aggressive; break;
261 TargetOptions Options;
262 Options.LessPreciseFPMADOption = EnableFPMAD;
263 Options.NoFramePointerElim = DisableFPElim;
264 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
265 Options.AllowFPOpFusion = FuseFPOps;
266 Options.UnsafeFPMath = EnableUnsafeFPMath;
267 Options.NoInfsFPMath = EnableNoInfsFPMath;
268 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
269 Options.HonorSignDependentRoundingFPMathOption =
270 EnableHonorSignDependentRoundingFPMath;
271 Options.UseSoftFloat = GenerateSoftFloatCalls;
272 if (FloatABIForCalls != FloatABI::Default)
273 Options.FloatABIType = FloatABIForCalls;
274 Options.NoZerosInBSS = DontPlaceZerosInBSS;
275 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
276 Options.DisableTailCalls = DisableTailCalls;
277 Options.StackAlignmentOverride = OverrideStackAlignment;
278 Options.RealignStack = EnableRealignStack;
279 Options.TrapFuncName = TrapFuncName;
280 Options.PositionIndependentExecutable = EnablePIE;
281 Options.EnableSegmentedStacks = SegmentedStacks;
282 Options.UseInitArray = UseInitArray;
283 Options.SSPBufferSize = SSPBufferSize;
285 OwningPtr<TargetMachine>
286 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
287 MCPU, FeaturesStr, Options,
288 RelocModel, CMModel, OLvl));
289 assert(target.get() && "Could not allocate target machine!");
290 assert(mod && "Should have exited after outputting help!");
291 TargetMachine &Target = *target.get();
294 Target.setMCUseLoc(false);
297 Target.setMCUseCFI(false);
299 if (EnableDwarfDirectory)
300 Target.setMCUseDwarfDirectory(true);
302 if (GenerateSoftFloatCalls)
303 FloatABIForCalls = FloatABI::Soft;
305 // Disable .loc support for older OS X versions.
306 if (TheTriple.isMacOSX() &&
307 TheTriple.isMacOSXVersionLT(10, 6))
308 Target.setMCUseLoc(false);
310 // Figure out where we are going to send the output.
311 OwningPtr<tool_output_file> Out
312 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
315 // Build up all of the passes that we want to do to the module.
318 // Add an appropriate TargetLibraryInfo pass for the module's triple.
319 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
320 if (DisableSimplifyLibCalls)
321 TLI->disableAllFunctions();
324 // Add intenal analysis passes from the target machine.
325 Target.addAnalysisPasses(PM);
327 // Add the target data from the target machine, if it exists, or the module.
328 if (const DataLayout *TD = Target.getDataLayout())
329 PM.add(new DataLayout(*TD));
331 PM.add(new DataLayout(mod));
333 // Override default to generate verbose assembly.
334 Target.setAsmVerbosityDefault(true);
337 if (FileType != TargetMachine::CGFT_ObjectFile)
339 << ": warning: ignoring -mc-relax-all because filetype != obj";
341 Target.setMCRelaxAll(true);
345 formatted_raw_ostream FOS(Out->os());
347 AnalysisID StartAfterID = 0;
348 AnalysisID StopAfterID = 0;
349 const PassRegistry *PR = PassRegistry::getPassRegistry();
350 if (!StartAfter.empty()) {
351 const PassInfo *PI = PR->getPassInfo(StartAfter);
353 errs() << argv[0] << ": start-after pass is not registered.\n";
356 StartAfterID = PI->getTypeInfo();
358 if (!StopAfter.empty()) {
359 const PassInfo *PI = PR->getPassInfo(StopAfter);
361 errs() << argv[0] << ": stop-after pass is not registered.\n";
364 StopAfterID = PI->getTypeInfo();
367 // Ask the target to add backend passes as necessary.
368 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
369 StartAfterID, StopAfterID)) {
370 errs() << argv[0] << ": target does not support generation of this"
375 // Before executing passes, print the final values of the LLVM options.
376 cl::PrintOptionValues();