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