1 //===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
3 // This is the llc compiler driver.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Bytecode/Reader.h"
8 #include "llvm/Target/TargetMachineImpls.h"
9 #include "llvm/Target/TargetMachine.h"
10 #include "llvm/Transforms/Instrumentation.h"
11 #include "llvm/Transforms/Scalar.h"
12 #include "llvm/Transforms/Utils/Linker.h"
13 #include "llvm/Assembly/PrintModulePass.h"
14 #include "llvm/Bytecode/WriteBytecodePass.h"
15 #include "llvm/Transforms/IPO.h"
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Support/PassNameParser.h"
20 #include "Support/CommandLine.h"
21 #include "Support/Signals.h"
27 //------------------------------------------------------------------------------
28 // Option declarations for LLC.
29 //------------------------------------------------------------------------------
31 // Make all registered optimization passes available to llc. These passes
32 // will all be run before the simplification and lowering steps used by the
33 // back-end code generator, and will be run in the order specified on the
34 // command line. The OptimizationList is automatically populated with
35 // registered Passes by the PassNameParser.
37 static cl::list<const PassInfo*, bool,
38 FilteredPassNameParser<PassInfo::Optimization> >
39 OptimizationList(cl::desc("Optimizations available:"));
42 // General options for llc. Other pass-specific options are specified
43 // within the corresponding llc passes, and target-specific options
44 // and back-end code generation options are specified with the target machine.
46 static cl::opt<string>
47 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
49 static cl::opt<string>
50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
52 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
55 DumpAsm("d", cl::desc("Print bytecode before native code generation"),
58 static cl::opt<string>
59 TraceLibPath("tracelibpath", cl::desc("Path to libinstr for trace code"),
60 cl::value_desc("directory"), cl::Hidden);
63 // flags set from -tracem and -trace options to control tracing
64 static bool TraceFunctions = false;
65 static bool TraceBasicBlocks = false;
68 // GetFileNameRoot - Helper function to get the basename of a filename...
70 GetFileNameRoot(const string &InputFilename)
72 string IFN = InputFilename;
73 string outputFilename;
74 int Len = IFN.length();
75 if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
76 outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
80 return outputFilename;
84 insertTraceCodeFor(Module &M)
88 // Insert trace code in all functions in the module
90 Passes.add(createTraceValuesPassForBasicBlocks());
91 else if (TraceFunctions)
92 Passes.add(createTraceValuesPassForFunction());
96 // Eliminate duplication in constant pool
97 Passes.add(createConstantMergePass());
99 // Run passes to insert and clean up trace code...
102 std::string ErrorMessage;
104 // Load the module that contains the runtime helper routines neccesary for
105 // pointer hashing and stuff... link this module into the program if possible
107 Module *TraceModule = ParseBytecodeFile(TraceLibPath+"libinstr.bc");
109 // Check if the TraceLibPath contains a valid module. If not, try to load
110 // the module from the current LLVM-GCC install directory. This is kindof
111 // a hack, but allows people to not HAVE to have built the library.
113 if (TraceModule == 0)
114 TraceModule = ParseBytecodeFile("/home/vadve/lattner/cvs/gcc_install/lib/"
115 "gcc-lib/llvm/3.1/libinstr.bc");
117 // If we still didn't get it, cancel trying to link it in...
118 if (TraceModule == 0)
119 cerr << "Warning, could not load trace routines to link into program!\n";
122 // Link in the trace routines... if this fails, don't panic, because the
123 // compile should still succeed, but the native linker will probably fail.
125 std::auto_ptr<Module> TraceRoutines(TraceModule);
126 if (LinkModules(&M, TraceRoutines.get(), &ErrorMessage))
127 cerr << "Warning: Error linking in trace routines: "
128 << ErrorMessage << "\n";
131 // Write out the module with tracing code just before code generation
132 assert (InputFilename != "-"
133 && "Cannot write out traced bytecode when reading input from stdin");
134 string TraceFilename = GetFileNameRoot(InputFilename) + ".trace.bc";
136 std::ofstream Out(TraceFilename.c_str());
138 cerr << "Error opening '" << TraceFilename
139 << "'!: Skipping output of trace code as bytecode\n";
142 cerr << "Emitting trace code to '" << TraceFilename
143 << "' for comparison...\n";
144 WriteBytecodeToFile(&M, Out);
150 // Making tracing a module pass so the entire module with tracing
151 // can be written out before continuing.
152 struct InsertTracingCodePass: public Pass {
153 virtual bool run(Module &M) {
154 return insertTraceCodeFor(M);
159 //===---------------------------------------------------------------------===//
162 // Entry point for the llc compiler.
163 //===---------------------------------------------------------------------===//
166 main(int argc, char **argv)
168 cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
170 // Allocate a target... in the future this will be controllable on the
172 std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
173 assert(target.get() && "Could not allocate target machine!");
175 TargetMachine &Target = *target.get();
176 const TargetData &TD = Target.getTargetData();
178 // Load the module to be compiled...
179 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
182 cerr << argv[0] << ": bytecode didn't read correctly.\n";
186 // Build up all of the passes that we want to do to the module...
189 Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getSubWordDataSize(),
190 TD.getIntegerRegSize(), TD.getPointerSize(),
191 TD.getPointerAlignment()));
193 // Create a new optimization pass for each one specified on the command line
194 // Deal specially with tracing passes, which must be run differently than opt.
196 for (unsigned i = 0; i < OptimizationList.size(); ++i)
198 const PassInfo *Opt = OptimizationList[i];
200 if (std::string(Opt->getPassArgument()) == "trace")
201 TraceFunctions = !(TraceBasicBlocks = true);
202 else if (std::string(Opt->getPassArgument()) == "tracem")
203 TraceFunctions = !(TraceBasicBlocks = false);
205 { // handle other passes as normal optimization passes
206 if (Opt->getNormalCtor())
207 Passes.add(Opt->getNormalCtor()());
208 else if (Opt->getTargetCtor())
209 Passes.add(Opt->getTargetCtor()(Target));
211 cerr << argv[0] << ": cannot create pass: "
212 << Opt->getPassName() << "\n";
216 // Run tracing passes after other optimization passes and before llc passes.
217 if (TraceFunctions || TraceBasicBlocks)
218 Passes.add(new InsertTracingCodePass);
220 // Decompose multi-dimensional refs into a sequence of 1D refs
221 Passes.add(createDecomposeMultiDimRefsPass());
223 // Replace malloc and free instructions with library calls.
224 // Do this after tracing until lli implements these lib calls.
225 // For now, it will emulate malloc and free internally.
226 Passes.add(createLowerAllocationsPass());
228 // If LLVM dumping after transformations is requested, add it to the pipeline
230 Passes.add(new PrintFunctionPass("Code after xformations: \n", &cerr));
232 // Strip all of the symbols from the bytecode so that it will be smaller...
233 Passes.add(createSymbolStrippingPass());
235 // Figure out where we are going to send the output...
236 std::ostream *Out = 0;
237 if (OutputFilename != "")
238 { // Specified an output filename?
239 if (!Force && std::ifstream(OutputFilename.c_str())) {
240 // If force is not specified, make sure not to overwrite a file!
241 cerr << argv[0] << ": error opening '" << OutputFilename
242 << "': file exists!\n"
243 << "Use -f command line argument to force output\n";
246 Out = new std::ofstream(OutputFilename.c_str());
248 // Make sure that the Out file gets unlink'd from the disk if we get a
250 RemoveFileOnSignal(OutputFilename);
254 if (InputFilename == "-")
256 OutputFilename = "-";
261 string OutputFilename = GetFileNameRoot(InputFilename);
262 OutputFilename += ".s";
264 if (!Force && std::ifstream(OutputFilename.c_str()))
266 // If force is not specified, make sure not to overwrite a file!
267 cerr << argv[0] << ": error opening '" << OutputFilename
268 << "': file exists!\n"
269 << "Use -f command line argument to force output\n";
273 Out = new std::ofstream(OutputFilename.c_str());
276 cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
281 // Make sure that the Out file gets unlink'd from the disk if we get a
283 RemoveFileOnSignal(OutputFilename);
287 // Ask the target to add backend passes as neccesary
288 if (Target.addPassesToEmitAssembly(Passes, *Out)) {
289 cerr << argv[0] << ": target '" << Target.getName()
290 << " does not support static compilation!\n";
292 // Run our queue of passes all at once now, efficiently.
293 Passes.run(*M.get());
296 // Delete the ostream if it's not a stdout stream
297 if (Out != &std::cout) delete Out;