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