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