コード例 #1
0
ファイル: TargetSelect.cpp プロジェクト: romix/llvm
/// selectTarget - Pick a target either via -march or by guessing the native
/// arch.  Add any CPU features specified via -mcpu or -mattr.
TargetMachine *EngineBuilder::selectTarget(const Triple &TargetTriple,
        StringRef MArch,
        StringRef MCPU,
        const SmallVectorImpl<std::string>& MAttrs) {
    Triple TheTriple(TargetTriple);
    if (TheTriple.getTriple().empty())
        TheTriple.setTriple(sys::getDefaultTargetTriple());

    // Adjust the triple to match what the user requested.
    const Target *TheTarget = 0;
    if (!MArch.empty()) {
        for (TargetRegistry::iterator it = TargetRegistry::begin(),
                ie = TargetRegistry::end(); it != ie; ++it) {
            if (MArch == it->getName()) {
                TheTarget = &*it;
                break;
            }
        }

        if (!TheTarget) {
            if (ErrorStr)
                *ErrorStr = "No available targets are compatible with this -march, "
                            "see -version for the available targets.\n";
            return 0;
        }

        // Adjust the triple to match (if known), otherwise stick with the
        // requested/host triple.
        Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
        if (Type != Triple::UnknownArch)
            TheTriple.setArch(Type);
    } else {
        std::string Error;
        TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error);
        if (TheTarget == 0) {
            if (ErrorStr)
                *ErrorStr = Error;
            return 0;
        }
    }

    // Package up features to be passed to target/subtarget
    std::string FeaturesStr;
    if (!MAttrs.empty()) {
        SubtargetFeatures Features;
        for (unsigned i = 0; i != MAttrs.size(); ++i)
            Features.AddFeature(MAttrs[i]);
        FeaturesStr = Features.getString();
    }

    // Allocate a target...
    TargetMachine *Target = TheTarget->createTargetMachine(TheTriple.getTriple(),
                            MCPU, FeaturesStr,
                            Options,
                            RelocModel, CMModel,
                            OptLevel);
    assert(Target && "Could not allocate target machine!");
    return Target;
}
コード例 #2
0
ファイル: TargetMachineC.cpp プロジェクト: Fairly/opencor
LLVMTargetRef LLVMGetTargetFromName(const char *Name) {
  StringRef NameRef = Name;
  for (TargetRegistry::iterator IT = TargetRegistry::begin(),
                                IE = TargetRegistry::end(); IT != IE; ++IT) {
    if (IT->getName() == NameRef)
      return wrap(&*IT);
  }

  return nullptr;
}
コード例 #3
0
ファイル: TargetRegistry.cpp プロジェクト: Fairly/opencor
void TargetRegistry::printRegisteredTargetsForVersion() {
  std::vector<std::pair<StringRef, const Target*> > Targets;
  size_t Width = 0;
  for (TargetRegistry::iterator I = TargetRegistry::begin(),
       E = TargetRegistry::end();
       I != E; ++I) {
    Targets.push_back(std::make_pair(I->getName(), &*I));
    Width = std::max(Width, Targets.back().first.size());
  }
  array_pod_sort(Targets.begin(), Targets.end(), TargetArraySortFn);

  raw_ostream &OS = outs();
  OS << "  Registered Targets:\n";
  for (unsigned i = 0, e = Targets.size(); i != e; ++i) {
    OS << "    " << Targets[i].first;
    OS.indent(Width - Targets[i].first.size()) << " - "
      << Targets[i].second->getShortDescription() << '\n';
  }
  if (Targets.empty())
    OS << "    (none)\n";
}
コード例 #4
0
ファイル: TargetRegistry.cpp プロジェクト: Fairly/opencor
const Target *TargetRegistry::lookupTarget(const std::string &ArchName,
                                           Triple &TheTriple,
                                           std::string &Error) {
  // Allocate target machine.  First, check whether the user has explicitly
  // specified an architecture to compile for. If so we have to look it up by
  // name, because it might be a backend that has no mapping to a target triple.
  const Target *TheTarget = nullptr;
  if (!ArchName.empty()) {
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
           ie = TargetRegistry::end(); it != ie; ++it) {
      if (ArchName == it->getName()) {
        TheTarget = &*it;
        break;
      }
    }

    if (!TheTarget) {
      Error = "error: invalid target '" + ArchName + "'.\n";
      return nullptr;
    }

    // Adjust the triple to match (if known), otherwise stick with the
    // given triple.
    Triple::ArchType Type = Triple::getArchTypeForLLVMName(ArchName);
    if (Type != Triple::UnknownArch)
      TheTriple.setArch(Type);
  } else {
    // Get the target specific parser.
    std::string TempError;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), TempError);
    if (!TheTarget) {
      Error = ": error: unable to get target for '"
            + TheTriple.getTriple()
            + "', see --version and --triple.\n";
      return nullptr;
    }
  }

  return TheTarget;
}
コード例 #5
0
LLVMTargetMachineRef LLVMCreateTargetMachine(const char* cpu, const char* triple, const char** feats, size_t nfeats)
{
    // based on LDC code

    // find target from the given triple and cpu
    const Target* target = NULL;
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
             ie = TargetRegistry::end(); it != ie; ++it)
    {
#if 0
        printf("cpu: %s target: %s\n", cpu, it->getName());
#endif
        if (strcmp(cpu, it->getName()) == 0)
        {
            target = &*it;
            break;
        }
    }
    assert(target != NULL);

    // add any features the user might have provided
    Twine twine;

    SubtargetFeatures features;
    //features.setCPU(cpu);

    for (size_t i = 0; i < nfeats; ++i)
    {
        features.AddFeature(feats[i]);
        twine = twine.concat(features.getString());
    }

    // create machine
    TargetMachine* targetMachine = target->createTargetMachine(triple, twine.str());
    if (!targetMachine)
        return NULL;

    return wrap(targetMachine);
}
コード例 #6
0
ファイル: TargetSelect.cpp プロジェクト: 5432935/crossbridge
/// selectTarget - Pick a target either via -march or by guessing the native
/// arch.  Add any CPU features specified via -mcpu or -mattr.
TargetMachine *MCJIT::selectTarget(Module *Mod,
                                 StringRef MArch,
                                 StringRef MCPU,
                                 const SmallVectorImpl<std::string>& MAttrs,
                                 std::string *ErrorStr) {
  Triple TheTriple(Mod->getTargetTriple());
  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getHostTriple());

  // Adjust the triple to match what the user requested.
  const Target *TheTarget = 0;
  if (!MArch.empty()) {
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
           ie = TargetRegistry::end(); it != ie; ++it) {
      if (MArch == it->getName()) {
        TheTarget = &*it;
        break;
      }
    }

    if (!TheTarget) {
      *ErrorStr = "No available targets are compatible with this -march, "
        "see -version for the available targets.\n";
      return 0;
    }

    // Adjust the triple to match (if known), otherwise stick with the
    // module/host triple.
    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
    if (Type != Triple::UnknownArch)
      TheTriple.setArch(Type);
  } else {
    std::string Error;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error);
    if (TheTarget == 0) {
      if (ErrorStr)
        *ErrorStr = Error;
      return 0;
    }
  }

  if (!TheTarget->hasJIT()) {
    errs() << "WARNING: This target JIT is not designed for the host you are"
           << " running.  If bad things happen, please choose a different "
           << "-march switch.\n";
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (!MCPU.empty() || !MAttrs.empty()) {
    SubtargetFeatures Features;
    Features.setCPU(MCPU);
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  // Allocate a target...
  TargetMachine *Target =
    TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr);
  assert(Target && "Could not allocate target machine!");
  return Target;
}
コード例 #7
0
// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");

  // Load the module to be compiled...
  SMDiagnostic Err;
  std::auto_ptr<Module> M;

  M.reset(ParseIRFile(InputFilename, Err, Context));
  if (M.get() == 0) {
    Err.Print(argv[0], errs());
    return 1;
  }
  Module &mod = *M.get();

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    mod.setTargetTriple(Triple::normalize(TargetTriple));

  Triple TheTriple(mod.getTargetTriple());
  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getHostTriple());

  // Allocate target machine.  First, check whether the user has explicitly
  // specified an architecture to compile for. If so we have to look it up by
  // name, because it might be a backend that has no mapping to a target triple.
  const Target *TheTarget = 0;
  if (!MArch.empty()) {
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
           ie = TargetRegistry::end(); it != ie; ++it) {
      if (MArch == it->getName()) {
        TheTarget = &*it;
        break;
      }
    }

    if (!TheTarget) {
      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
      return 1;
    }

    // Adjust the triple to match (if known), otherwise stick with the
    // module/host triple.
    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
    if (Type != Triple::UnknownArch)
      TheTriple.setArch(Type);
  } else {
    std::string Err;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
    if (TheTarget == 0) {
      errs() << argv[0] << ": error auto-selecting target for module '"
             << Err << "'.  Please use the -march option to explicitly "
             << "pick a target.\n";
      return 1;
    }
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (MCPU.size() || MAttrs.size()) {
    SubtargetFeatures Features;
    Features.setCPU(MCPU);
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  std::auto_ptr<TargetMachine>
    target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
  assert(target.get() && "Could not allocate target machine!");
  TargetMachine &Target = *target.get();

  if (DisableDotLoc)
    Target.setMCUseLoc(false);
  if (TheTriple.getOS() == Triple::Darwin) {
    switch (TheTriple.getDarwinMajorNumber()) {
    case 7:
    case 8:
    case 9:
      // disable .loc support for older darwin OS.
      Target.setMCUseLoc(false);
      break;
    default:
      break;
    }
  }

  // Figure out where we are going to send the output...
  OwningPtr<tool_output_file> Out
    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
  if (!Out) return 1;

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  // Build up all of the passes that we want to do to the module.
  PassManager PM;

  // Add the target data from the target machine, if it exists, or the module.
  if (const TargetData *TD = Target.getTargetData())
    PM.add(new TargetData(*TD));
  else
    PM.add(new TargetData(&mod));

  // Override default to generate verbose assembly.
  Target.setAsmVerbosityDefault(true);

  if (RelaxAll) {
    if (FileType != TargetMachine::CGFT_ObjectFile)
      errs() << argv[0]
             << ": warning: ignoring -mc-relax-all because filetype != obj";
    else
      Target.setMCRelaxAll(true);
  }

  {
    formatted_raw_ostream FOS(Out->os());

    // Ask the target to add backend passes as necessary.
    if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      return 1;
    }

    // Before executing passes, print the final values of the LLVM options.
    cl::PrintOptionValues();

    PM.run(mod);
  }

  // Declare success.
  Out->keep();

  return 0;
}
コード例 #8
0
// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllAsmPrinters();

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
  
  // Load the module to be compiled...
  SMDiagnostic Err;
  std::auto_ptr<Module> M;

  M.reset(ParseIRFile(InputFilename, Err, Context));
  if (M.get() == 0) {
    Err.Print(argv[0], errs());
    return 1;
  }
  Module &mod = *M.get();

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    mod.setTargetTriple(TargetTriple);

  Triple TheTriple(mod.getTargetTriple());
  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getHostTriple());

  // Allocate target machine.  First, check whether the user has explicitly
  // specified an architecture to compile for. If so we have to look it up by
  // name, because it might be a backend that has no mapping to a target triple.
  const Target *TheTarget = 0;
  if (!MArch.empty()) {
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
           ie = TargetRegistry::end(); it != ie; ++it) {
      if (MArch == it->getName()) {
        TheTarget = &*it;
        break;
      }
    }

    if (!TheTarget) {
      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
      return 1;
    }

    // Adjust the triple to match (if known), otherwise stick with the
    // module/host triple.
    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
    if (Type != Triple::UnknownArch)
      TheTriple.setArch(Type);
  } else {
    std::string Err;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
    if (TheTarget == 0) {
      errs() << argv[0] << ": error auto-selecting target for module '"
             << Err << "'.  Please use the -march option to explicitly "
             << "pick a target.\n";
      return 1;
    }
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (MCPU.size() || MAttrs.size()) {
    SubtargetFeatures Features;
    Features.setCPU(MCPU);
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  std::auto_ptr<TargetMachine> 
    target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
  assert(target.get() && "Could not allocate target machine!");
  TargetMachine &Target = *target.get();

  // Figure out where we are going to send the output...
  formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(), argv[0]);
  if (Out == 0) return 1;

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  // Request that addPassesToEmitFile run the Verifier after running
  // passes which modify the IR.
#ifndef NDEBUG
  bool DisableVerify = false;
#else
  bool DisableVerify = true;
#endif

  // If this target requires addPassesToEmitWholeFile, do it now.  This is
  // used by strange things like the C backend.
  if (Target.WantsWholeFile()) {
    PassManager PM;

    // Add the target data from the target machine, if it exists, or the module.
    if (const TargetData *TD = Target.getTargetData())
      PM.add(new TargetData(*TD));
    else
      PM.add(new TargetData(&mod));

    if (!NoVerify)
      PM.add(createVerifierPass());

    // Ask the target to add backend passes as necessary.
    if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, OLvl,
                                        DisableVerify)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      if (Out != &fouts()) delete Out;
      // And the Out file is empty and useless, so remove it now.
      sys::Path(OutputFilename).eraseFromDisk();
      return 1;
    }
    PM.run(mod);
  } else {
    // Build up all of the passes that we want to do to the module.
    FunctionPassManager Passes(M.get());

    // Add the target data from the target machine, if it exists, or the module.
    if (const TargetData *TD = Target.getTargetData())
      Passes.add(new TargetData(*TD));
    else
      Passes.add(new TargetData(&mod));

#ifndef NDEBUG
    if (!NoVerify)
      Passes.add(createVerifierPass());
#endif

    // Override default to generate verbose assembly.
    Target.setAsmVerbosityDefault(true);

    if (Target.addPassesToEmitFile(Passes, *Out, FileType, OLvl,
                                   DisableVerify)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      if (Out != &fouts()) delete Out;
      // And the Out file is empty and useless, so remove it now.
      sys::Path(OutputFilename).eraseFromDisk();
      return 1;
    }

    Passes.doInitialization();

    // Run our queue of passes all at once now, efficiently.
    // TODO: this could lazily stream functions out of the module.
    for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
      if (!I->isDeclaration()) {
        if (DisableRedZone)
          I->addFnAttr(Attribute::NoRedZone);
        if (NoImplicitFloats)
          I->addFnAttr(Attribute::NoImplicitFloat);
        Passes.run(*I);
      }

    Passes.doFinalization();
  }

  // Delete the ostream if it's not a stdout stream
  if (Out != &fouts()) delete Out;

  return 0;
}
コード例 #9
0
ファイル: llc.cpp プロジェクト: mdekruijf/llvm
// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllTargetMCs();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();

  // Register the target printer for --version.
  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");

  // Load the module to be compiled...
  SMDiagnostic Err;
  std::auto_ptr<Module> M;

  M.reset(ParseIRFile(InputFilename, Err, Context));
  if (M.get() == 0) {
    Err.print(argv[0], errs());
    return 1;
  }
  Module &mod = *M.get();

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    mod.setTargetTriple(Triple::normalize(TargetTriple));

  Triple TheTriple(mod.getTargetTriple());
  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getDefaultTargetTriple());

  // Allocate target machine.  First, check whether the user has explicitly
  // specified an architecture to compile for. If so we have to look it up by
  // name, because it might be a backend that has no mapping to a target triple.
  const Target *TheTarget = 0;
  if (!MArch.empty()) {
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
           ie = TargetRegistry::end(); it != ie; ++it) {
      if (MArch == it->getName()) {
        TheTarget = &*it;
        break;
      }
    }

    if (!TheTarget) {
      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
      return 1;
    }

    // Adjust the triple to match (if known), otherwise stick with the
    // module/host triple.
    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
    if (Type != Triple::UnknownArch)
      TheTriple.setArch(Type);
  } else {
    std::string Err;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
    if (TheTarget == 0) {
      errs() << argv[0] << ": error auto-selecting target for module '"
             << Err << "'.  Please use the -march option to explicitly "
             << "pick a target.\n";
      return 1;
    }
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (MAttrs.size()) {
    SubtargetFeatures Features;
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  TargetOptions Options;
  Options.LessPreciseFPMADOption = EnableFPMAD;
  Options.PrintMachineCode = PrintCode;
  Options.NoFramePointerElim = DisableFPElim;
  Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
  Options.NoExcessFPPrecision = DisableExcessPrecision;
  Options.UnsafeFPMath = EnableUnsafeFPMath;
  Options.NoInfsFPMath = EnableNoInfsFPMath;
  Options.NoNaNsFPMath = EnableNoNaNsFPMath;
  Options.HonorSignDependentRoundingFPMathOption =
      EnableHonorSignDependentRoundingFPMath;
  Options.UseSoftFloat = GenerateSoftFloatCalls;
  if (FloatABIForCalls != FloatABI::Default)
    Options.FloatABIType = FloatABIForCalls;
  Options.NoZerosInBSS = DontPlaceZerosInBSS;
  Options.JITExceptionHandling = EnableJITExceptionHandling;
  Options.JITEmitDebugInfo = EmitJitDebugInfo;
  Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
  Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
  Options.DisableTailCalls = DisableTailCalls;
  Options.StackAlignmentOverride = OverrideStackAlignment;
  Options.RealignStack = EnableRealignStack;
  Options.DisableJumpTables = DisableSwitchTables;
  Options.TrapFuncName = TrapFuncName;
  Options.EnableSegmentedStacks = SegmentedStacks;

  std::auto_ptr<TargetMachine>
    target(TheTarget->createTargetMachine(TheTriple.getTriple(),
                                          MCPU, FeaturesStr, Options,
                                          RelocModel, CMModel, OLvl));
  assert(target.get() && "Could not allocate target machine!");
  TargetMachine &Target = *target.get();

  if (DisableDotLoc)
    Target.setMCUseLoc(false);

  if (DisableCFI)
    Target.setMCUseCFI(false);

  if (EnableDwarfDirectory)
    Target.setMCUseDwarfDirectory(true);

  if (GenerateSoftFloatCalls)
    FloatABIForCalls = FloatABI::Soft;

  // Disable .loc support for older OS X versions.
  if (TheTriple.isMacOSX() &&
      TheTriple.isMacOSXVersionLT(10, 6))
    Target.setMCUseLoc(false);

  // Figure out where we are going to send the output...
  OwningPtr<tool_output_file> Out
    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
  if (!Out) return 1;

  // Build up all of the passes that we want to do to the module.
  PassManager PM;

  // Add the target data from the target machine, if it exists, or the module.
  if (const TargetData *TD = Target.getTargetData())
    PM.add(new TargetData(*TD));
  else
    PM.add(new TargetData(&mod));

  // Override default to generate verbose assembly.
  Target.setAsmVerbosityDefault(true);

  if (RelaxAll) {
    if (FileType != TargetMachine::CGFT_ObjectFile)
      errs() << argv[0]
             << ": warning: ignoring -mc-relax-all because filetype != obj";
    else
      Target.setMCRelaxAll(true);
  }

  {
    formatted_raw_ostream FOS(Out->os());

    // Ask the target to add backend passes as necessary.
    if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      return 1;
    }

    // Before executing passes, print the final values of the LLVM options.
    cl::PrintOptionValues();

    PM.run(mod);
  }

  // Declare success.
  Out->keep();

  return 0;
}
コード例 #10
0
int main(int argc, char **argv) {
    std::vector<StringRef> Components;
    bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;
    bool HasAnyOption = false;

    // llvm-config is designed to support being run both from a development tree
    // and from an installed path. We try and auto-detect which case we are in so
    // that we can report the correct information when run from a development
    // tree.
    bool IsInDevelopmentTree, DevelopmentTreeLayoutIsCMakeStyle;
    llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]).str());
    std::string CurrentExecPrefix;
    std::string ActiveObjRoot;

    // Create an absolute path, and pop up one directory (we expect to be inside a
    // bin dir).
    sys::fs::make_absolute(CurrentPath);
    CurrentExecPrefix = sys::path::parent_path(
                            sys::path::parent_path(CurrentPath)).str();

    // Check to see if we are inside a development tree by comparing to possible
    // locations (prefix style or CMake style). This could be wrong in the face of
    // symbolic links, but is good enough.
    if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + "/" + LLVM_BUILDMODE) {
        IsInDevelopmentTree = true;
        DevelopmentTreeLayoutIsCMakeStyle = false;

        // If we are in a development tree, then check if we are in a BuildTools
        // directory. This indicates we are built for the build triple, but we
        // always want to provide information for the host triple.
        if (sys::path::filename(LLVM_OBJ_ROOT) == "BuildTools") {
            ActiveObjRoot = sys::path::parent_path(LLVM_OBJ_ROOT);
        } else {
            ActiveObjRoot = LLVM_OBJ_ROOT;
        }
    } else if (CurrentExecPrefix == std::string(LLVM_OBJ_ROOT) + "/bin") {
        IsInDevelopmentTree = true;
        DevelopmentTreeLayoutIsCMakeStyle = true;
        ActiveObjRoot = LLVM_OBJ_ROOT;
    } else {
        IsInDevelopmentTree = false;
    }

    // Compute various directory locations based on the derived location
    // information.
    std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;
    std::string ActiveIncludeOption;
    if (IsInDevelopmentTree) {
        ActivePrefix = CurrentExecPrefix;

        // CMake organizes the products differently than a normal prefix style
        // layout.
        if (DevelopmentTreeLayoutIsCMakeStyle) {
            ActiveIncludeDir = ActiveObjRoot + "/include";
            ActiveBinDir = ActiveObjRoot + "/bin/" + LLVM_BUILDMODE;
            ActiveLibDir = ActiveObjRoot + "/lib/" + LLVM_BUILDMODE;
        } else {
            ActiveIncludeDir = ActiveObjRoot + "/include";
            ActiveBinDir = ActiveObjRoot + "/" + LLVM_BUILDMODE + "/bin";
            ActiveLibDir = ActiveObjRoot + "/" + LLVM_BUILDMODE + "/lib";
        }

        // We need to include files from both the source and object trees.
        ActiveIncludeOption = ("-I" + ActiveIncludeDir + " " +
                               "-I" + ActiveObjRoot + "/include");
    } else {
        ActivePrefix = CurrentExecPrefix;
        ActiveIncludeDir = ActivePrefix + "/include";
        ActiveBinDir = ActivePrefix + "/bin";
        ActiveLibDir = ActivePrefix + "/lib";
        ActiveIncludeOption = "-I" + ActiveIncludeDir;
    }

    raw_ostream &OS = outs();
    for (int i = 1; i != argc; ++i) {
        StringRef Arg = argv[i];

        if (Arg.startswith("-")) {
            HasAnyOption = true;
            if (Arg == "--version") {
                OS << PACKAGE_VERSION << '\n';
            } else if (Arg == "--prefix") {
                OS << ActivePrefix << '\n';
            } else if (Arg == "--bindir") {
                OS << ActiveBinDir << '\n';
            } else if (Arg == "--includedir") {
                OS << ActiveIncludeDir << '\n';
            } else if (Arg == "--libdir") {
                OS << ActiveLibDir << '\n';
            } else if (Arg == "--cppflags") {
                OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
            } else if (Arg == "--cflags") {
                OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
            } else if (Arg == "--cxxflags") {
                OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
            } else if (Arg == "--ldflags") {
                OS << "-L" << ActiveLibDir << ' ' << LLVM_LDFLAGS
                   << ' ' << LLVM_SYSTEM_LIBS << '\n';
            } else if (Arg == "--libs") {
                PrintLibs = true;
            } else if (Arg == "--libnames") {
                PrintLibNames = true;
            } else if (Arg == "--libfiles") {
                PrintLibFiles = true;
            } else if (Arg == "--components") {
                for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
                    OS << ' ';
                    OS << AvailableComponents[j].Name;
                }
                OS << '\n';
            } else if (Arg == "--targets-built") {
                bool First = true;
                for (TargetRegistry::iterator I = TargetRegistry::begin(),
                        E = TargetRegistry::end(); I != E; First = false, ++I) {
                    if (!First)
                        OS << ' ';
                    OS << I->getName();
                }
                OS << '\n';
            } else if (Arg == "--host-target") {
                OS << LLVM_DEFAULT_TARGET_TRIPLE << '\n';
            } else if (Arg == "--build-mode") {
                OS << LLVM_BUILDMODE << '\n';
            } else if (Arg == "--obj-root") {
                OS << LLVM_OBJ_ROOT << '\n';
            } else if (Arg == "--src-root") {
                OS << LLVM_SRC_ROOT << '\n';
            } else {
                usage();
            }
        } else {
            Components.push_back(Arg);
        }
    }

    if (!HasAnyOption)
        usage();

    if (PrintLibs || PrintLibNames || PrintLibFiles) {
        // Construct the list of all the required libraries.
        std::vector<StringRef> RequiredLibs;
        ComputeLibsForComponents(Components, RequiredLibs);

        for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
            StringRef Lib = RequiredLibs[i];
            if (i)
                OS << ' ';

            if (PrintLibNames) {
                OS << Lib;
            } else if (PrintLibFiles) {
                OS << ActiveLibDir << '/' << Lib;
            } else if (PrintLibs) {
                // If this is a typical library name, include it using -l.
                if (Lib.startswith("lib") && Lib.endswith(".a")) {
                    OS << "-l" << Lib.slice(3, Lib.size()-2);
                    continue;
                }

                // Otherwise, print the full path.
                OS << ActiveLibDir << '/' << Lib;
            }
        }
        OS << '\n';
    } else if (!Components.empty()) {
        errs() << "llvm-config: error: components given, but unused\n\n";
        usage();
    }

    return 0;
}