For PR780:
[oota-llvm.git] / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 bytecode.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Bytecode/Reader.h"
17 #include "llvm/Target/SubtargetFeature.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetMachineRegistry.h"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Module.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/PluginLoader.h"
27 #include "llvm/Support/FileUtilities.h"
28 #include "llvm/Analysis/Verifier.h"
29 #include "llvm/System/Signals.h"
30 #include "llvm/Config/config.h"
31 #include "llvm/LinkAllVMCore.h"
32 #include <fstream>
33 #include <iostream>
34 #include <memory>
35
36 using namespace llvm;
37
38 // General options for llc.  Other pass-specific options are specified
39 // within the corresponding llc passes, and target-specific options
40 // and back-end code generation options are specified with the target machine.
41 //
42 static cl::opt<std::string>
43 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
44
45 static cl::opt<std::string>
46 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
47
48 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
49
50 static cl::opt<bool> Fast("fast", 
51       cl::desc("Generate code quickly, potentially sacrificing code quality"));
52
53 static cl::opt<std::string>
54 TargetTriple("mtriple", cl::desc("Override target triple for module"));
55
56 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
57 MArch("march", cl::desc("Architecture to generate code for:"));
58
59 static cl::opt<std::string>
60 MCPU("mcpu", 
61   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
62   cl::value_desc("cpu-name"),
63   cl::init(""));
64
65 static cl::list<std::string>
66 MAttrs("mattr", 
67   cl::CommaSeparated,
68   cl::desc("Target specific attributes (-mattr=help for details)"),
69   cl::value_desc("a1,+a2,-a3,..."));
70
71 cl::opt<TargetMachine::CodeGenFileType>
72 FileType("filetype", cl::init(TargetMachine::AssemblyFile),
73   cl::desc("Choose a file type (not all types are supported by all targets):"),
74   cl::values(
75        clEnumValN(TargetMachine::AssemblyFile,    "asm",
76                   "  Emit an assembly ('.s') file"),
77        clEnumValN(TargetMachine::ObjectFile,    "obj",
78                   "  Emit a native object ('.o') file [experimental]"),
79        clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
80                   "  Emit a native dynamic library ('.so') file"),
81        clEnumValEnd));
82
83 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
84                        cl::desc("Do not verify input module"));
85
86
87 // GetFileNameRoot - Helper function to get the basename of a filename.
88 static inline std::string
89 GetFileNameRoot(const std::string &InputFilename) {
90   std::string IFN = InputFilename;
91   std::string outputFilename;
92   int Len = IFN.length();
93   if ((Len > 2) &&
94       IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
95     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
96   } else {
97     outputFilename = IFN;
98   }
99   return outputFilename;
100 }
101
102
103 // main - Entry point for the llc compiler.
104 //
105 int main(int argc, char **argv) {
106   try {
107     cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
108     sys::PrintStackTraceOnErrorSignal();
109
110     // Load the module to be compiled...
111     std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
112     if (M.get() == 0) {
113       std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
114       return 1;
115     }
116     Module &mod = *M.get();
117
118     // If we are supposed to override the target triple, do so now.
119     if (!TargetTriple.empty())
120       mod.setTargetTriple(TargetTriple);
121     
122     // Allocate target machine.  First, check whether the user has
123     // explicitly specified an architecture to compile for.
124     if (MArch == 0) {
125       std::string Err;
126       MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
127       if (MArch == 0) {
128         std::cerr << argv[0] << ": error auto-selecting target for module '"
129                   << Err << "'.  Please use the -march option to explicitly "
130                   << "pick a target.\n";
131         return 1;
132       }
133     }
134
135     // Package up features to be passed to target/subtarget
136     std::string FeaturesStr;
137     if (MCPU.size() || MAttrs.size()) {
138       SubtargetFeatures Features;
139       Features.setCPU(MCPU);
140       for (unsigned i = 0; i != MAttrs.size(); ++i)
141         Features.AddFeature(MAttrs[i]);
142       FeaturesStr = Features.getString();
143     }
144
145     std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
146     assert(target.get() && "Could not allocate target machine!");
147     TargetMachine &Target = *target.get();
148
149     // Build up all of the passes that we want to do to the module...
150     PassManager Passes;
151     Passes.add(new TargetData(*Target.getTargetData()));
152
153 #ifndef NDEBUG
154     if(!NoVerify)
155       Passes.add(createVerifierPass());
156 #endif
157
158     // Figure out where we are going to send the output...
159     std::ostream *Out = 0;
160     if (OutputFilename != "") {
161       if (OutputFilename != "-") {
162         // Specified an output filename?
163         if (!Force && std::ifstream(OutputFilename.c_str())) {
164           // If force is not specified, make sure not to overwrite a file!
165           std::cerr << argv[0] << ": error opening '" << OutputFilename
166                     << "': file exists!\n"
167                     << "Use -f command line argument to force output\n";
168           return 1;
169         }
170         Out = new std::ofstream(OutputFilename.c_str());
171
172         // Make sure that the Out file gets unlinked from the disk if we get a
173         // SIGINT
174         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
175       } else {
176         Out = &std::cout;
177       }
178     } else {
179       if (InputFilename == "-") {
180         OutputFilename = "-";
181         Out = &std::cout;
182       } else {
183         OutputFilename = GetFileNameRoot(InputFilename);
184
185         switch (FileType) {
186         case TargetMachine::AssemblyFile:
187           if (MArch->Name[0] != 'c' || MArch->Name[1] != 0)  // not CBE
188             OutputFilename += ".s";
189           else
190             OutputFilename += ".cbe.c";
191           break;
192         case TargetMachine::ObjectFile:
193           OutputFilename += ".o";
194           break;
195         case TargetMachine::DynamicLibrary:
196           OutputFilename += LTDL_SHLIB_EXT;
197           break;
198         }
199
200         if (!Force && std::ifstream(OutputFilename.c_str())) {
201           // If force is not specified, make sure not to overwrite a file!
202           std::cerr << argv[0] << ": error opening '" << OutputFilename
203                     << "': file exists!\n"
204                     << "Use -f command line argument to force output\n";
205           return 1;
206         }
207
208         Out = new std::ofstream(OutputFilename.c_str());
209         if (!Out->good()) {
210           std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
211           delete Out;
212           return 1;
213         }
214
215         // Make sure that the Out file gets unlinked from the disk if we get a
216         // SIGINT
217         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
218       }
219     }
220
221     if (FileType != TargetMachine::AssemblyFile)
222       std::cerr << "WARNING: only -filetype=asm is currently supported.\n";
223     
224     // Ask the target to add backend passes as necessary.
225     if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
226       std::cerr << argv[0] << ": target '" << Target.getName()
227                 << "' does not support generation of this file type!\n";
228       if (Out != &std::cout) delete Out;
229       // And the Out file is empty and useless, so remove it now.
230       sys::Path(OutputFilename).eraseFromDisk();
231       return 1;
232     } else {
233       // Run our queue of passes all at once now, efficiently.
234       Passes.run(*M.get());
235     }
236
237     // Delete the ostream if it's not a stdout stream
238     if (Out != &std::cout) delete Out;
239
240     return 0;
241   } catch (const std::string& msg) {
242     std::cerr << argv[0] << ": " << msg << "\n";
243   } catch (...) {
244     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
245   }
246   return 1;
247 }