llc.cpp revision c58d01b235fb6aba9edb49f6dbe08edaa756a873
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/LLVMContext.h" 17#include "llvm/Module.h" 18#include "llvm/ModuleProvider.h" 19#include "llvm/PassManager.h" 20#include "llvm/Pass.h" 21#include "llvm/ADT/Triple.h" 22#include "llvm/Analysis/Verifier.h" 23#include "llvm/Support/IRReader.h" 24#include "llvm/CodeGen/FileWriters.h" 25#include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 26#include "llvm/CodeGen/LinkAllCodegenComponents.h" 27#include "llvm/CodeGen/ObjectCodeEmitter.h" 28#include "llvm/Config/config.h" 29#include "llvm/LinkAllVMCore.h" 30#include "llvm/Support/CommandLine.h" 31#include "llvm/Support/Debug.h" 32#include "llvm/Support/FileUtilities.h" 33#include "llvm/Support/FormattedStream.h" 34#include "llvm/Support/ManagedStatic.h" 35#include "llvm/Support/MemoryBuffer.h" 36#include "llvm/Support/PluginLoader.h" 37#include "llvm/Support/PrettyStackTrace.h" 38#include "llvm/System/Host.h" 39#include "llvm/System/Signals.h" 40#include "llvm/Target/SubtargetFeature.h" 41#include "llvm/Target/TargetData.h" 42#include "llvm/Target/TargetMachine.h" 43#include "llvm/Target/TargetRegistry.h" 44#include "llvm/Target/TargetSelect.h" 45#include "llvm/Transforms/Scalar.h" 46#include <memory> 47using namespace llvm; 48 49// General options for llc. Other pass-specific options are specified 50// within the corresponding llc passes, and target-specific options 51// and back-end code generation options are specified with the target machine. 52// 53static cl::opt<std::string> 54InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 55 56static cl::opt<std::string> 57OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 58 59static cl::opt<bool> 60Force("f", cl::desc("Enable binary output on terminals")); 61 62// Determine optimization level. 63static cl::opt<char> 64OptLevel("O", 65 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 66 "(default = '-O2')"), 67 cl::Prefix, 68 cl::ZeroOrMore, 69 cl::init(' ')); 70 71static cl::opt<std::string> 72TargetTriple("mtriple", cl::desc("Override target triple for module")); 73 74static cl::opt<std::string> 75MArch("march", cl::desc("Architecture to generate code for (see --version)")); 76 77static cl::opt<std::string> 78MCPU("mcpu", 79 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 80 cl::value_desc("cpu-name"), 81 cl::init("")); 82 83static cl::list<std::string> 84MAttrs("mattr", 85 cl::CommaSeparated, 86 cl::desc("Target specific attributes (-mattr=help for details)"), 87 cl::value_desc("a1,+a2,-a3,...")); 88 89cl::opt<TargetMachine::CodeGenFileType> 90FileType("filetype", cl::init(TargetMachine::AssemblyFile), 91 cl::desc("Choose a file type (not all types are supported by all targets):"), 92 cl::values( 93 clEnumValN(TargetMachine::AssemblyFile, "asm", 94 "Emit an assembly ('.s') file"), 95 clEnumValN(TargetMachine::ObjectFile, "obj", 96 "Emit a native object ('.o') file [experimental]"), 97 clEnumValN(TargetMachine::DynamicLibrary, "dynlib", 98 "Emit a native dynamic library ('.so') file" 99 " [experimental]"), 100 clEnumValEnd)); 101 102cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 103 cl::desc("Do not verify input module")); 104 105 106static cl::opt<bool> 107DisableRedZone("disable-red-zone", 108 cl::desc("Do not emit code that uses the red zone."), 109 cl::init(false)); 110 111static cl::opt<bool> 112NoImplicitFloats("no-implicit-float", 113 cl::desc("Don't generate implicit floating point instructions (x86-only)"), 114 cl::init(false)); 115 116// GetFileNameRoot - Helper function to get the basename of a filename. 117static inline std::string 118GetFileNameRoot(const std::string &InputFilename) { 119 std::string IFN = InputFilename; 120 std::string outputFilename; 121 int Len = IFN.length(); 122 if ((Len > 2) && 123 IFN[Len-3] == '.' && 124 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') || 125 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) { 126 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ 127 } else { 128 outputFilename = IFN; 129 } 130 return outputFilename; 131} 132 133static formatted_raw_ostream *GetOutputStream(const char *TargetName, 134 const char *ProgName) { 135 if (OutputFilename != "") { 136 if (OutputFilename == "-") 137 return &fouts(); 138 139 // Make sure that the Out file gets unlinked from the disk if we get a 140 // SIGINT 141 sys::RemoveFileOnSignal(sys::Path(OutputFilename)); 142 143 std::string error; 144 raw_fd_ostream *FDOut = 145 new raw_fd_ostream(OutputFilename.c_str(), error, 146 raw_fd_ostream::F_Binary); 147 if (!error.empty()) { 148 errs() << error << '\n'; 149 delete FDOut; 150 return 0; 151 } 152 formatted_raw_ostream *Out = 153 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM); 154 155 return Out; 156 } 157 158 if (InputFilename == "-") { 159 OutputFilename = "-"; 160 return &fouts(); 161 } 162 163 OutputFilename = GetFileNameRoot(InputFilename); 164 165 bool Binary = false; 166 switch (FileType) { 167 case TargetMachine::AssemblyFile: 168 if (TargetName[0] == 'c') { 169 if (TargetName[1] == 0) 170 OutputFilename += ".cbe.c"; 171 else if (TargetName[1] == 'p' && TargetName[2] == 'p') 172 OutputFilename += ".cpp"; 173 else 174 OutputFilename += ".s"; 175 } else 176 OutputFilename += ".s"; 177 break; 178 case TargetMachine::ObjectFile: 179 OutputFilename += ".o"; 180 Binary = true; 181 break; 182 case TargetMachine::DynamicLibrary: 183 OutputFilename += LTDL_SHLIB_EXT; 184 Binary = true; 185 break; 186 } 187 188 // Make sure that the Out file gets unlinked from the disk if we get a 189 // SIGINT 190 sys::RemoveFileOnSignal(sys::Path(OutputFilename)); 191 192 std::string error; 193 unsigned OpenFlags = 0; 194 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary; 195 raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error, 196 OpenFlags); 197 if (!error.empty()) { 198 errs() << error << '\n'; 199 delete FDOut; 200 return 0; 201 } 202 203 formatted_raw_ostream *Out = 204 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM); 205 206 return Out; 207} 208 209// main - Entry point for the llc compiler. 210// 211int main(int argc, char **argv) { 212 sys::PrintStackTraceOnErrorSignal(); 213 PrettyStackTraceProgram X(argc, argv); 214 215 // Enable debug stream buffering. 216 EnableDebugBuffering = true; 217 218 LLVMContext &Context = getGlobalContext(); 219 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 220 221 // Initialize targets first, so that --version shows registered targets. 222 InitializeAllTargets(); 223 InitializeAllAsmPrinters(); 224 225 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 226 227 // Load the module to be compiled... 228 SMDiagnostic Err; 229 std::auto_ptr<Module> M; 230 231 M.reset(ParseIRFile(InputFilename, Err, Context)); 232 if (M.get() == 0) { 233 Err.Print(argv[0], errs()); 234 return 1; 235 } 236 Module &mod = *M.get(); 237 238 // If we are supposed to override the target triple, do so now. 239 if (!TargetTriple.empty()) 240 mod.setTargetTriple(TargetTriple); 241 242 Triple TheTriple(mod.getTargetTriple()); 243 if (TheTriple.getTriple().empty()) 244 TheTriple.setTriple(sys::getHostTriple()); 245 246 // Allocate target machine. First, check whether the user has explicitly 247 // specified an architecture to compile for. If so we have to look it up by 248 // name, because it might be a backend that has no mapping to a target triple. 249 const Target *TheTarget = 0; 250 if (!MArch.empty()) { 251 for (TargetRegistry::iterator it = TargetRegistry::begin(), 252 ie = TargetRegistry::end(); it != ie; ++it) { 253 if (MArch == it->getName()) { 254 TheTarget = &*it; 255 break; 256 } 257 } 258 259 if (!TheTarget) { 260 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n"; 261 return 1; 262 } 263 264 // Adjust the triple to match (if known), otherwise stick with the 265 // module/host triple. 266 Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch); 267 if (Type != Triple::UnknownArch) 268 TheTriple.setArch(Type); 269 } else { 270 std::string Err; 271 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err); 272 if (TheTarget == 0) { 273 errs() << argv[0] << ": error auto-selecting target for module '" 274 << Err << "'. Please use the -march option to explicitly " 275 << "pick a target.\n"; 276 return 1; 277 } 278 } 279 280 // Package up features to be passed to target/subtarget 281 std::string FeaturesStr; 282 if (MCPU.size() || MAttrs.size()) { 283 SubtargetFeatures Features; 284 Features.setCPU(MCPU); 285 for (unsigned i = 0; i != MAttrs.size(); ++i) 286 Features.AddFeature(MAttrs[i]); 287 FeaturesStr = Features.getString(); 288 } 289 290 std::auto_ptr<TargetMachine> 291 target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr)); 292 assert(target.get() && "Could not allocate target machine!"); 293 TargetMachine &Target = *target.get(); 294 295 // Figure out where we are going to send the output... 296 formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(), argv[0]); 297 if (Out == 0) return 1; 298 299 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 300 switch (OptLevel) { 301 default: 302 errs() << argv[0] << ": invalid optimization level.\n"; 303 return 1; 304 case ' ': break; 305 case '0': OLvl = CodeGenOpt::None; break; 306 case '1': OLvl = CodeGenOpt::Less; break; 307 case '2': OLvl = CodeGenOpt::Default; break; 308 case '3': OLvl = CodeGenOpt::Aggressive; break; 309 } 310 311 // If this target requires addPassesToEmitWholeFile, do it now. This is 312 // used by strange things like the C backend. 313 if (Target.WantsWholeFile()) { 314 PassManager PM; 315 316 // Add the target data from the target machine, if it exists, or the module. 317 if (const TargetData *TD = Target.getTargetData()) 318 PM.add(new TargetData(*TD)); 319 else 320 PM.add(new TargetData(&mod)); 321 322 if (!NoVerify) 323 PM.add(createVerifierPass()); 324 325 // Ask the target to add backend passes as necessary. 326 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, OLvl)) { 327 errs() << argv[0] << ": target does not support generation of this" 328 << " file type!\n"; 329 if (Out != &fouts()) delete Out; 330 // And the Out file is empty and useless, so remove it now. 331 sys::Path(OutputFilename).eraseFromDisk(); 332 return 1; 333 } 334 PM.run(mod); 335 } else { 336 // Build up all of the passes that we want to do to the module. 337 ExistingModuleProvider Provider(M.release()); 338 FunctionPassManager Passes(&Provider); 339 340 // Add the target data from the target machine, if it exists, or the module. 341 if (const TargetData *TD = Target.getTargetData()) 342 Passes.add(new TargetData(*TD)); 343 else 344 Passes.add(new TargetData(&mod)); 345 346#ifndef NDEBUG 347 if (!NoVerify) 348 Passes.add(createVerifierPass()); 349#endif 350 351 // Ask the target to add backend passes as necessary. 352 ObjectCodeEmitter *OCE = 0; 353 354 // Override default to generate verbose assembly. 355 Target.setAsmVerbosityDefault(true); 356 357 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, OLvl)) { 358 default: 359 assert(0 && "Invalid file model!"); 360 return 1; 361 case FileModel::Error: 362 errs() << argv[0] << ": target does not support generation of this" 363 << " file type!\n"; 364 if (Out != &fouts()) delete Out; 365 // And the Out file is empty and useless, so remove it now. 366 sys::Path(OutputFilename).eraseFromDisk(); 367 return 1; 368 case FileModel::AsmFile: 369 break; 370 case FileModel::MachOFile: 371 OCE = AddMachOWriter(Passes, *Out, Target); 372 break; 373 case FileModel::ElfFile: 374 OCE = AddELFWriter(Passes, *Out, Target); 375 break; 376 } 377 378 if (Target.addPassesToEmitFileFinish(Passes, OCE, OLvl)) { 379 errs() << argv[0] << ": target does not support generation of this" 380 << " file type!\n"; 381 if (Out != &fouts()) delete Out; 382 // And the Out file is empty and useless, so remove it now. 383 sys::Path(OutputFilename).eraseFromDisk(); 384 return 1; 385 } 386 387 Passes.doInitialization(); 388 389 // Run our queue of passes all at once now, efficiently. 390 // TODO: this could lazily stream functions out of the module. 391 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I) 392 if (!I->isDeclaration()) { 393 if (DisableRedZone) 394 I->addFnAttr(Attribute::NoRedZone); 395 if (NoImplicitFloats) 396 I->addFnAttr(Attribute::NoImplicitFloat); 397 Passes.run(*I); 398 } 399 400 Passes.doFinalization(); 401 } 402 403 // Delete the ostream if it's not a stdout stream 404 if (Out != &fouts()) delete Out; 405 406 return 0; 407} 408