本文整理汇总了C++中cl::list类的典型用法代码示例。如果您正苦于以下问题:C++ list类的具体用法?C++ list怎么用?C++ list使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了list类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: main
//===----------------------------------------------------------------------===//
// main for opt
//
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
if (AnalyzeOnly && NoOutput) {
errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
return 1;
}
// Enable debug stream buffering.
EnableDebugBuffering = true;
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
LLVMContext &Context = getGlobalContext();
cl::ParseCommandLineOptions(argc, argv,
"llvm .bc -> .bc modular optimizer and analysis printer\n");
// Allocate a full target machine description only if necessary.
// FIXME: The choice of target should be controllable on the command line.
std::auto_ptr<TargetMachine> target;
SMDiagnostic Err;
// Load the input module...
std::auto_ptr<Module> M;
M.reset(ParseIRFile(InputFilename, Err, Context));
if (M.get() == 0) {
Err.Print(argv[0], errs());
return 1;
}
// Figure out what stream we are supposed to write to...
OwningPtr<tool_output_file> Out;
if (NoOutput) {
if (!OutputFilename.empty())
errs() << "WARNING: The -o (output filename) option is ignored when\n"
"the --disable-output option is used.\n";
} else {
// Default to standard output.
if (OutputFilename.empty())
OutputFilename = "-";
std::string ErrorInfo;
Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
raw_fd_ostream::F_Binary));
if (!ErrorInfo.empty()) {
errs() << ErrorInfo << '\n';
return 1;
}
}
// If the output is set to be emitted to standard out, and standard out is a
// console, print out a warning message and refuse to do it. We don't
// impress anyone by spewing tons of binary goo to a terminal.
if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
NoOutput = true;
// Create a PassManager to hold and optimize the collection of passes we are
// about to build...
//
PassManager Passes;
// Add an appropriate TargetData instance for this module...
TargetData *TD = 0;
const std::string &ModuleDataLayout = M.get()->getDataLayout();
if (!ModuleDataLayout.empty())
TD = new TargetData(ModuleDataLayout);
else if (!DefaultDataLayout.empty())
TD = new TargetData(DefaultDataLayout);
if (TD)
Passes.add(TD);
OwningPtr<PassManager> FPasses;
if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
FPasses.reset(new PassManager());
if (TD)
FPasses->add(new TargetData(*TD));
}
// If the -strip-debug command line option was specified, add it. If
// -std-compile-opts was also specified, it will handle StripDebug.
if (StripDebug && !StandardCompileOpts)
addPass(Passes, createStripSymbolsPass(true));
// Create a new optimization pass for each one specified on the command line
for (unsigned i = 0; i < PassList.size(); ++i) {
// Check to see if -std-compile-opts was specified before this option. If
// so, handle it.
if (StandardCompileOpts &&
StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
AddStandardCompilePasses(Passes);
StandardCompileOpts = false;
}
//.........这里部分代码省略.........
开发者ID:Persper,项目名称:PTMC,代码行数:101,代码来源:opt.cpp
示例2: Help
namespace format {
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
// Mark all our options with this category, everything else (except for -version
// and -help) will be hidden.
static cl::OptionCategory SwiftFormatCategory("Swift-format options");
static cl::list<unsigned> Offsets("offset",
cl::desc("Format a range starting at this byte offset.\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"Can only be used with one input file."),
cl::cat(SwiftFormatCategory));
static cl::list<unsigned> Lengths("length",
cl::desc("Format a range of this length (in bytes).\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"When only a single -offset is specified without\n"
"-length, clang-format will format up to the end\n"
"of the file.\n"
"Can only be used with one input file."),
cl::cat(SwiftFormatCategory));
static cl::list<std::string> LineRanges("lines",
cl::desc("<start line>:<end line> - format a range of\n"
"lines (both 1-based).\n"
"Multiple ranges can be formatted by specifying\n"
"several -lines arguments.\n"
"Can't be used with -offset and -length.\n"
"Can only be used with one input file."),
cl::cat(SwiftFormatCategory));
static llvm::cl::opt<bool> UseTabs("usetabs",
llvm::cl::desc("Use tabs for indentation"),
cl::cat(SwiftFormatCategory));
static llvm::cl::opt<unsigned> TabWidth("tabwidth",
llvm::cl::desc("Assumed width of tab character"),
cl::cat(SwiftFormatCategory));
static llvm::cl::opt<unsigned> IndentWidth("indentwidth",
llvm::cl::desc("Characters to indent"),
cl::cat(SwiftFormatCategory));
static cl::opt<std::string> AssumeFileName("assume-filename",
cl::desc("When reading from stdin, clang-format assumes this\n"
"filename to look for a style config file (with\n"
"-style=file) and to determine the language."),
cl::init("<stdin>"), cl::cat(SwiftFormatCategory));
static cl::opt<bool> Inplace("i",
cl::desc("Inplace edit <file>s, if specified."),
cl::cat(SwiftFormatCategory));
static cl::opt<bool> OutputXML("output-replacements-xml",
cl::desc("Output replacements as XML."),
cl::cat(SwiftFormatCategory));
static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
cl::cat(SwiftFormatCategory));
CodeFormatOptions FormatOptions;
class FormatterDocument {
SourceManager SM;
unsigned BufferID;
CompilerInvocation CompInv;
std::unique_ptr<ParserUnit> Parser;
class FormatterDiagConsumer: public swift::DiagnosticConsumer {
void handleDiagnostic(SourceManager &SM, SourceLoc Loc,
DiagnosticKind Kind, StringRef Text,
const DiagnosticInfo &Info) override {
llvm::errs() << "Parse error: " << Text << "\n";
}
} DiagConsumer;
public:
FormatterDocument(std::unique_ptr<llvm::MemoryBuffer> Buffer) {
updateCode(std::move(Buffer));
}
void updateCode( std::unique_ptr<llvm::MemoryBuffer> buff ) {
BufferID = SM.addNewSourceBuffer(std::move(buff));
Parser.reset(
new ParserUnit(SM, BufferID,
CompInv.getLangOptions(),
CompInv.getModuleName())
);
Parser->getDiagnosticEngine().addConsumer(DiagConsumer);
auto &P = Parser->getParser();
bool Done = false;
while (!Done) {
P.parseTopLevel();
Done = P.Tok.is(tok::eof);
//.........这里部分代码省略.........
开发者ID:johnno1962b,项目名称:swift,代码行数:101,代码来源:swift-format.cpp
示例3: main
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
unsigned BaseArg = 0;
std::string ErrorMessage;
std::auto_ptr<Module> Composite(LoadFile(argv[0],
InputFilenames[BaseArg], Context));
if (Composite.get() == 0) {
errs() << argv[0] << ": error loading file '"
<< InputFilenames[BaseArg] << "'\n";
return 1;
}
for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
std::auto_ptr<Module> M(LoadFile(argv[0],
InputFilenames[i], Context));
if (M.get() == 0) {
errs() << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n";
return 1;
}
if (Verbose) errs() << "Linking in '" << InputFilenames[i] << "'\n";
if (Linker::LinkModules(Composite.get(), M.get(), Linker::DestroySource,
&ErrorMessage)) {
errs() << argv[0] << ": link error in '" << InputFilenames[i]
<< "': " << ErrorMessage << "\n";
return 1;
}
}
// TODO: Iterate over the -l list and link in any modules containing
// global symbols that have not been resolved so far.
if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
std::string ErrorInfo;
tool_output_file Out(OutputFilename.c_str(), ErrorInfo,
raw_fd_ostream::F_Binary);
if (!ErrorInfo.empty()) {
errs() << ErrorInfo << '\n';
return 1;
}
if (verifyModule(*Composite)) {
errs() << argv[0] << ": linked module is broken!\n";
return 1;
}
if (Verbose) errs() << "Writing bitcode...\n";
if (OutputAssembly) {
Out.os() << *Composite;
} else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
WriteBitcodeToFile(Composite.get(), Out.os());
// Declare success.
Out.keep();
return 0;
}
开发者ID:2014-class,项目名称:freerouter,代码行数:67,代码来源:llvm-link.cpp
示例4: main
//===----------------------------------------------------------------------===//
// main for opt
//
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
// Enable debug stream buffering.
EnableDebugBuffering = true;
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
LLVMContext &Context = getGlobalContext();
InitializeAllTargets();
InitializeAllTargetMCs();
// Initialize passes
PassRegistry &Registry = *PassRegistry::getPassRegistry();
initializeCore(Registry);
initializeDebugIRPass(Registry);
initializeScalarOpts(Registry);
initializeObjCARCOpts(Registry);
initializeVectorization(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
initializeIPA(Registry);
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);
cl::ParseCommandLineOptions(argc, argv,
"llvm .bc -> .bc modular optimizer and analysis printer\n");
if (AnalyzeOnly && NoOutput) {
errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
return 1;
}
SMDiagnostic Err;
// Load the input module...
OwningPtr<Module> M;
M.reset(ParseIRFile(InputFilename, Err, Context));
if (M.get() == 0) {
Err.print(argv[0], errs());
return 1;
}
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
M->setTargetTriple(Triple::normalize(TargetTriple));
// Figure out what stream we are supposed to write to...
OwningPtr<tool_output_file> Out;
if (NoOutput) {
if (!OutputFilename.empty())
errs() << "WARNING: The -o (output filename) option is ignored when\n"
"the --disable-output option is used.\n";
} else {
// Default to standard output.
if (OutputFilename.empty())
OutputFilename = "-";
std::string ErrorInfo;
Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
sys::fs::F_Binary));
if (!ErrorInfo.empty()) {
errs() << ErrorInfo << '\n';
return 1;
}
}
// If the output is set to be emitted to standard out, and standard out is a
// console, print out a warning message and refuse to do it. We don't
// impress anyone by spewing tons of binary goo to a terminal.
if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
NoOutput = true;
// Create a PassManager to hold and optimize the collection of passes we are
// about to build.
//
PassManager Passes;
// Add an appropriate TargetLibraryInfo pass for the module's triple.
TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
// The -disable-simplify-libcalls flag actually disables all builtin optzns.
if (DisableSimplifyLibCalls)
TLI->disableAllFunctions();
Passes.add(TLI);
// Add an appropriate DataLayout instance for this module.
DataLayout *TD = 0;
const std::string &ModuleDataLayout = M.get()->getDataLayout();
if (!ModuleDataLayout.empty())
TD = new DataLayout(ModuleDataLayout);
else if (!DefaultDataLayout.empty())
//.........这里部分代码省略.........
开发者ID:rimsa,项目名称:llvm,代码行数:101,代码来源:opt.cpp
示例5: UnbundleFiles
// Unbundle the files. Return true if an error was found.
static bool UnbundleFiles() {
// Open Input file.
ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
MemoryBuffer::getFileOrSTDIN(InputFileNames.front());
if (std::error_code EC = CodeOrErr.getError()) {
errs() << "error: Can't open file " << InputFileNames.front() << ": "
<< EC.message() << "\n";
return true;
}
MemoryBuffer &Input = *CodeOrErr.get();
// Select the right files handler.
std::unique_ptr<FileHandler> FH;
FH.reset(CreateFileHandler(Input));
// Quit if we don't have a handler.
if (!FH.get())
return true;
// Read the header of the bundled file.
FH.get()->ReadHeader(Input);
// Create a work list that consist of the map triple/output file.
StringMap<StringRef> Worklist;
auto Output = OutputFileNames.begin();
for (auto &Triple : TargetNames) {
Worklist[Triple] = *Output;
++Output;
}
// Read all the bundles that are in the work list. If we find no bundles we
// assume the file is meant for the host target.
bool FoundHostBundle = false;
while (!Worklist.empty()) {
StringRef CurTriple = FH.get()->ReadBundleStart(Input);
// We don't have more bundles.
if (CurTriple.empty())
break;
auto Output = Worklist.find(CurTriple);
// The file may have more bundles for other targets, that we don't care
// about. Therefore, move on to the next triple
if (Output == Worklist.end()) {
continue;
}
// Check if the output file can be opened and copy the bundle to it.
std::error_code EC;
raw_fd_ostream OutputFile(Output->second, EC, sys::fs::F_None);
if (EC) {
errs() << "error: Can't open file " << Output->second << ": "
<< EC.message() << "\n";
return true;
}
FH.get()->ReadBundle(OutputFile, Input);
FH.get()->ReadBundleEnd(Input);
Worklist.erase(Output);
// Record if we found the host bundle.
if (hasHostKind(CurTriple))
FoundHostBundle = true;
}
// If no bundles were found, assume the input file is the host bundle and
// create empty files for the remaining targets.
if (Worklist.size() == TargetNames.size()) {
for (auto &E : Worklist) {
std::error_code EC;
raw_fd_ostream OutputFile(E.second, EC, sys::fs::F_None);
if (EC) {
errs() << "error: Can't open file " << E.second << ": " << EC.message()
<< "\n";
return true;
}
// If this entry has a host kind, copy the input file to the output file.
if (hasHostKind(E.first()))
OutputFile.write(Input.getBufferStart(), Input.getBufferSize());
}
return false;
}
// If we found elements, we emit an error if none of those were for the host.
if (!FoundHostBundle) {
errs() << "error: Can't find bundle for the host target\n";
return true;
}
// If we still have any elements in the worklist, create empty files for them.
for (auto &E : Worklist) {
std::error_code EC;
raw_fd_ostream OutputFile(E.second, EC, sys::fs::F_None);
if (EC) {
errs() << "error: Can't open file " << E.second << ": " << EC.message()
<< "\n";
return true;
}
//.........这里部分代码省略.........
开发者ID:LegalizeAdulthood,项目名称:clang,代码行数:101,代码来源:ClangOffloadBundler.cpp
示例6: main
int main(int argc, const char **argv) {
sys::PrintStackTraceOnErrorSignal(argv[0]);
cl::HideUnrelatedOptions(ClangOffloadBundlerCategory);
cl::SetVersionPrinter(PrintVersion);
cl::ParseCommandLineOptions(
argc, argv,
"A tool to bundle several input files of the specified type <type> \n"
"referring to the same source file but different targets into a single \n"
"one. The resulting file can also be unbundled into different files by \n"
"this tool if -unbundle is provided.\n");
if (Help) {
cl::PrintHelpMessage();
return 0;
}
bool Error = false;
if (Unbundle) {
if (InputFileNames.size() != 1) {
Error = true;
errs() << "error: only one input file supported in unbundling mode.\n";
}
if (OutputFileNames.size() != TargetNames.size()) {
Error = true;
errs() << "error: number of output files and targets should match in "
"unbundling mode.\n";
}
} else {
if (OutputFileNames.size() != 1) {
Error = true;
errs() << "error: only one output file supported in bundling mode.\n";
}
if (InputFileNames.size() != TargetNames.size()) {
Error = true;
errs() << "error: number of input files and targets should match in "
"bundling mode.\n";
}
}
// Verify that the offload kinds and triples are known. We also check that we
// have exactly one host target.
unsigned Index = 0u;
unsigned HostTargetNum = 0u;
for (StringRef Target : TargetNames) {
StringRef Kind;
StringRef Triple;
getOffloadKindAndTriple(Target, Kind, Triple);
bool KindIsValid = !Kind.empty();
KindIsValid = KindIsValid && StringSwitch<bool>(Kind)
.Case("host", true)
.Case("openmp", true)
.Case("hip", true)
.Default(false);
bool TripleIsValid = !Triple.empty();
llvm::Triple T(Triple);
TripleIsValid &= T.getArch() != Triple::UnknownArch;
if (!KindIsValid || !TripleIsValid) {
Error = true;
errs() << "error: invalid target '" << Target << "'";
if (!KindIsValid)
errs() << ", unknown offloading kind '" << Kind << "'";
if (!TripleIsValid)
errs() << ", unknown target triple '" << Triple << "'";
errs() << ".\n";
}
if (KindIsValid && Kind == "host") {
++HostTargetNum;
// Save the index of the input that refers to the host.
HostInputIndex = Index;
}
++Index;
}
if (HostTargetNum != 1) {
Error = true;
errs() << "error: expecting exactly one host target but got "
<< HostTargetNum << ".\n";
}
if (Error)
return 1;
// Save the current executable directory as it will be useful to find other
// tools.
BundlerExecutable = sys::fs::getMainExecutable(argv[0], &BundlerExecutable);
return Unbundle ? UnbundleFiles() : BundleFiles();
}
开发者ID:LegalizeAdulthood,项目名称:clang,代码行数:95,代码来源:ClangOffloadBundler.cpp
示例7: main
//===----------------------------------------------------------------------===//
// main for opt
//
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
// Enable debug stream buffering.
EnableDebugBuffering = true;
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
LLVMContext &Context = getGlobalContext();
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
// Initialize passes
PassRegistry &Registry = *PassRegistry::getPassRegistry();
initializeCore(Registry);
initializeScalarOpts(Registry);
initializeObjCARCOpts(Registry);
initializeVectorization(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
initializeIPA(Registry);
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);
// For codegen passes, only passes that do IR to IR transformation are
// supported.
initializeCodeGenPreparePass(Registry);
initializeAtomicExpandPass(Registry);
initializeRewriteSymbolsPass(Registry);
initializeWinEHPreparePass(Registry);
initializeDwarfEHPreparePass(Registry);
#ifdef LINK_POLLY_INTO_TOOLS
polly::initializePollyPasses(Registry);
#endif
// @LOCALMOD-BEGIN
initializeAddPNaClExternalDeclsPass(Registry);
initializeAllocateDataSegmentPass(Registry);
initializeBackendCanonicalizePass(Registry);
initializeCanonicalizeMemIntrinsicsPass(Registry);
initializeCleanupUsedGlobalsMetadataPass(Registry);
initializeConstantInsertExtractElementIndexPass(Registry);
initializeExpandAllocasPass(Registry);
initializeExpandArithWithOverflowPass(Registry);
initializeExpandByValPass(Registry);
initializeExpandConstantExprPass(Registry);
initializeExpandCtorsPass(Registry);
initializeExpandGetElementPtrPass(Registry);
initializeExpandIndirectBrPass(Registry);
initializeExpandLargeIntegersPass(Registry);
initializeExpandShuffleVectorPass(Registry);
initializeExpandSmallArgumentsPass(Registry);
initializeExpandStructRegsPass(Registry);
initializeExpandTlsConstantExprPass(Registry);
initializeExpandTlsPass(Registry);
initializeExpandVarArgsPass(Registry);
initializeFixVectorLoadStoreAlignmentPass(Registry);
initializeFlattenGlobalsPass(Registry);
initializeGlobalCleanupPass(Registry);
initializeGlobalizeConstantVectorsPass(Registry);
initializeInsertDivideCheckPass(Registry);
initializeInternalizeUsedGlobalsPass(Registry);
initializeNormalizeAlignmentPass(Registry);
initializePNaClABIVerifyFunctionsPass(Registry);
initializePNaClABIVerifyModulePass(Registry);
initializePNaClSjLjEHPass(Registry);
initializePromoteI1OpsPass(Registry);
initializePromoteIntegersPass(Registry);
initializeRemoveAsmMemoryPass(Registry);
initializeRenameEntryPointPass(Registry);
initializeReplacePtrsWithIntsPass(Registry);
initializeResolveAliasesPass(Registry);
initializeResolvePNaClIntrinsicsPass(Registry);
initializeRewriteAtomicsPass(Registry);
initializeRewriteLLVMIntrinsicsPass(Registry);
initializeRewritePNaClLibraryCallsPass(Registry);
initializeSandboxIndirectCallsPass(Registry);
initializeSandboxMemoryAccessesPass(Registry);
initializeSimplifyAllocasPass(Registry);
initializeSimplifyStructRegSignaturesPass(Registry);
initializeStripAttributesPass(Registry);
initializeStripMetadataPass(Registry);
initializeStripModuleFlagsPass(Registry);
initializeStripTlsPass(Registry);
initializeSubstituteUndefsPass(Registry);
// Emscripten passes:
initializeExpandI64Pass(Registry);
initializeExpandInsertExtractElementPass(Registry);
initializeLowerEmAsyncifyPass(Registry);
initializeLowerEmExceptionsPass(Registry);
initializeLowerEmSetjmpPass(Registry);
initializeNoExitRuntimePass(Registry);
// Emscripten passes end.
//.........这里部分代码省略.........
开发者ID:Maher4Ever,项目名称:emscripten-fastcomp,代码行数:101,代码来源:opt.cpp
示例8: runPasses
/// runPasses - Run the specified passes on Program, outputting a bitcode file
/// and writing the filename into OutputFile if successful. If the
/// optimizations fail for some reason (optimizer crashes), return true,
/// otherwise return false. If DeleteOutput is set to true, the bitcode is
/// deleted on success, and the filename string is undefined. This prints to
/// outs() a single line message indicating whether compilation was successful
/// or failed.
///
bool BugDriver::runPasses(Module *Program,
const std::vector<std::string> &Passes,
std::string &OutputFilename, bool DeleteOutput,
bool Quiet, unsigned NumExtraArgs,
const char * const *ExtraArgs) const {
// setup the output file name
outs().flush();
SmallString<128> UniqueFilename;
std::error_code EC = sys::fs::createUniqueFile(
OutputPrefix + "-output-%%%%%%%.bc", UniqueFilename);
if (EC) {
errs() << getToolName() << ": Error making unique filename: "
<< EC.message() << "\n";
return 1;
}
OutputFilename = UniqueFilename.str();
// set up the input file name
SmallString<128> InputFilename;
int InputFD;
EC = sys::fs::createUniqueFile(OutputPrefix + "-input-%%%%%%%.bc", InputFD,
InputFilename);
if (EC) {
errs() << getToolName() << ": Error making unique filename: "
<< EC.message() << "\n";
return 1;
}
tool_output_file InFile(InputFilename, InputFD);
WriteBitcodeToFile(Program, InFile.os(), PreserveBitcodeUseListOrder);
InFile.os().close();
if (InFile.os().has_error()) {
errs() << "Error writing bitcode file: " << InputFilename << "\n";
InFile.os().clear_error();
return 1;
}
std::string tool = OptCmd;
if (OptCmd.empty()) {
if (ErrorOr<std::string> Path = sys::findProgramByName("opt"))
tool = *Path;
else
errs() << Path.getError().message() << "\n";
}
if (tool.empty()) {
errs() << "Cannot find `opt' in PATH!\n";
return 1;
}
std::string Prog;
if (UseValgrind) {
if (ErrorOr<std::string> Path = sys::findProgramByName("valgrind"))
Prog = *Path;
else
errs() << Path.getError().message() << "\n";
} else
Prog = tool;
if (Prog.empty()) {
errs() << "Cannot find `valgrind' in PATH!\n";
return 1;
}
// Ok, everything that could go wrong before running opt is done.
InFile.keep();
// setup the child process' arguments
SmallVector<const char*, 8> Args;
if (UseValgrind) {
Args.push_back("valgrind");
Args.push_back("--error-exitcode=1");
Args.push_back("-q");
Args.push_back(tool.c_str());
} else
Args.push_back(tool.c_str());
Args.push_back("-o");
Args.push_back(OutputFilename.c_str());
for (unsigned i = 0, e = OptArgs.size(); i != e; ++i)
Args.push_back(OptArgs[i].c_str());
std::vector<std::string> pass_args;
for (unsigned i = 0, e = PluginLoader::getNumPlugins(); i != e; ++i) {
pass_args.push_back( std::string("-load"));
pass_args.push_back( PluginLoader::getPlugin(i));
}
for (std::vector<std::string>::const_iterator I = Passes.begin(),
E = Passes.end(); I != E; ++I )
pass_args.push_back( std::string("-") + (*I) );
for (std::vector<std::string>::const_iterator I = pass_args.begin(),
E = pass_args.end(); I != E; ++I )
Args.push_back(I->c_str());
Args.push_back(InputFilename.c_str());
//.........这里部分代码省略.........
开发者ID:CSI-LLVM,项目名称:llvm,代码行数:101,代码来源:OptimizerDriver.cpp
示例9: format
// Returns true on error.
static bool format(StringRef FileName) {
ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
MemoryBuffer::getFileOrSTDIN(FileName);
if (std::error_code EC = CodeOrErr.getError()) {
llvm::errs() << EC.message() << "\n";
return true;
}
std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
if (Code->getBufferSize() == 0)
return false; // Empty files are formatted correctly.
FormatterDocument Doc(std::move(Code));
if (!Offsets.empty() || !Lengths.empty()) {
if (Offsets.size() != Lengths.size()) {
llvm::errs() << "error: number of offsets not equal to number of lengths.\n";
return true;
}
for ( unsigned i=0 ; i < Offsets.size() ; i++ ) {
unsigned FromLine = Doc.getLineAndColumn(Offsets[i]).first;
unsigned ToLine = Doc.getLineAndColumn(Offsets[i] + Lengths[i]).first;
if (ToLine == 0) {
llvm::errs() << "error: offset + length after end of file\n";
return true;
}
std::ostringstream s;
s << FromLine << ":" << ToLine;
LineRanges.push_back(s.str());
}
}
if (LineRanges.empty())
LineRanges.push_back("1:999999");
std::string Output = Doc.memBuffer().getBuffer();
Replacements Replaces;
for ( unsigned Range = 0 ; Range < LineRanges.size() ; Range++ ) {
unsigned FromLine, ToLine;
if (parseLineRange(LineRanges[Range], FromLine, ToLine)) {
llvm::errs() << "error: invalid <start line>:<end line> pair\n";
return true;
}
if (FromLine > ToLine) {
llvm::errs() << "error: start line should be less than end line\n";
return true;
}
for ( unsigned Line = FromLine ; Line<=ToLine ; Line++ ) {
size_t Offset = getOffsetOfLine(Line,Output);
ssize_t Length = getOffsetOfLine(Line+1,Output)-1-Offset;
if (Length < 0)
break;
std::string Formatted = Doc.reformat(LineRange(Line,1), FormatOptions).second;
if (Formatted.find_first_not_of(" \t\v\f", 0) == StringRef::npos)
Formatted = "";
if (Formatted == Output.substr(Offset, Length))
continue;
Output.replace(Offset, Length, Formatted);
Doc.updateCode(std::move(MemoryBuffer::getMemBuffer(Output)));
Replaces.insert(clang::tooling::Replacement(FileName, Offset, Length, Formatted));
}
}
if (OutputXML) {
llvm::outs() << "<?xml version='1.0'?>\n<replacements>\n";
outputReplacementsXML(Replaces);
llvm::outs() << "</replacements>\n";
} else {
if (Inplace) {
if (FileName == "-") {
llvm::errs() << "error: cannot use -i when reading from stdin.\n";
return true;
}
else {
std::error_code EC;
raw_fd_ostream writer(FileName, EC, llvm::sys::fs::F_None);
if (EC) {
llvm::errs() << "error: writing " << FileName << ": " << EC.message() << "\n";
return true;
}
writer << Output;
}
} else {
llvm::outs() << Output;
}
}
return false;
}
开发者ID:johnno1962b,项目名称:swift,代码行数:95,代码来源:swift-format.cpp
示例10: main
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets and assembly printers/parsers.
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmParsers();
llvm::InitializeAllDisassemblers();
// Register the target printer for --version.
cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
TripleName = Triple::normalize(TripleName);
setDwarfDebugFlags(argc, argv);
setDwarfDebugProducer();
const char *ProgName = argv[0];
const Target *TheTarget = GetTarget(ProgName);
if (!TheTarget)
return 1;
OwningPtr<MemoryBuffer> BufferPtr;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
errs() << ProgName << ": " << ec.message() << '\n';
return 1;
}
MemoryBuffer *Buffer = BufferPtr.take();
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(IncludeDirs);
llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
assert(MRI && "Unable to create target register info!");
llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
assert(MAI && "Unable to create target asm info!");
// FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
// MCObjectFileInfo needs a MCContext reference in order to initialize itself.
OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
if (SaveTempLabels)
Ctx.setAllowTemporaryLabels(false);
Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
if (!DwarfDebugFlags.empty())
Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
if (!DwarfDebugProducer.empty())
Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
if (!DebugCompilationDir.empty())
Ctx.setCompilationDir(DebugCompilationDir);
if (!MainFileName.empty())
Ctx.setMainFileName(MainFileName);
// 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();
}
OwningPtr<tool_output_file> Out(GetOutputStream());
if (!Out)
return 1;
formatted_raw_ostream FOS(Out->os());
OwningPtr<MCStreamer> Str;
OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
OwningPtr<MCSubtargetInfo>
STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
MCInstPrinter *IP = NULL;
if (FileType == OFT_AssemblyFile) {
IP =
TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
MCCodeEmitter *CE = 0;
MCAsmBackend *MAB = 0;
if (ShowEncoding) {
CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
}
bool UseCFI = !DisableCFI;
Str.reset(TheTarget->createAsmStreamer(
Ctx, FOS, /*asmverbose*/ true, UseCFI,
//.........这里部分代码省略.........
开发者ID:adevress,项目名称:root-1,代码行数:101,代码来源:llvm-mc.cpp
示例11: printLineInfoForInput
static int printLineInfoForInput() {
// Load any dylibs requested on the command line.
loadDylibs();
// If we don't have any input files, read from stdin.
if (!InputFileList.size())
InputFileList.push_back("-");
for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
// Instantiate a dynamic linker.
TrivialMemoryManager MemMgr;
RuntimeDyld Dyld(MemMgr, MemMgr);
// Load the input memory buffer.
ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
if (std::error_code EC = InputBuffer.getError())
return Error("unable to read input: '" + EC.message() + "'");
ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
if (std::error_code EC = MaybeObj.getError())
return Error("unable to create object file: '" + EC.message() + "'");
ObjectFile &Obj = **MaybeObj;
// Load the object file
std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo =
Dyld.loadObject(Obj);
if (Dyld.hasError())
return Error(Dyld.getErrorString());
// Resolve all the relocations we can.
Dyld.resolveRelocations();
OwningBinary<ObjectFile> DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
std::unique_ptr<DIContext> Context(
DIContext::getDWARFContext(*DebugObj.getBinary()));
// Use symbol info to iterate functions in the object.
for (object::symbol_iterator I = DebugObj.getBinary()->symbol_begin(),
E = DebugObj.getBinary()->symbol_end();
I != E; ++I) {
object::SymbolRef::Type SymType;
if (I->getType(SymType)) continue;
if (SymType == object::SymbolRef::ST_Function) {
StringRef Name;
uint64_t Addr;
uint64_t Size;
if (I->getName(Name)) continue;
if (I->getAddress(Addr)) continue;
if (I->getSize(Size)) continue;
outs() << "Function: " << Name << ", Size = " << Size << "\n";
DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
DILineInfoTable::iterator Begin = Lines.begin();
DILineInfoTable::iterator End = Lines.end();
for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
outs() << " Line info @ " << It->first - Addr << ": "
<< It->second.FileName << ", line:" << It->second.Line << "\n";
}
}
}
}
return 0;
}
开发者ID:CODECOMMUNITY,项目名称:llvm,代码行数:71,代码来源:llvm-rtdyld.cpp
示例12: linkAndVerify
// Load and link the objects specified on the command line, but do not execute
// anything. Instead, attach a RuntimeDyldChecker instance and call it to
// verify the correctness of the linked memory.
static int linkAndVerify() {
// Check for missing triple.
if (TripleName == "") {
llvm::errs() << "Error: -triple required when running in -verify mode.\n";
return 1;
}
// Look up the target and build the disassembler.
Triple TheTriple(Triple::normalize(TripleName));
std::string ErrorStr;
const Target *TheTarget =
TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
if (!TheTarget) {
llvm::errs() << "Error accessing target '" << TripleName << "': "
<< ErrorStr << "\n";
return 1;
}
TripleName = TheTriple.getTriple();
std::unique_ptr<MCSubtargetInfo> STI(
TheTarget->createMCSubtargetInfo(TripleName, "", ""));
assert(STI && "Unable to create subtarget info!");
std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
assert(MRI && "Unable to create target register info!");
std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
assert(MAI && "Unable to create target asm info!");
MCContext Ctx(MAI.get(), MRI.get(), nullptr);
std::unique_ptr<MCDisassembler> Disassembler(
TheTarget->createMCDisassembler(*STI, Ctx));
assert(Disassembler && "Unable to create disassembler!");
std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
std::unique_ptr<MCInstPrinter> InstPrinter(
TheTarget->createMCInstPrinter(Triple(TripleName), 0, *MAI, *MII, *MRI));
// Load any dylibs requested on the command line.
loadDylibs();
// Instantiate a dynamic linker.
TrivialMemoryManager MemMgr;
RuntimeDyld Dyld(MemMgr, MemMgr);
Dyld.setProcessAllSections(true);
RuntimeDyldChecker Checker(Dyld, Disassembler.get(), InstPrinter.get(),
llvm::dbgs());
// FIXME: Preserve buffers until resolveRelocations time to work around a bug
// in RuntimeDyldELF.
// This fixme should be fixed ASAP. This is a very brittle workaround.
std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
// If we don't have any input files, read from stdin.
if (!InputFileList.size())
InputFileList.push_back("-");
for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
// Load the input memory buffer.
ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
if (std::error_code EC = InputBuffer.getError())
return Error("unable to read input: '" + EC.message() + "'");
ErrorOr<std::unique_ptr<ObjectFile>> MaybeObj(
ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
if (std::error_code EC = MaybeObj.getError())
return Error("unable to create object file: '" + EC.message() + "'");
ObjectFile &Obj = **MaybeObj;
InputBuffers.push_back(std::move(*InputBuffer));
// Load the object file
Dyld.loadObject(Obj);
if (Dyld.hasError()) {
return Error(Dyld.getErrorString());
}
}
// Re-map the section addresses into the phony target address space.
remapSections(TheTriple, MemMgr, Checker);
// Resolve all the relocations we can.
Dyld.resolveRelocations();
// Register EH frames.
Dyld.registerEHFrames();
int ErrorCode = checkAllExpressions(Checker);
if (Dyld.hasError()) {
errs() << "RTDyld reported an error applying relocations:\n "
<< Dyld.getErrorString() << "\n";
ErrorCode = 1;
//.........这里部分代码省略.........
开发者ID:CODECOMMUNITY,项目名称:llvm,代码行数:101,代码来源:llvm-rtdyld.cpp
示例13: main
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal(argv[0]);
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets and assembly printers/parsers.
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmParsers();
llvm::InitializeAllDisassemblers();
// Register the target printer for --version.
cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
TripleName = Triple::normalize(TripleName);
setDwarfDebugFlags(argc, argv);
setDwarfDebugProducer();
const char *ProgName = argv[0];
const Target *TheTarget = GetTarget(ProgName);
if (!TheTarget)
return 1;
// Now that GetTarget() has (potentially) replaced TripleName, it's safe to
// construct the Triple object.
Triple TheTriple(TripleName);
ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
MemoryBuffer::getFileOrSTDIN(InputFilename);
if (std::error_code EC = BufferPtr.getError()) {
errs() << InputFilename << ": " << EC.message() << '\n';
return 1;
}
MemoryBuffer *Buffer = BufferPtr->get();
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(IncludeDirs);
std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
assert(MRI && "Unable to create target register info!");
std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
assert(MAI && "Unable to create target asm info!");
MAI->setRelaxELFRelocations(RelaxELFRel);
if (CompressDebugSections != DebugCompressionType::None) {
if (!zlib::isAvailable()) {
errs() << ProgName
|
请发表评论