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