llc.cpp revision 2388a588bdf32610e18a66c0c6ef248087fd1cdc
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/Bitcode/ReaderWriter.h" 17#include "llvm/CodeGen/FileWriters.h" 18#include "llvm/CodeGen/LinkAllCodegenComponents.h" 19#include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 20#include "llvm/Target/SubtargetFeature.h" 21#include "llvm/Target/TargetData.h" 22#include "llvm/Target/TargetMachine.h" 23#include "llvm/Target/TargetMachineRegistry.h" 24#include "llvm/Transforms/Scalar.h" 25#include "llvm/Module.h" 26#include "llvm/ModuleProvider.h" 27#include "llvm/PassManager.h" 28#include "llvm/Pass.h" 29#include "llvm/Support/CommandLine.h" 30#include "llvm/Support/FileUtilities.h" 31#include "llvm/Support/ManagedStatic.h" 32#include "llvm/Support/MemoryBuffer.h" 33#include "llvm/Support/PluginLoader.h" 34#include "llvm/Support/RegistryParser.h" 35#include "llvm/Support/raw_ostream.h" 36#include "llvm/Analysis/Verifier.h" 37#include "llvm/System/Signals.h" 38#include "llvm/Config/config.h" 39#include "llvm/LinkAllVMCore.h" 40#include <fstream> 41#include <iostream> 42#include <memory> 43using namespace llvm; 44 45// General options for llc. Other pass-specific options are specified 46// within the corresponding llc passes, and target-specific options 47// and back-end code generation options are specified with the target machine. 48// 49static cl::opt<std::string> 50InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 51 52static cl::opt<std::string> 53OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 54 55static cl::opt<bool> Force("f", cl::desc("Overwrite output files")); 56 57static cl::opt<bool> Fast("fast", 58 cl::desc("Generate code quickly, potentially sacrificing code quality")); 59 60static cl::opt<std::string> 61TargetTriple("mtriple", cl::desc("Override target triple for module")); 62 63static cl::opt<const TargetMachineRegistry::entry*, false, 64 RegistryParser<TargetMachine> > 65MArch("march", cl::desc("Architecture to generate code for:")); 66 67static cl::opt<std::string> 68MCPU("mcpu", 69 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 70 cl::value_desc("cpu-name"), 71 cl::init("")); 72 73static cl::list<std::string> 74MAttrs("mattr", 75 cl::CommaSeparated, 76 cl::desc("Target specific attributes (-mattr=help for details)"), 77 cl::value_desc("a1,+a2,-a3,...")); 78 79cl::opt<TargetMachine::CodeGenFileType> 80FileType("filetype", cl::init(TargetMachine::AssemblyFile), 81 cl::desc("Choose a file type (not all types are supported by all targets):"), 82 cl::values( 83 clEnumValN(TargetMachine::AssemblyFile, "asm", 84 "Emit an assembly ('.s') file"), 85 clEnumValN(TargetMachine::ObjectFile, "obj", 86 "Emit a native object ('.o') file [experimental]"), 87 clEnumValN(TargetMachine::DynamicLibrary, "dynlib", 88 "Emit a native dynamic library ('.so') file" 89 " [experimental]"), 90 clEnumValEnd)); 91 92cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 93 cl::desc("Do not verify input module")); 94 95 96// GetFileNameRoot - Helper function to get the basename of a filename. 97static inline std::string 98GetFileNameRoot(const std::string &InputFilename) { 99 std::string IFN = InputFilename; 100 std::string outputFilename; 101 int Len = IFN.length(); 102 if ((Len > 2) && 103 IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') { 104 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ 105 } else { 106 outputFilename = IFN; 107 } 108 return outputFilename; 109} 110 111static raw_ostream *GetOutputStream(const char *ProgName) { 112 if (OutputFilename != "") { 113 if (OutputFilename == "-") 114 return &outs(); 115 116 // Specified an output filename? 117 if (!Force && std::ifstream(OutputFilename.c_str())) { 118 // If force is not specified, make sure not to overwrite a file! 119 std::cerr << ProgName << ": error opening '" << OutputFilename 120 << "': file exists!\n" 121 << "Use -f command line argument to force output\n"; 122 return 0; 123 } 124 // Make sure that the Out file gets unlinked from the disk if we get a 125 // SIGINT 126 sys::RemoveFileOnSignal(sys::Path(OutputFilename)); 127 128 std::string error; 129 raw_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), true, error); 130 if (!error.empty()) { 131 std::cerr << error << '\n'; 132 delete Out; 133 return 0; 134 } 135 136 return Out; 137 } 138 139 if (InputFilename == "-") { 140 OutputFilename = "-"; 141 return &outs(); 142 } 143 144 OutputFilename = GetFileNameRoot(InputFilename); 145 146 bool Binary = false; 147 switch (FileType) { 148 case TargetMachine::AssemblyFile: 149 if (MArch->Name[0] == 'c') { 150 if (MArch->Name[1] == 0) 151 OutputFilename += ".cbe.c"; 152 else if (MArch->Name[1] == 'p' && MArch->Name[2] == 'p') 153 OutputFilename += ".cpp"; 154 else 155 OutputFilename += ".s"; 156 } else 157 OutputFilename += ".s"; 158 break; 159 case TargetMachine::ObjectFile: 160 OutputFilename += ".o"; 161 Binary = true; 162 break; 163 case TargetMachine::DynamicLibrary: 164 OutputFilename += LTDL_SHLIB_EXT; 165 Binary = true; 166 break; 167 } 168 169 if (!Force && std::ifstream(OutputFilename.c_str())) { 170 // If force is not specified, make sure not to overwrite a file! 171 std::cerr << ProgName << ": error opening '" << OutputFilename 172 << "': file exists!\n" 173 << "Use -f command line argument to force output\n"; 174 return 0; 175 } 176 177 // Make sure that the Out file gets unlinked from the disk if we get a 178 // SIGINT 179 sys::RemoveFileOnSignal(sys::Path(OutputFilename)); 180 181 std::string error; 182 raw_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Binary, error); 183 if (!error.empty()) { 184 std::cerr << error << '\n'; 185 delete Out; 186 return 0; 187 } 188 189 return Out; 190} 191 192// main - Entry point for the llc compiler. 193// 194int main(int argc, char **argv) { 195 llvm_shutdown_obj X; // Call llvm_shutdown() on exit. 196 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 197 sys::PrintStackTraceOnErrorSignal(); 198 199 // Load the module to be compiled... 200 std::string ErrorMessage; 201 std::auto_ptr<Module> M; 202 203 std::auto_ptr<MemoryBuffer> Buffer( 204 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)); 205 if (Buffer.get()) 206 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage)); 207 if (M.get() == 0) { 208 std::cerr << argv[0] << ": bitcode didn't read correctly.\n"; 209 std::cerr << "Reason: " << ErrorMessage << "\n"; 210 return 1; 211 } 212 Module &mod = *M.get(); 213 214 // If we are supposed to override the target triple, do so now. 215 if (!TargetTriple.empty()) 216 mod.setTargetTriple(TargetTriple); 217 218 // Allocate target machine. First, check whether the user has 219 // explicitly specified an architecture to compile for. 220 if (MArch == 0) { 221 std::string Err; 222 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err); 223 if (MArch == 0) { 224 std::cerr << argv[0] << ": error auto-selecting target for module '" 225 << Err << "'. Please use the -march option to explicitly " 226 << "pick a target.\n"; 227 return 1; 228 } 229 } 230 231 // Package up features to be passed to target/subtarget 232 std::string FeaturesStr; 233 if (MCPU.size() || MAttrs.size()) { 234 SubtargetFeatures Features; 235 Features.setCPU(MCPU); 236 for (unsigned i = 0; i != MAttrs.size(); ++i) 237 Features.AddFeature(MAttrs[i]); 238 FeaturesStr = Features.getString(); 239 } 240 241 std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr)); 242 assert(target.get() && "Could not allocate target machine!"); 243 TargetMachine &Target = *target.get(); 244 245 // Figure out where we are going to send the output... 246 raw_ostream *Out = GetOutputStream(argv[0]); 247 if (Out == 0) return 1; 248 249 // If this target requires addPassesToEmitWholeFile, do it now. This is 250 // used by strange things like the C backend. 251 if (Target.WantsWholeFile()) { 252 PassManager PM; 253 PM.add(new TargetData(*Target.getTargetData())); 254 if (!NoVerify) 255 PM.add(createVerifierPass()); 256 257 // Ask the target to add backend passes as necessary. 258 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) { 259 std::cerr << argv[0] << ": target does not support generation of this" 260 << " file type!\n"; 261 if (Out != &outs()) delete Out; 262 // And the Out file is empty and useless, so remove it now. 263 sys::Path(OutputFilename).eraseFromDisk(); 264 return 1; 265 } 266 PM.run(mod); 267 } else { 268 // Build up all of the passes that we want to do to the module. 269 ExistingModuleProvider Provider(M.release()); 270 FunctionPassManager Passes(&Provider); 271 Passes.add(new TargetData(*Target.getTargetData())); 272 273#ifndef NDEBUG 274 if (!NoVerify) 275 Passes.add(createVerifierPass()); 276#endif 277 278 // Ask the target to add backend passes as necessary. 279 MachineCodeEmitter *MCE = 0; 280 281 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) { 282 default: 283 assert(0 && "Invalid file model!"); 284 return 1; 285 case FileModel::Error: 286 std::cerr << argv[0] << ": target does not support generation of this" 287 << " file type!\n"; 288 if (Out != &outs()) delete Out; 289 // And the Out file is empty and useless, so remove it now. 290 sys::Path(OutputFilename).eraseFromDisk(); 291 return 1; 292 case FileModel::AsmFile: 293 break; 294 case FileModel::MachOFile: 295 MCE = AddMachOWriter(Passes, *Out, Target); 296 break; 297 case FileModel::ElfFile: 298 MCE = AddELFWriter(Passes, *Out, Target); 299 break; 300 } 301 302 if (Target.addPassesToEmitFileFinish(Passes, MCE, Fast)) { 303 std::cerr << argv[0] << ": target does not support generation of this" 304 << " file type!\n"; 305 if (Out != &outs()) delete Out; 306 // And the Out file is empty and useless, so remove it now. 307 sys::Path(OutputFilename).eraseFromDisk(); 308 return 1; 309 } 310 311 Passes.doInitialization(); 312 313 // Run our queue of passes all at once now, efficiently. 314 // TODO: this could lazily stream functions out of the module. 315 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I) 316 if (!I->isDeclaration()) 317 Passes.run(*I); 318 319 Passes.doFinalization(); 320 } 321 322 // Delete the ostream if it's not a stdout stream 323 if (Out != &outs()) delete Out; 324 325 return 0; 326} 327