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