llc.cpp revision 249423
1193323Sed//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This is the llc code generator driver. It provides a convenient 11193323Sed// command-line interface for generating native assembly-language code 12193323Sed// or C code, given LLVM bitcode. 13193323Sed// 14193323Sed//===----------------------------------------------------------------------===// 15193323Sed 16249423Sdim#include "llvm/IR/LLVMContext.h" 17198090Srdivacky#include "llvm/ADT/Triple.h" 18239462Sdim#include "llvm/Assembly/PrintModulePass.h" 19243830Sdim#include "llvm/CodeGen/CommandFlags.h" 20198090Srdivacky#include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 21198090Srdivacky#include "llvm/CodeGen/LinkAllCodegenComponents.h" 22249423Sdim#include "llvm/IR/DataLayout.h" 23249423Sdim#include "llvm/IR/Module.h" 24249423Sdim#include "llvm/IRReader/IRReader.h" 25224133Sdim#include "llvm/MC/SubtargetFeature.h" 26249423Sdim#include "llvm/Pass.h" 27249423Sdim#include "llvm/PassManager.h" 28193323Sed#include "llvm/Support/CommandLine.h" 29202375Srdivacky#include "llvm/Support/Debug.h" 30198090Srdivacky#include "llvm/Support/FormattedStream.h" 31249423Sdim#include "llvm/Support/Host.h" 32193323Sed#include "llvm/Support/ManagedStatic.h" 33193323Sed#include "llvm/Support/PluginLoader.h" 34193323Sed#include "llvm/Support/PrettyStackTrace.h" 35218885Sdim#include "llvm/Support/Signals.h" 36249423Sdim#include "llvm/Support/SourceMgr.h" 37226584Sdim#include "llvm/Support/TargetRegistry.h" 38226584Sdim#include "llvm/Support/TargetSelect.h" 39249423Sdim#include "llvm/Support/ToolOutputFile.h" 40239462Sdim#include "llvm/Target/TargetLibraryInfo.h" 41198090Srdivacky#include "llvm/Target/TargetMachine.h" 42193323Sed#include <memory> 43193323Sedusing namespace llvm; 44193323Sed 45193323Sed// General options for llc. Other pass-specific options are specified 46193323Sed// within the corresponding llc passes, and target-specific options 47193323Sed// and back-end code generation options are specified with the target machine. 48193323Sed// 49193323Sedstatic cl::opt<std::string> 50193323SedInputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 51193323Sed 52193323Sedstatic cl::opt<std::string> 53193323SedOutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 54193323Sed 55249423Sdimstatic cl::opt<unsigned> 56249423SdimTimeCompilations("time-compilations", cl::Hidden, cl::init(1u), 57249423Sdim cl::value_desc("N"), 58249423Sdim cl::desc("Repeat compilation N times for timing")); 59249423Sdim 60193323Sed// Determine optimization level. 61193323Sedstatic cl::opt<char> 62193323SedOptLevel("O", 63193323Sed cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 64193323Sed "(default = '-O2')"), 65193323Sed cl::Prefix, 66193323Sed cl::ZeroOrMore, 67193323Sed cl::init(' ')); 68193323Sed 69193323Sedstatic cl::opt<std::string> 70193323SedTargetTriple("mtriple", cl::desc("Override target triple for module")); 71193323Sed 72193323Sedcl::opt<bool> NoVerify("disable-verify", cl::Hidden, 73193323Sed cl::desc("Do not verify input module")); 74193323Sed 75243830Sdimcl::opt<bool> 76239462SdimDisableSimplifyLibCalls("disable-simplify-libcalls", 77243830Sdim cl::desc("Disable simplify-libcalls"), 78243830Sdim cl::init(false)); 79239462Sdim 80249423Sdimstatic int compileModule(char**, LLVMContext&); 81249423Sdim 82193323Sed// GetFileNameRoot - Helper function to get the basename of a filename. 83193323Sedstatic inline std::string 84193323SedGetFileNameRoot(const std::string &InputFilename) { 85193323Sed std::string IFN = InputFilename; 86193323Sed std::string outputFilename; 87193323Sed int Len = IFN.length(); 88193323Sed if ((Len > 2) && 89198090Srdivacky IFN[Len-3] == '.' && 90198090Srdivacky ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') || 91198090Srdivacky (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) { 92193323Sed outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ 93193323Sed } else { 94193323Sed outputFilename = IFN; 95193323Sed } 96193323Sed return outputFilename; 97193323Sed} 98193323Sed 99212793Sdimstatic tool_output_file *GetOutputStream(const char *TargetName, 100212793Sdim Triple::OSType OS, 101212793Sdim const char *ProgName) { 102212793Sdim // If we don't yet have an output filename, make one. 103212793Sdim if (OutputFilename.empty()) { 104212793Sdim if (InputFilename == "-") 105212793Sdim OutputFilename = "-"; 106212793Sdim else { 107212793Sdim OutputFilename = GetFileNameRoot(InputFilename); 108193323Sed 109212793Sdim switch (FileType) { 110212793Sdim case TargetMachine::CGFT_AssemblyFile: 111212793Sdim if (TargetName[0] == 'c') { 112212793Sdim if (TargetName[1] == 0) 113212793Sdim OutputFilename += ".cbe.c"; 114212793Sdim else if (TargetName[1] == 'p' && TargetName[2] == 'p') 115212793Sdim OutputFilename += ".cpp"; 116212793Sdim else 117212793Sdim OutputFilename += ".s"; 118212793Sdim } else 119212793Sdim OutputFilename += ".s"; 120212793Sdim break; 121212793Sdim case TargetMachine::CGFT_ObjectFile: 122212793Sdim if (OS == Triple::Win32) 123212793Sdim OutputFilename += ".obj"; 124212793Sdim else 125212793Sdim OutputFilename += ".o"; 126212793Sdim break; 127212793Sdim case TargetMachine::CGFT_Null: 128212793Sdim OutputFilename += ".null"; 129212793Sdim break; 130212793Sdim } 131193323Sed } 132193323Sed } 133193323Sed 134212793Sdim // Decide if we need "binary" output. 135193323Sed bool Binary = false; 136193323Sed switch (FileType) { 137203954Srdivacky case TargetMachine::CGFT_AssemblyFile: 138193323Sed break; 139203954Srdivacky case TargetMachine::CGFT_ObjectFile: 140203954Srdivacky case TargetMachine::CGFT_Null: 141193323Sed Binary = true; 142193323Sed break; 143193323Sed } 144193323Sed 145212793Sdim // Open the file. 146193323Sed std::string error; 147198090Srdivacky unsigned OpenFlags = 0; 148198090Srdivacky if (Binary) OpenFlags |= raw_fd_ostream::F_Binary; 149212793Sdim tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error, 150212793Sdim OpenFlags); 151193323Sed if (!error.empty()) { 152198090Srdivacky errs() << error << '\n'; 153198090Srdivacky delete FDOut; 154193323Sed return 0; 155193323Sed } 156193323Sed 157212793Sdim return FDOut; 158193323Sed} 159193323Sed 160193323Sed// main - Entry point for the llc compiler. 161193323Sed// 162193323Sedint main(int argc, char **argv) { 163193323Sed sys::PrintStackTraceOnErrorSignal(); 164193323Sed PrettyStackTraceProgram X(argc, argv); 165202375Srdivacky 166202375Srdivacky // Enable debug stream buffering. 167202375Srdivacky EnableDebugBuffering = true; 168202375Srdivacky 169198090Srdivacky LLVMContext &Context = getGlobalContext(); 170193323Sed llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 171193323Sed 172198090Srdivacky // Initialize targets first, so that --version shows registered targets. 173194612Sed InitializeAllTargets(); 174226584Sdim InitializeAllTargetMCs(); 175194612Sed InitializeAllAsmPrinters(); 176206274Srdivacky InitializeAllAsmParsers(); 177198090Srdivacky 178239462Sdim // Initialize codegen and IR passes used by llc so that the -print-after, 179239462Sdim // -print-before, and -stop-after options work. 180239462Sdim PassRegistry *Registry = PassRegistry::getPassRegistry(); 181239462Sdim initializeCore(*Registry); 182239462Sdim initializeCodeGen(*Registry); 183239462Sdim initializeLoopStrengthReducePass(*Registry); 184239462Sdim initializeLowerIntrinsicsPass(*Registry); 185239462Sdim initializeUnreachableBlockElimPass(*Registry); 186239462Sdim 187226584Sdim // Register the target printer for --version. 188226584Sdim cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 189226584Sdim 190198090Srdivacky cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 191221337Sdim 192249423Sdim // Compile the module TimeCompilations times to give better compile time 193249423Sdim // metrics. 194249423Sdim for (unsigned I = TimeCompilations; I; --I) 195249423Sdim if (int RetVal = compileModule(argv, Context)) 196249423Sdim return RetVal; 197249423Sdim return 0; 198249423Sdim} 199249423Sdim 200249423Sdimstatic int compileModule(char **argv, LLVMContext &Context) { 201193323Sed // Load the module to be compiled... 202198090Srdivacky SMDiagnostic Err; 203193323Sed std::auto_ptr<Module> M; 204239462Sdim Module *mod = 0; 205239462Sdim Triple TheTriple; 206193323Sed 207239462Sdim bool SkipModule = MCPU == "help" || 208239462Sdim (!MAttrs.empty() && MAttrs.front() == "help"); 209193323Sed 210239462Sdim // If user just wants to list available options, skip module loading 211239462Sdim if (!SkipModule) { 212239462Sdim M.reset(ParseIRFile(InputFilename, Err, Context)); 213239462Sdim mod = M.get(); 214239462Sdim if (mod == 0) { 215239462Sdim Err.print(argv[0], errs()); 216198090Srdivacky return 1; 217198090Srdivacky } 218198090Srdivacky 219239462Sdim // If we are supposed to override the target triple, do so now. 220239462Sdim if (!TargetTriple.empty()) 221239462Sdim mod->setTargetTriple(Triple::normalize(TargetTriple)); 222239462Sdim TheTriple = Triple(mod->getTargetTriple()); 223198090Srdivacky } else { 224239462Sdim TheTriple = Triple(Triple::normalize(TargetTriple)); 225193323Sed } 226193323Sed 227239462Sdim if (TheTriple.getTriple().empty()) 228239462Sdim TheTriple.setTriple(sys::getDefaultTargetTriple()); 229239462Sdim 230239462Sdim // Get the target specific parser. 231239462Sdim std::string Error; 232239462Sdim const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 233239462Sdim Error); 234239462Sdim if (!TheTarget) { 235239462Sdim errs() << argv[0] << ": " << Error; 236239462Sdim return 1; 237239462Sdim } 238239462Sdim 239193323Sed // Package up features to be passed to target/subtarget 240193323Sed std::string FeaturesStr; 241224133Sdim if (MAttrs.size()) { 242193323Sed SubtargetFeatures Features; 243193323Sed for (unsigned i = 0; i != MAttrs.size(); ++i) 244193323Sed Features.AddFeature(MAttrs[i]); 245193323Sed FeaturesStr = Features.getString(); 246193323Sed } 247193323Sed 248234353Sdim CodeGenOpt::Level OLvl = CodeGenOpt::Default; 249234353Sdim switch (OptLevel) { 250234353Sdim default: 251234353Sdim errs() << argv[0] << ": invalid optimization level.\n"; 252234353Sdim return 1; 253234353Sdim case ' ': break; 254234353Sdim case '0': OLvl = CodeGenOpt::None; break; 255234353Sdim case '1': OLvl = CodeGenOpt::Less; break; 256234353Sdim case '2': OLvl = CodeGenOpt::Default; break; 257234353Sdim case '3': OLvl = CodeGenOpt::Aggressive; break; 258234353Sdim } 259234353Sdim 260234353Sdim TargetOptions Options; 261234353Sdim Options.LessPreciseFPMADOption = EnableFPMAD; 262234353Sdim Options.NoFramePointerElim = DisableFPElim; 263234353Sdim Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf; 264239462Sdim Options.AllowFPOpFusion = FuseFPOps; 265234353Sdim Options.UnsafeFPMath = EnableUnsafeFPMath; 266234353Sdim Options.NoInfsFPMath = EnableNoInfsFPMath; 267234353Sdim Options.NoNaNsFPMath = EnableNoNaNsFPMath; 268234353Sdim Options.HonorSignDependentRoundingFPMathOption = 269234353Sdim EnableHonorSignDependentRoundingFPMath; 270234353Sdim Options.UseSoftFloat = GenerateSoftFloatCalls; 271234353Sdim if (FloatABIForCalls != FloatABI::Default) 272234353Sdim Options.FloatABIType = FloatABIForCalls; 273234353Sdim Options.NoZerosInBSS = DontPlaceZerosInBSS; 274234353Sdim Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt; 275234353Sdim Options.DisableTailCalls = DisableTailCalls; 276234353Sdim Options.StackAlignmentOverride = OverrideStackAlignment; 277234353Sdim Options.RealignStack = EnableRealignStack; 278234353Sdim Options.TrapFuncName = TrapFuncName; 279234353Sdim Options.PositionIndependentExecutable = EnablePIE; 280234353Sdim Options.EnableSegmentedStacks = SegmentedStacks; 281239462Sdim Options.UseInitArray = UseInitArray; 282243830Sdim Options.SSPBufferSize = SSPBufferSize; 283234353Sdim 284221337Sdim std::auto_ptr<TargetMachine> 285226584Sdim target(TheTarget->createTargetMachine(TheTriple.getTriple(), 286234353Sdim MCPU, FeaturesStr, Options, 287234353Sdim RelocModel, CMModel, OLvl)); 288193323Sed assert(target.get() && "Could not allocate target machine!"); 289239462Sdim assert(mod && "Should have exited after outputting help!"); 290193323Sed TargetMachine &Target = *target.get(); 291193323Sed 292218885Sdim if (DisableDotLoc) 293218885Sdim Target.setMCUseLoc(false); 294218885Sdim 295221337Sdim if (DisableCFI) 296221337Sdim Target.setMCUseCFI(false); 297221337Sdim 298234353Sdim if (EnableDwarfDirectory) 299234353Sdim Target.setMCUseDwarfDirectory(true); 300234353Sdim 301234353Sdim if (GenerateSoftFloatCalls) 302234353Sdim FloatABIForCalls = FloatABI::Soft; 303234353Sdim 304221337Sdim // Disable .loc support for older OS X versions. 305221337Sdim if (TheTriple.isMacOSX() && 306221337Sdim TheTriple.isMacOSXVersionLT(10, 6)) 307221337Sdim Target.setMCUseLoc(false); 308221337Sdim 309239462Sdim // Figure out where we are going to send the output. 310212793Sdim OwningPtr<tool_output_file> Out 311212793Sdim (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0])); 312212793Sdim if (!Out) return 1; 313193323Sed 314208599Srdivacky // Build up all of the passes that we want to do to the module. 315208599Srdivacky PassManager PM; 316198090Srdivacky 317239462Sdim // Add an appropriate TargetLibraryInfo pass for the module's triple. 318239462Sdim TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple); 319239462Sdim if (DisableSimplifyLibCalls) 320239462Sdim TLI->disableAllFunctions(); 321239462Sdim PM.add(TLI); 322239462Sdim 323249423Sdim // Add intenal analysis passes from the target machine. 324249423Sdim Target.addAnalysisPasses(PM); 325243830Sdim 326208599Srdivacky // Add the target data from the target machine, if it exists, or the module. 327243830Sdim if (const DataLayout *TD = Target.getDataLayout()) 328243830Sdim PM.add(new DataLayout(*TD)); 329208599Srdivacky else 330243830Sdim PM.add(new DataLayout(mod)); 331198090Srdivacky 332208599Srdivacky // Override default to generate verbose assembly. 333208599Srdivacky Target.setAsmVerbosityDefault(true); 334193323Sed 335212793Sdim if (RelaxAll) { 336212793Sdim if (FileType != TargetMachine::CGFT_ObjectFile) 337212793Sdim errs() << argv[0] 338212793Sdim << ": warning: ignoring -mc-relax-all because filetype != obj"; 339212793Sdim else 340212793Sdim Target.setMCRelaxAll(true); 341208599Srdivacky } 342198090Srdivacky 343212793Sdim { 344212793Sdim formatted_raw_ostream FOS(Out->os()); 345193323Sed 346239462Sdim AnalysisID StartAfterID = 0; 347239462Sdim AnalysisID StopAfterID = 0; 348239462Sdim const PassRegistry *PR = PassRegistry::getPassRegistry(); 349239462Sdim if (!StartAfter.empty()) { 350239462Sdim const PassInfo *PI = PR->getPassInfo(StartAfter); 351239462Sdim if (!PI) { 352239462Sdim errs() << argv[0] << ": start-after pass is not registered.\n"; 353239462Sdim return 1; 354239462Sdim } 355239462Sdim StartAfterID = PI->getTypeInfo(); 356239462Sdim } 357239462Sdim if (!StopAfter.empty()) { 358239462Sdim const PassInfo *PI = PR->getPassInfo(StopAfter); 359239462Sdim if (!PI) { 360239462Sdim errs() << argv[0] << ": stop-after pass is not registered.\n"; 361239462Sdim return 1; 362239462Sdim } 363239462Sdim StopAfterID = PI->getTypeInfo(); 364239462Sdim } 365239462Sdim 366212793Sdim // Ask the target to add backend passes as necessary. 367239462Sdim if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify, 368239462Sdim StartAfterID, StopAfterID)) { 369212793Sdim errs() << argv[0] << ": target does not support generation of this" 370212793Sdim << " file type!\n"; 371212793Sdim return 1; 372212793Sdim } 373193323Sed 374221337Sdim // Before executing passes, print the final values of the LLVM options. 375221337Sdim cl::PrintOptionValues(); 376221337Sdim 377239462Sdim PM.run(*mod); 378212793Sdim } 379212793Sdim 380212793Sdim // Declare success. 381212793Sdim Out->keep(); 382212793Sdim 383193323Sed return 0; 384193323Sed} 385