llc.cpp revision 309124
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 17#include "llvm/ADT/STLExtras.h" 18#include "llvm/ADT/Triple.h" 19#include "llvm/Analysis/TargetLibraryInfo.h" 20#include "llvm/CodeGen/CommandFlags.h" 21#include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 22#include "llvm/CodeGen/LinkAllCodegenComponents.h" 23#include "llvm/CodeGen/MIRParser/MIRParser.h" 24#include "llvm/CodeGen/MachineFunctionPass.h" 25#include "llvm/CodeGen/MachineModuleInfo.h" 26#include "llvm/CodeGen/TargetPassConfig.h" 27#include "llvm/IR/DataLayout.h" 28#include "llvm/IR/DiagnosticInfo.h" 29#include "llvm/IR/DiagnosticPrinter.h" 30#include "llvm/IR/IRPrintingPasses.h" 31#include "llvm/IR/LLVMContext.h" 32#include "llvm/IR/LegacyPassManager.h" 33#include "llvm/IR/Module.h" 34#include "llvm/IR/Verifier.h" 35#include "llvm/IRReader/IRReader.h" 36#include "llvm/MC/SubtargetFeature.h" 37#include "llvm/Pass.h" 38#include "llvm/Support/CommandLine.h" 39#include "llvm/Support/Debug.h" 40#include "llvm/Support/FileSystem.h" 41#include "llvm/Support/FormattedStream.h" 42#include "llvm/Support/Host.h" 43#include "llvm/Support/ManagedStatic.h" 44#include "llvm/Support/PluginLoader.h" 45#include "llvm/Support/PrettyStackTrace.h" 46#include "llvm/Support/Signals.h" 47#include "llvm/Support/SourceMgr.h" 48#include "llvm/Support/TargetRegistry.h" 49#include "llvm/Support/TargetSelect.h" 50#include "llvm/Support/ToolOutputFile.h" 51#include "llvm/Target/TargetMachine.h" 52#include "llvm/Target/TargetSubtargetInfo.h" 53#include "llvm/Transforms/Utils/Cloning.h" 54#include <memory> 55using namespace llvm; 56 57// General options for llc. Other pass-specific options are specified 58// within the corresponding llc passes, and target-specific options 59// and back-end code generation options are specified with the target machine. 60// 61static cl::opt<std::string> 62InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 63 64static cl::opt<std::string> 65OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 66 67static cl::opt<unsigned> 68TimeCompilations("time-compilations", cl::Hidden, cl::init(1u), 69 cl::value_desc("N"), 70 cl::desc("Repeat compilation N times for timing")); 71 72static cl::opt<bool> 73NoIntegratedAssembler("no-integrated-as", cl::Hidden, 74 cl::desc("Disable integrated assembler")); 75 76static cl::opt<bool> 77 PreserveComments("preserve-as-comments", cl::Hidden, 78 cl::desc("Preserve Comments in outputted assembly"), 79 cl::init(true)); 80 81// Determine optimization level. 82static cl::opt<char> 83OptLevel("O", 84 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 85 "(default = '-O2')"), 86 cl::Prefix, 87 cl::ZeroOrMore, 88 cl::init(' ')); 89 90static cl::opt<std::string> 91TargetTriple("mtriple", cl::desc("Override target triple for module")); 92 93static cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 94 cl::desc("Do not verify input module")); 95 96static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls", 97 cl::desc("Disable simplify-libcalls")); 98 99static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 100 cl::desc("Show encoding in .s output")); 101 102static cl::opt<bool> EnableDwarfDirectory( 103 "enable-dwarf-directory", cl::Hidden, 104 cl::desc("Use .file directives with an explicit directory.")); 105 106static cl::opt<bool> AsmVerbose("asm-verbose", 107 cl::desc("Add comments to directives."), 108 cl::init(true)); 109 110static cl::opt<bool> 111 CompileTwice("compile-twice", cl::Hidden, 112 cl::desc("Run everything twice, re-using the same pass " 113 "manager and verify the result is the same."), 114 cl::init(false)); 115 116static cl::opt<bool> DiscardValueNames( 117 "discard-value-names", 118 cl::desc("Discard names from Value (other than GlobalValue)."), 119 cl::init(false), cl::Hidden); 120 121namespace { 122static ManagedStatic<std::vector<std::string>> RunPassNames; 123 124struct RunPassOption { 125 void operator=(const std::string &Val) const { 126 if (Val.empty()) 127 return; 128 SmallVector<StringRef, 8> PassNames; 129 StringRef(Val).split(PassNames, ',', -1, false); 130 for (auto PassName : PassNames) 131 RunPassNames->push_back(PassName); 132 } 133}; 134} 135 136static RunPassOption RunPassOpt; 137 138static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass( 139 "run-pass", 140 cl::desc("Run compiler only for specified passes (comma separated list)"), 141 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt)); 142 143static int compileModule(char **, LLVMContext &); 144 145static std::unique_ptr<tool_output_file> 146GetOutputStream(const char *TargetName, Triple::OSType OS, 147 const char *ProgName) { 148 // If we don't yet have an output filename, make one. 149 if (OutputFilename.empty()) { 150 if (InputFilename == "-") 151 OutputFilename = "-"; 152 else { 153 // If InputFilename ends in .bc or .ll, remove it. 154 StringRef IFN = InputFilename; 155 if (IFN.endswith(".bc") || IFN.endswith(".ll")) 156 OutputFilename = IFN.drop_back(3); 157 else if (IFN.endswith(".mir")) 158 OutputFilename = IFN.drop_back(4); 159 else 160 OutputFilename = IFN; 161 162 switch (FileType) { 163 case TargetMachine::CGFT_AssemblyFile: 164 if (TargetName[0] == 'c') { 165 if (TargetName[1] == 0) 166 OutputFilename += ".cbe.c"; 167 else if (TargetName[1] == 'p' && TargetName[2] == 'p') 168 OutputFilename += ".cpp"; 169 else 170 OutputFilename += ".s"; 171 } else 172 OutputFilename += ".s"; 173 break; 174 case TargetMachine::CGFT_ObjectFile: 175 if (OS == Triple::Win32) 176 OutputFilename += ".obj"; 177 else 178 OutputFilename += ".o"; 179 break; 180 case TargetMachine::CGFT_Null: 181 OutputFilename += ".null"; 182 break; 183 } 184 } 185 } 186 187 // Decide if we need "binary" output. 188 bool Binary = false; 189 switch (FileType) { 190 case TargetMachine::CGFT_AssemblyFile: 191 break; 192 case TargetMachine::CGFT_ObjectFile: 193 case TargetMachine::CGFT_Null: 194 Binary = true; 195 break; 196 } 197 198 // Open the file. 199 std::error_code EC; 200 sys::fs::OpenFlags OpenFlags = sys::fs::F_None; 201 if (!Binary) 202 OpenFlags |= sys::fs::F_Text; 203 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC, 204 OpenFlags); 205 if (EC) { 206 errs() << EC.message() << '\n'; 207 return nullptr; 208 } 209 210 return FDOut; 211} 212 213static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) { 214 bool *HasError = static_cast<bool *>(Context); 215 if (DI.getSeverity() == DS_Error) 216 *HasError = true; 217 218 DiagnosticPrinterRawOStream DP(errs()); 219 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": "; 220 DI.print(DP); 221 errs() << "\n"; 222} 223 224// main - Entry point for the llc compiler. 225// 226int main(int argc, char **argv) { 227 sys::PrintStackTraceOnErrorSignal(argv[0]); 228 PrettyStackTraceProgram X(argc, argv); 229 230 // Enable debug stream buffering. 231 EnableDebugBuffering = true; 232 233 LLVMContext Context; 234 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 235 236 // Initialize targets first, so that --version shows registered targets. 237 InitializeAllTargets(); 238 InitializeAllTargetMCs(); 239 InitializeAllAsmPrinters(); 240 InitializeAllAsmParsers(); 241 242 // Initialize codegen and IR passes used by llc so that the -print-after, 243 // -print-before, and -stop-after options work. 244 PassRegistry *Registry = PassRegistry::getPassRegistry(); 245 initializeCore(*Registry); 246 initializeCodeGen(*Registry); 247 initializeLoopStrengthReducePass(*Registry); 248 initializeLowerIntrinsicsPass(*Registry); 249 initializeUnreachableBlockElimLegacyPassPass(*Registry); 250 251 // Register the target printer for --version. 252 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 253 254 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 255 256 Context.setDiscardValueNames(DiscardValueNames); 257 258 // Set a diagnostic handler that doesn't exit on the first error 259 bool HasError = false; 260 Context.setDiagnosticHandler(DiagnosticHandler, &HasError); 261 262 // Compile the module TimeCompilations times to give better compile time 263 // metrics. 264 for (unsigned I = TimeCompilations; I; --I) 265 if (int RetVal = compileModule(argv, Context)) 266 return RetVal; 267 return 0; 268} 269 270static bool addPass(PassManagerBase &PM, const char *argv0, 271 StringRef PassName, TargetPassConfig &TPC) { 272 if (PassName == "none") 273 return false; 274 275 const PassRegistry *PR = PassRegistry::getPassRegistry(); 276 const PassInfo *PI = PR->getPassInfo(PassName); 277 if (!PI) { 278 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n"; 279 return true; 280 } 281 282 Pass *P; 283 if (PI->getTargetMachineCtor()) 284 P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>()); 285 else if (PI->getNormalCtor()) 286 P = PI->getNormalCtor()(); 287 else { 288 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n"; 289 return true; 290 } 291 std::string Banner = std::string("After ") + std::string(P->getPassName()); 292 PM.add(P); 293 TPC.printAndVerify(Banner); 294 295 return false; 296} 297 298static int compileModule(char **argv, LLVMContext &Context) { 299 // Load the module to be compiled... 300 SMDiagnostic Err; 301 std::unique_ptr<Module> M; 302 std::unique_ptr<MIRParser> MIR; 303 Triple TheTriple; 304 305 bool SkipModule = MCPU == "help" || 306 (!MAttrs.empty() && MAttrs.front() == "help"); 307 308 // If user just wants to list available options, skip module loading 309 if (!SkipModule) { 310 if (StringRef(InputFilename).endswith_lower(".mir")) { 311 MIR = createMIRParserFromFile(InputFilename, Err, Context); 312 if (MIR) 313 M = MIR->parseLLVMModule(); 314 } else 315 M = parseIRFile(InputFilename, Err, Context); 316 if (!M) { 317 Err.print(argv[0], errs()); 318 return 1; 319 } 320 321 // Verify module immediately to catch problems before doInitialization() is 322 // called on any passes. 323 if (!NoVerify && verifyModule(*M, &errs())) { 324 errs() << argv[0] << ": " << InputFilename 325 << ": error: input module is broken!\n"; 326 return 1; 327 } 328 329 // If we are supposed to override the target triple, do so now. 330 if (!TargetTriple.empty()) 331 M->setTargetTriple(Triple::normalize(TargetTriple)); 332 TheTriple = Triple(M->getTargetTriple()); 333 } else { 334 TheTriple = Triple(Triple::normalize(TargetTriple)); 335 } 336 337 if (TheTriple.getTriple().empty()) 338 TheTriple.setTriple(sys::getDefaultTargetTriple()); 339 340 // Get the target specific parser. 341 std::string Error; 342 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 343 Error); 344 if (!TheTarget) { 345 errs() << argv[0] << ": " << Error; 346 return 1; 347 } 348 349 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr(); 350 351 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 352 switch (OptLevel) { 353 default: 354 errs() << argv[0] << ": invalid optimization level.\n"; 355 return 1; 356 case ' ': break; 357 case '0': OLvl = CodeGenOpt::None; break; 358 case '1': OLvl = CodeGenOpt::Less; break; 359 case '2': OLvl = CodeGenOpt::Default; break; 360 case '3': OLvl = CodeGenOpt::Aggressive; break; 361 } 362 363 TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); 364 Options.DisableIntegratedAS = NoIntegratedAssembler; 365 Options.MCOptions.ShowMCEncoding = ShowMCEncoding; 366 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; 367 Options.MCOptions.AsmVerbose = AsmVerbose; 368 Options.MCOptions.PreserveAsmComments = PreserveComments; 369 370 std::unique_ptr<TargetMachine> Target( 371 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr, 372 Options, getRelocModel(), CMModel, OLvl)); 373 374 assert(Target && "Could not allocate target machine!"); 375 376 // If we don't have a module then just exit now. We do this down 377 // here since the CPU/Feature help is underneath the target machine 378 // creation. 379 if (SkipModule) 380 return 0; 381 382 assert(M && "Should have exited if we didn't have a module!"); 383 if (FloatABIForCalls != FloatABI::Default) 384 Options.FloatABIType = FloatABIForCalls; 385 386 // Figure out where we are going to send the output. 387 std::unique_ptr<tool_output_file> Out = 388 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]); 389 if (!Out) return 1; 390 391 // Build up all of the passes that we want to do to the module. 392 legacy::PassManager PM; 393 394 // Add an appropriate TargetLibraryInfo pass for the module's triple. 395 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple())); 396 397 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 398 if (DisableSimplifyLibCalls) 399 TLII.disableAllFunctions(); 400 PM.add(new TargetLibraryInfoWrapperPass(TLII)); 401 402 // Add the target data from the target machine, if it exists, or the module. 403 M->setDataLayout(Target->createDataLayout()); 404 405 // Override function attributes based on CPUStr, FeaturesStr, and command line 406 // flags. 407 setFunctionAttributes(CPUStr, FeaturesStr, *M); 408 409 if (RelaxAll.getNumOccurrences() > 0 && 410 FileType != TargetMachine::CGFT_ObjectFile) 411 errs() << argv[0] 412 << ": warning: ignoring -mc-relax-all because filetype != obj"; 413 414 { 415 raw_pwrite_stream *OS = &Out->os(); 416 417 // Manually do the buffering rather than using buffer_ostream, 418 // so we can memcmp the contents in CompileTwice mode 419 SmallVector<char, 0> Buffer; 420 std::unique_ptr<raw_svector_ostream> BOS; 421 if ((FileType != TargetMachine::CGFT_AssemblyFile && 422 !Out->os().supportsSeeking()) || 423 CompileTwice) { 424 BOS = make_unique<raw_svector_ostream>(Buffer); 425 OS = BOS.get(); 426 } 427 428 AnalysisID StartBeforeID = nullptr; 429 AnalysisID StartAfterID = nullptr; 430 AnalysisID StopAfterID = nullptr; 431 const PassRegistry *PR = PassRegistry::getPassRegistry(); 432 if (!RunPassNames->empty()) { 433 if (!StartAfter.empty() || !StopAfter.empty()) { 434 errs() << argv[0] << ": start-after and/or stop-after passes are " 435 "redundant when run-pass is specified.\n"; 436 return 1; 437 } 438 if (!MIR) { 439 errs() << argv[0] << ": run-pass needs a .mir input.\n"; 440 return 1; 441 } 442 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target); 443 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM); 444 PM.add(&TPC); 445 LLVMTM.addMachineModuleInfo(PM); 446 LLVMTM.addMachineFunctionAnalysis(PM, MIR.get()); 447 TPC.printAndVerify(""); 448 449 for (const std::string &RunPassName : *RunPassNames) { 450 if (addPass(PM, argv[0], RunPassName, TPC)) 451 return 1; 452 } 453 PM.add(createPrintMIRPass(*OS)); 454 } else { 455 if (!StartAfter.empty()) { 456 const PassInfo *PI = PR->getPassInfo(StartAfter); 457 if (!PI) { 458 errs() << argv[0] << ": start-after pass is not registered.\n"; 459 return 1; 460 } 461 StartAfterID = PI->getTypeInfo(); 462 } 463 if (!StopAfter.empty()) { 464 const PassInfo *PI = PR->getPassInfo(StopAfter); 465 if (!PI) { 466 errs() << argv[0] << ": stop-after pass is not registered.\n"; 467 return 1; 468 } 469 StopAfterID = PI->getTypeInfo(); 470 } 471 472 // Ask the target to add backend passes as necessary. 473 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, 474 StartBeforeID, StartAfterID, StopAfterID, 475 MIR.get())) { 476 errs() << argv[0] << ": target does not support generation of this" 477 << " file type!\n"; 478 return 1; 479 } 480 } 481 482 // Before executing passes, print the final values of the LLVM options. 483 cl::PrintOptionValues(); 484 485 // If requested, run the pass manager over the same module again, 486 // to catch any bugs due to persistent state in the passes. Note that 487 // opt has the same functionality, so it may be worth abstracting this out 488 // in the future. 489 SmallVector<char, 0> CompileTwiceBuffer; 490 if (CompileTwice) { 491 std::unique_ptr<Module> M2(llvm::CloneModule(M.get())); 492 PM.run(*M2); 493 CompileTwiceBuffer = Buffer; 494 Buffer.clear(); 495 } 496 497 PM.run(*M); 498 499 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext()); 500 if (HasError) 501 return 1; 502 503 // Compare the two outputs and make sure they're the same 504 if (CompileTwice) { 505 if (Buffer.size() != CompileTwiceBuffer.size() || 506 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 507 0)) { 508 errs() 509 << "Running the pass manager twice changed the output.\n" 510 "Writing the result of the second run to the specified output\n" 511 "To generate the one-run comparison binary, just run without\n" 512 "the compile-twice option\n"; 513 Out->os() << Buffer; 514 Out->keep(); 515 return 1; 516 } 517 } 518 519 if (BOS) { 520 Out->os() << Buffer; 521 } 522 } 523 524 // Declare success. 525 Out->keep(); 526 527 return 0; 528} 529