本文整理汇总了C++中cl::opt类的典型用法代码示例。如果您正苦于以下问题:C++ opt类的具体用法?C++ opt怎么用?C++ opt使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了opt类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: addMachinePasses
/// Add the complete set of target-independent postISel code generator passes.
///
/// This can be read as the standard order of major LLVM CodeGen stages. Stages
/// with nontrivial configuration or multiple passes are broken out below in
/// add%Stage routines.
///
/// Any TargetPassConfig::addXX routine may be overriden by the Target. The
/// addPre/Post methods with empty header implementations allow injecting
/// target-specific fixups just before or after major stages. Additionally,
/// targets have the flexibility to change pass order within a stage by
/// overriding default implementation of add%Stage routines below. Each
/// technique has maintainability tradeoffs because alternate pass orders are
/// not well supported. addPre/Post works better if the target pass is easily
/// tied to a common pass. But if it has subtle dependencies on multiple passes,
/// the target should override the stage instead.
///
/// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
/// before/after any target-independent pass. But it's currently overkill.
void TargetPassConfig::addMachinePasses() {
AddingMachinePasses = true;
// Insert a machine instr printer pass after the specified pass.
if (!StringRef(PrintMachineInstrs.getValue()).equals("") &&
!StringRef(PrintMachineInstrs.getValue()).equals("option-unspecified")) {
const PassRegistry *PR = PassRegistry::getPassRegistry();
const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
assert (TPI && IPI && "Pass ID not registered!");
const char *TID = (const char *)(TPI->getTypeInfo());
const char *IID = (const char *)(IPI->getTypeInfo());
insertPass(TID, IID);
}
// Print the instruction selected machine code...
printAndVerify("After Instruction Selection");
if (TM->Options.EnableIPRA)
addPass(createRegUsageInfoPropPass());
// Expand pseudo-instructions emitted by ISel.
addPass(&ExpandISelPseudosID);
// Add passes that optimize machine instructions in SSA form.
if (getOptLevel() != CodeGenOpt::None) {
addMachineSSAOptimization();
} else {
// If the target requests it, assign local variables to stack slots relative
// to one another and simplify frame index references where possible.
addPass(&LocalStackSlotAllocationID, false);
}
// Run pre-ra passes.
addPreRegAlloc();
// Run register allocation and passes that are tightly coupled with it,
// including phi elimination and scheduling.
if (getOptimizeRegAlloc())
addOptimizedRegAlloc(createRegAllocPass(true));
else
addFastRegAlloc(createRegAllocPass(false));
// Run post-ra passes.
addPostRegAlloc();
// Insert prolog/epilog code. Eliminate abstract frame index references...
if (getOptLevel() != CodeGenOpt::None)
addPass(&ShrinkWrapID);
// Prolog/Epilog inserter needs a TargetMachine to instantiate. But only
// do so if it hasn't been disabled, substituted, or overridden.
if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID))
addPass(createPrologEpilogInserterPass(TM));
/// Add passes that optimize machine instructions after register allocation.
if (getOptLevel() != CodeGenOpt::None)
addMachineLateOptimization();
// Expand pseudo instructions before second scheduling pass.
addPass(&ExpandPostRAPseudosID);
// Run pre-sched2 passes.
addPreSched2();
if (EnableImplicitNullChecks)
addPass(&ImplicitNullChecksID);
// Second pass scheduler.
// Let Target optionally insert this pass by itself at some other
// point.
if (getOptLevel() != CodeGenOpt::None &&
!TM->targetSchedulesPostRAScheduling()) {
if (MISchedPostRA)
addPass(&PostMachineSchedulerID);
else
addPass(&PostRASchedulerID);
}
// GC
if (addGCPasses()) {
if (PrintGCInfo)
//.........这里部分代码省略.........
示例2: main
//.........这里部分代码省略.........
SetBackdoorDriverOutputsFromEnvVars(TheDriver);
std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(clang_argv));
if(!C.get()) {
Res = 1;
goto cleanup;
}
SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
for (auto &J : C->getJobs())
ExecuteTemplightCommand(TheDriver, Diags, *C, J, clang_argv[0], FailingCommands);
// Merge all the temp files into a single output file:
if ( ! TempOutputFiles.empty() ) {
if ( OutputFilename.empty() )
OutputFilename = "a";
std::string FinalOutputFilename = TemplightAction::CreateOutputFilename(
nullptr, OutputFilename,
InstProfiler, OutputToStdOut, MemoryProfile);
if ( ( !FinalOutputFilename.empty() ) && ( FinalOutputFilename != "-" ) ) {
std::error_code error;
llvm::raw_fd_ostream TraceOS(FinalOutputFilename, error, llvm::sys::fs::F_None);
if ( error ) {
llvm::errs() <<
"Error: [Templight] Can not open file to write trace of template instantiations: "
<< FinalOutputFilename << " Error: " << error.message();
} else {
for ( SmallVector< std::string, 32 >::iterator it = TempOutputFiles.begin(),
it_end = TempOutputFiles.end(); it != it_end; ++it) {
llvm::ErrorOr< std::unique_ptr<llvm::MemoryBuffer> >
file_epbuf = llvm::MemoryBuffer::getFile(llvm::Twine(*it));
if(file_epbuf && file_epbuf.get()) {
TraceOS << StringRef(file_epbuf.get()->getBufferStart(),
file_epbuf.get()->getBufferEnd() - file_epbuf.get()->getBufferStart())
<< '\n';
}
}
}
}
}
// Remove temp files.
C->CleanupFileList(C->getTempFiles());
// If the command succeeded, the number of failing commands should zero:
Res = FailingCommands.size();
// Otherwise, remove result files and print extra information about abnormal
// failures.
for (SmallVectorImpl< std::pair<int, const Command *> >::iterator it =
FailingCommands.begin(), ie = FailingCommands.end(); it != ie; ++it) {
int FailRes = it->first;
const Command *FailingCommand = it->second;
// Remove result files if we're not saving temps.
if (!C->getArgs().hasArg(options::OPT_save_temps)) {
const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
C->CleanupFileMap(C->getResultFiles(), JA, true);
// Failure result files are valid unless we crashed.
if (FailRes < 0)
C->CleanupFileMap(C->getFailureResultFiles(), JA, true);
}
// Print extra information about abnormal failures, if possible.
const Tool &FailingTool = FailingCommand->getCreator();
if (!FailingCommand->getCreator().hasGoodDiagnostics() || FailRes != 1) {
if (FailRes < 0)
Diags.Report(clang::diag::err_drv_command_signalled)
<< FailingTool.getShortName();
else
Diags.Report(clang::diag::err_drv_command_failed)
<< FailingTool.getShortName() << FailRes;
}
}
}
cleanup:
// If any timers were active but haven't been destroyed yet, print their
// results now. This happens in -disable-free mode.
llvm::TimerGroup::printAll(llvm::errs());
llvm::llvm_shutdown();
#ifdef LLVM_ON_WIN32
// Exit status should not be negative on Win32, unless abnormal termination.
// Once abnormal termiation was caught, negative status should not be
// propagated.
if (Res < 0)
Res = 1;
#endif
// If we have multiple failing commands, we return the result of the first
// failing command.
return Res;
}
示例3: main
//.........这里部分代码省略.........
Files.push_back(sys::Path(InputFilenames[i]));
if (TheLinker.LinkInFiles(Files))
return 1; // Error already printed
// The libraries aren't linked in but are noted as "dependent" in the
// module.
for (cl::list<std::string>::const_iterator I = Libraries.begin(),
E = Libraries.end(); I != E ; ++I) {
TheLinker.getModule()->addLibrary(*I);
}
} else {
// Build a list of the items from our command line
Linker::ItemList Items;
BuildLinkItems(Items, InputFilenames, Libraries);
// Link all the items together
if (TheLinker.LinkInItems(Items, NativeLinkItems) )
return 1; // Error already printed
}
std::auto_ptr<Module> Composite(TheLinker.releaseModule());
// Optimize the module
Optimize(Composite.get());
// Generate the bitcode output.
GenerateBitcode(Composite.get(), BitcodeOutputFilename);
// If we are not linking a library, generate either a native executable
// or a JIT shell script, depending upon what the user wants.
if (!LinkAsLibrary) {
// If the user wants to run a post-link optimization, run it now.
if (!PostLinkOpts.empty()) {
std::vector<std::string> opts = PostLinkOpts;
for (std::vector<std::string>::iterator I = opts.begin(),
E = opts.end(); I != E; ++I) {
sys::Path prog(*I);
if (!prog.canExecute()) {
prog = sys::Program::FindProgramByName(*I);
if (prog.isEmpty())
PrintAndExit(std::string("Optimization program '") + *I +
"' is not found or not executable.", Composite.get());
}
// Get the program arguments
sys::Path tmp_output("opt_result");
std::string ErrMsg;
if (tmp_output.createTemporaryFileOnDisk(true, &ErrMsg))
PrintAndExit(ErrMsg, Composite.get());
const char* args[4];
args[0] = I->c_str();
args[1] = BitcodeOutputFilename.c_str();
args[2] = tmp_output.c_str();
args[3] = 0;
if (0 == sys::Program::ExecuteAndWait(prog, args, 0,0,0,0, &ErrMsg)) {
if (tmp_output.isBitcodeFile()) {
sys::Path target(BitcodeOutputFilename);
target.eraseFromDisk();
if (tmp_output.renamePathOnDisk(target, &ErrMsg))
PrintAndExit(ErrMsg, Composite.get(), 2);
} else
PrintAndExit("Post-link optimization output is not bitcode",
Composite.get());
} else {
PrintAndExit(ErrMsg, Composite.get());
}
示例4: main
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal(argv[0]);
llvm::PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
LLVMContext Context;
//InitializeAllTargets();
//InitializeAllTargetMCs();
// 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);
initializeSoaapPass(Registry);
cl::ParseCommandLineOptions(argc, argv,
"llvm .bc -> .bc modular optimizer and analysis printer\n");
SMDiagnostic Err;
// Load the input module...
std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
if (!M.get()) {
Err.print(argv[0], errs());
return 1;
}
// Warn if M doesn't have debug info
if (M->getNamedMetadata("llvm.dbg.cu") == NULL) {
errs() << "**********************************************************\n";
errs() << "WARNING: Input IR file does not contain debug information\n";
errs() << "**********************************************************\n";
}
// Figure out what stream we are supposed to write to...
std::unique_ptr<tool_output_file> Out;
if (!OutputFilename.empty()) {
std::error_code EC;
Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
if (EC) {
errs() << EC.message() << '\n';
return 1;
}
}
// Create a PassManager to hold and optimize the collection of passes we are
// about to build.
//
legacy::PassManager Passes;
Passes.add(new soaap::Soaap);
// Check that the module is well formed on completion of optimization
if (!OutputFilename.empty()) {
if (Verify)
Passes.add(createVerifierPass());
// Pass to create output
if (OutputAssembly)
Passes.add(createPrintModulePass(Out->os()));
else
Passes.add(createBitcodeWriterPass(Out->os()));
}
// Now that we have all of the passes ready, run them.
Passes.run(*M.get());
// Declare success.
if (!OutputFilename.empty()) {
Out->keep();
}
return 0;
}
示例5: LLVMFuzzerInitialize
int LLVMFuzzerInitialize(int *argc, char ***argv) {
// The command line is unusual compared to other fuzzers due to the need to
// specify the target. Options like -triple, -mcpu, and -mattr work like
// their counterparts in llvm-mc, while -fuzzer-args collects options for the
// fuzzer itself.
//
// Examples:
//
// Fuzz the big-endian MIPS32R6 disassembler using 100,000 inputs of up to
// 4-bytes each and use the contents of ./corpus as the test corpus:
// llvm-mc-fuzzer -triple mips-linux-gnu -mcpu=mips32r6 -disassemble \
// -fuzzer-args -max_len=4 -runs=100000 ./corpus
//
// Infinitely fuzz the little-endian MIPS64R2 disassembler with the MSA
// feature enabled using up to 64-byte inputs:
// llvm-mc-fuzzer -triple mipsel-linux-gnu -mcpu=mips64r2 -mattr=msa \
// -disassemble -fuzzer-args ./corpus
//
// If your aim is to find instructions that are not tested, then it is
// advisable to constrain the maximum input size to a single instruction
// using -max_len as in the first example. This results in a test corpus of
// individual instructions that test unique paths. Without this constraint,
// there will be considerable redundancy in the corpus.
char **OriginalArgv = *argv;
LLVMInitializeAllTargetInfos();
LLVMInitializeAllTargetMCs();
LLVMInitializeAllAsmParsers();
cl::ParseCommandLineOptions(*argc, OriginalArgv);
// Rebuild the argv without the arguments llvm-mc-fuzzer consumed so that
// the driver can parse its arguments.
//
// FuzzerArgs cannot provide the non-const pointer that OriginalArgv needs.
// Re-use the strings from OriginalArgv instead of copying FuzzerArg to a
// non-const buffer to avoid the need to clean up when the fuzzer terminates.
ModifiedArgv.push_back(OriginalArgv[0]);
for (const auto &FuzzerArg : FuzzerArgs) {
for (int i = 1; i < *argc; ++i) {
if (FuzzerArg == OriginalArgv[i])
ModifiedArgv.push_back(OriginalArgv[i]);
}
}
*argc = ModifiedArgv.size();
*argv = ModifiedArgv.data();
// Package up features to be passed to target/subtarget
// We have to pass it via a global since the callback doesn't
// permit any user data.
if (MAttrs.size()) {
SubtargetFeatures Features;
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
if (TripleName.empty())
TripleName = sys::getDefaultTargetTriple();
return 0;
}
示例6: main
//===----------------------------------------------------------------------===//
// main for instrument
//
int main(int argc, char **argv) {
llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
LLVMContext &Context = getGlobalContext();
try {
cl::ParseCommandLineOptions(argc, argv,
"zoltar .bc -> .bc instrumenter and mutator\n");
sys::PrintStackTraceOnErrorSignal();
// 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;
std::string ErrorMessage;
// Load the input module...
std::auto_ptr<Module> M;
if (MemoryBuffer *Buffer
= MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
M.reset(ParseBitcodeFile(Buffer, Context, &ErrorMessage));
delete Buffer;
}
if (M.get() == 0) {
errs() << argv[0] << ": ";
if (ErrorMessage.size())
errs() << ErrorMessage << "\n";
else
errs() << "bitcode didn't read correctly.\n";
return 1;
}
// Figure out what stream we are supposed to write to...
// FIXME: outs() is not binary!
raw_ostream *Out = &outs(); // Default to printing to stdout...
if (OutputFilename != "-") {
std::string ErrorInfo;
/*TODO: solve this problem */
//Out = new raw_fd_ostream(OutputFilename.c_str(), /*Binary=*/true,
// Force, ErrorInfo);
Out = new raw_fd_ostream(OutputFilename.c_str(),ErrorInfo,0);
if (!ErrorInfo.empty()) {
errs() << ErrorInfo << '\n';
if (!Force)
errs() << "Use -f command line argument to force output\n";
delete Out;
return 1;
}
// Make sure that the Output file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
}
// 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 && CheckBitcodeOutputToConsole(*Out,!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...
Passes.add(new TargetData(M.get()));
// Create a new instrumentation pass for each one specified on the command line
for (unsigned i = 0; i < PassList.size(); ++i) {
const PassInfo *PassInf = PassList[i];
Pass *P = 0;
if (PassInf->getNormalCtor())
P = PassInf->getNormalCtor()();
else
errs() << argv[0] << ": cannot create pass: "
<< PassInf->getPassName() << "\n";
if (P) {
Passes.add(P);
}
}
// Enable the specified mutation operators
if (!MutOps) {
OperatorManager* OM = OperatorManager::getInstance();
OperatorInfoList::iterator oit;
for (oit = OM->getRegistered().begin(); oit != OM->getRegistered().end(); oit++) {
(*oit)->setEnabled(true);
}
} else {
for (unsigned i = 0; i < OperatorList.size(); ++i) {
OperatorInfo *OInf = OperatorList[i];
OInf->setEnabled(true);
}
//.........这里部分代码省略.........
示例7: process
int ObjectGenerator::process(Module *module) {
cerr << "Starting object generation" << endl;
cerr.flush();
// if (false) {
//
// Initialize targets first, so that --version shows registered targets.
//
InitializeAllTargets();
InitializeAllAsmPrinters();
//
// Load the module to be compiled...
//
SMDiagnostic Err;
Module &mod = *module;
//
// 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() << "RoseToLLVM" /*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() << "RoseToLLVM" /*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(), "RoseToLLVM"/*argv[0]*/);
if (Out == 0) return 1;
CodeGenOpt::Level OLvl = CodeGenOpt::Default;
switch (OptLevel) {
default:
cerr << "The optimization level is " << OptLevel << endl;
cerr.flush();
errs() << "RoseToLLVM" /*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;
}
//.........这里部分代码省略.........
示例8: startCmdLine
//Command line decoder control
void startCmdLine(){
LLVMContext &Context = getGlobalContext();
for (unsigned int i =0 ; i < PassList.size(); i++ ){
cout << "Pass added: "<< PassList[i]->getPassName() << endl;
cout << "Argument name :" << PassList[i]->getPassArgument() << endl;
}
clock_t timer = clock();
//Parsing XDF file
std::cout << "Parsing file " << XDFFile.getValue() << "." << endl;
XDFParser xdfParser(Verbose);
Network* network = xdfParser.parseFile(XDFFile, Context);
cout << "Network parsed in : "<< (clock() - timer) * 1000 / CLOCKS_PER_SEC << " ms, start engine" << endl;
//Parsing XCF file if needed
if(XCFFile != "") {
std::cout << "Parsing file " << XCFFile.getValue() << "." << endl;
XCFParser xcfParser(Verbose);
map<string, string>* mapping = xcfParser.parseFile(XCFFile);
network->setMapping(mapping);
}
if (enableTrace){
setTraces(network);
}
//Load network
engine->load(network);
// Optimizing decoder
if (optLevel > 0){
engine->optimize(network, optLevel);
}
// Verify the given decoder if needed
if (Verify){
engine->verify(network, "error.txt");
}
// Set input file
input_file = (char*)VidFile.c_str();
// Print the given decoder if needed
if (OutputDir != ""){
engine->print(network);
}
//Run network
engine->run(network);
cout << "End of Jade" << endl;
cout << "Total time: " << (clock() - timer) * 1000 / CLOCKS_PER_SEC << " ms" << endl;
if(XCFFile != "") {
cout << "Note: This execution time is calculated from CPU clock. When more than 1 thread were run, "
"the value displayed is higher than the real execution time." << endl;
}
}
示例9: remapSectionsAndSymbols
// Scatter sections in all directions!
// Remaps section addresses for -verify mode. The following command line options
// can be used to customize the layout of the memory within the phony target's
// address space:
// -target-addr-start <s> -- Specify where the phony target addres range starts.
// -target-addr-end <e> -- Specify where the phony target address range ends.
// -target-section-sep <d> -- Specify how big a gap should be left between the
// end of one section and the start of the next.
// Defaults to zero. Set to something big
// (e.g. 1 << 32) to stress-test stubs, GOTs, etc.
//
static void remapSectionsAndSymbols(const llvm::Triple &TargetTriple,
TrivialMemoryManager &MemMgr,
RuntimeDyldChecker &Checker) {
// Set up a work list (section addr/size pairs).
typedef std::list<std::pair<void*, uint64_t>> WorklistT;
WorklistT Worklist;
for (const auto& CodeSection : MemMgr.FunctionMemory)
Worklist.push_back(std::make_pair(CodeSection.base(), CodeSection.size()));
for (const auto& DataSection : MemMgr.DataMemory)
Worklist.push_back(std::make_pair(DataSection.base(), DataSection.size()));
// Apply any section-specific mappings that were requested on the command
// line.
typedef std::map<void*, uint64_t> AppliedMappingsT;
AppliedMappingsT AppliedMappings = applySpecificSectionMappings(Checker);
// Keep an "already allocated" mapping of section target addresses to sizes.
// Sections whose address mappings aren't specified on the command line will
// allocated around the explicitly mapped sections while maintaining the
// minimum separation.
std::map<uint64_t, uint64_t> AlreadyAllocated;
// Move the previously applied mappings into the already-allocated map.
for (WorklistT::iterator I = Worklist.begin(), E = Worklist.end();
I != E;) {
WorklistT::iterator Tmp = I;
++I;
AppliedMappingsT::iterator AI = AppliedMappings.find(Tmp->first);
if (AI != AppliedMappings.end()) {
AlreadyAllocated[AI->second] = Tmp->second;
Worklist.erase(Tmp);
}
}
// If the -target-addr-end option wasn't explicitly passed, then set it to a
// sensible default based on the target triple.
if (TargetAddrEnd.getNumOccurrences() == 0) {
if (TargetTriple.isArch16Bit())
TargetAddrEnd = (1ULL << 16) - 1;
else if (TargetTriple.isArch32Bit())
TargetAddrEnd = (1ULL << 32) - 1;
// TargetAddrEnd already has a sensible default for 64-bit systems, so
// there's nothing to do in the 64-bit case.
}
// Process any elements remaining in the worklist.
while (!Worklist.empty()) {
std::pair<void*, uint64_t> CurEntry = Worklist.front();
Worklist.pop_front();
uint64_t NextSectionAddr = TargetAddrStart;
for (const auto &Alloc : AlreadyAllocated)
if (NextSectionAddr + CurEntry.second + TargetSectionSep <= Alloc.first)
break;
else
NextSectionAddr = Alloc.first + Alloc.second + TargetSectionSep;
AlreadyAllocated[NextSectionAddr] = CurEntry.second;
Checker.getRTDyld().mapSectionAddress(CurEntry.first, NextSectionAddr);
}
// Add dummy symbols to the memory manager.
for (const auto &Mapping : DummySymbolMappings) {
size_t EqualsIdx = Mapping.find_first_of("=");
if (EqualsIdx == StringRef::npos)
report_fatal_error("Invalid dummy symbol specification '" + Mapping +
"'. Should be '<symbol name>=<addr>'");
std::string Symbol = Mapping.substr(0, EqualsIdx);
std::string AddrStr = Mapping.substr(EqualsIdx + 1);
uint64_t Addr;
if (StringRef(AddrStr).getAsInteger(0, Addr))
report_fatal_error("Invalid symbol mapping '" + Mapping + "'.");
MemMgr.addDummySymbol(Symbol, Addr);
}
}
示例10: canCompletelyDuplicateBB
/// Determine if it is profitable to duplicate this block.
bool
TailDuplicatePass::shouldTailDuplicate(const MachineFunction &MF,
bool IsSimple,
MachineBasicBlock &TailBB) {
// Only duplicate blocks that end with unconditional branches.
if (TailBB.canFallThrough())
return false;
// Don't try to tail-duplicate single-block loops.
if (TailBB.isSuccessor(&TailBB))
return false;
// Set the limit on the cost to duplicate. When optimizing for size,
// duplicate only one, because one branch instruction can be eliminated to
// compensate for the duplication.
unsigned MaxDuplicateCount;
if (TailDuplicateSize.getNumOccurrences() == 0 &&
// FIXME: Use Function::optForSize().
MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
MaxDuplicateCount = 1;
else
MaxDuplicateCount = TailDuplicateSize;
// If the target has hardware branch prediction that can handle indirect
// branches, duplicating them can often make them predictable when there
// are common paths through the code. The limit needs to be high enough
// to allow undoing the effects of tail merging and other optimizations
// that rearrange the predecessors of the indirect branch.
bool HasIndirectbr = false;
if (!TailBB.empty())
HasIndirectbr = TailBB.back().isIndirectBranch();
if (HasIndirectbr && PreRegAlloc)
MaxDuplicateCount = 20;
// Check the instructions in the block to determine whether tail-duplication
// is invalid or unlikely to be profitable.
unsigned InstrCount = 0;
for (MachineInstr &MI : TailBB) {
// Non-duplicable things shouldn't be tail-duplicated.
if (MI.isNotDuplicable())
return false;
// Do not duplicate 'return' instructions if this is a pre-regalloc run.
// A return may expand into a lot more instructions (e.g. reload of callee
// saved registers) after PEI.
if (PreRegAlloc && MI.isReturn())
return false;
// Avoid duplicating calls before register allocation. Calls presents a
// barrier to register allocation so duplicating them may end up increasing
// spills.
if (PreRegAlloc && MI.isCall())
return false;
if (!MI.isPHI() && !MI.isDebugValue())
InstrCount += 1;
if (InstrCount > MaxDuplicateCount)
return false;
}
if (HasIndirectbr && PreRegAlloc)
return true;
if (IsSimple)
return true;
if (!PreRegAlloc)
return true;
return canCompletelyDuplicateBB(TailBB);
}
示例11: main
int main(int argc, char **argv) {
#ifndef DEBUG_BUGPOINT
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
#endif
// 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);
#ifdef LINK_POLLY_INTO_TOOLS
polly::initializePollyPasses(Registry);
#endif
cl::ParseCommandLineOptions(argc, argv,
"LLVM automatic testcase reducer. See\nhttp://"
"llvm.org/cmds/bugpoint.html"
" for more information.\n");
#ifndef DEBUG_BUGPOINT
sys::SetInterruptFunction(BugpointInterruptFunction);
#endif
LLVMContext& Context = getGlobalContext();
// If we have an override, set it and then track the triple we want Modules
// to use.
if (!OverrideTriple.empty()) {
TargetTriple.setTriple(Triple::normalize(OverrideTriple));
outs() << "Override triple set to '" << TargetTriple.getTriple() << "'\n";
}
if (MemoryLimit < 0) {
// Set the default MemoryLimit. Be sure to update the flag's description if
// you change this.
if (sys::RunningOnValgrind() || UseValgrind)
MemoryLimit = 800;
else
MemoryLimit = 300;
}
BugDriver D(argv[0], FindBugs, TimeoutValue, MemoryLimit,
UseValgrind, Context);
if (D.addSources(InputFilenames)) return 1;
AddToDriver PM(D);
if (StandardLinkOpts) {
PassManagerBuilder Builder;
Builder.Inliner = createFunctionInliningPass();
Builder.populateLTOPassManager(PM);
}
if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
PassManagerBuilder Builder;
if (OptLevelO1)
Builder.Inliner = createAlwaysInlinerPass();
else if (OptLevelO2)
Builder.Inliner = createFunctionInliningPass(225);
else
Builder.Inliner = createFunctionInliningPass(275);
// Note that although clang/llvm-gcc use two separate passmanagers
// here, it shouldn't normally make a difference.
Builder.populateFunctionPassManager(PM);
Builder.populateModulePassManager(PM);
}
for (std::vector<const PassInfo*>::iterator I = PassList.begin(),
E = PassList.end();
I != E; ++I) {
const PassInfo* PI = *I;
D.addPass(PI->getPassArgument());
}
// Bugpoint has the ability of generating a plethora of core files, so to
// avoid filling up the disk, we prevent it
#ifndef DEBUG_BUGPOINT
sys::Process::PreventCoreFiles();
#endif
std::string Error;
bool Failure = D.run(Error);
if (!Error.empty()) {
errs() << Error;
return 1;
}
return Failure;
}
示例12: main
int main(int argc, char* argv[])
{
std::string programName = argv[0];
try
{
cl::ParseCommandLineOptions( argc, argv );
SMDiagnostic Err;
// Load the input module.
std::auto_ptr<Module> M(ParseAssemblyFile(InputFilename, Err, Context));
if (M.get() == 0)
{
Err.Print(argv[0], errs());
return (1);
}
if (!DisableVerify) {
std::string Err;
if (verifyModule(*M.get(), ReturnStatusAction, &Err)) {
errs() << argv[0]
<< ": assembly parsed, but does not verify as correct!\n";
errs() << Err;
return (1);
}
}
std::ostream *Out = new std::ofstream(OutputFilename.c_str(),
std::ios::out | std::ios::trunc
| std::ios::binary);
if (!Out->good())
{
std::cerr << programName << ": Error opening " << OutputFilename
<< "!\n";
return (1);
}
if (DumpAsm)
errs() << "Here's the assembly:\n" << *M.get();
PassManager Passes;
raw_os_ostream L(*Out);
// Add an appropriate TargetData instance for this module.
Passes.add(new TargetData("onfuscator"));
Passes.add(new MakeDispatcherPass());
// Passes.add(new WriteBytecodePass(Out, true));
Passes.add(createPrintModulePass(&L));
Passes.run( *M.get() );
}
catch( std::exception e )
{
std::cerr << programName << ": " << e.what() << "\n";
return (1);
}
catch( const std::string& msg )
{
std::cerr << programName << ": " << msg << "\n";
return (1);
}
catch( ... )
{
std::cerr << programName << ": Unexpected exception occurred.\n";
return (1);
}
return (0);
}
示例13: if
void WorklessInstrument::InstrumentWorkless0Star1(Module * pModule, Loop * pLoop)
{
Function * pMain = NULL;
if(strMainName != "" )
{
pMain = pModule->getFunction(strMainName.c_str());
}
else
{
pMain = pModule->getFunction("main");
}
LoadInst * pLoad;
BinaryOperator* pAdd = NULL;
StoreInst * pStore = NULL;
for (Function::iterator BB = pMain->begin(); BB != pMain->end(); ++BB)
{
if(BB->getName().equals("entry"))
{
CallInst * pCall;
StoreInst * pStore;
Instruction * II = BB->begin();
pCall = CallInst::Create(this->InitHooks, "", II);
pCall->setCallingConv(CallingConv::C);
pCall->setTailCall(false);
AttributeSet emptySet;
pCall->setAttributes(emptySet);
pCall = CallInst::Create(this->getenv, this->SAMPLE_RATE_ptr, "", II);
pCall->setCallingConv(CallingConv::C);
pCall->setTailCall(false);
AttributeSet AS;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
PAS = AttributeSet::get(pModule->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
AS = AttributeSet::get(pModule->getContext(), Attrs);
}
pCall->setAttributes(AS);
pCall = CallInst::Create(this->function_atoi, pCall, "", II);
pCall->setCallingConv(CallingConv::C);
pCall->setTailCall(false);
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
B.addAttribute(Attribute::ReadOnly);
PAS = AttributeSet::get(pModule->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
AS = AttributeSet::get(pModule->getContext(), Attrs);
}
pCall->setAttributes(AS);
pStore = new StoreInst(pCall, this->SAMPLE_RATE, false, II);
pStore->setAlignment(4);
pCall = CallInst::Create(this->geo, pCall, "", II);
pCall->setCallingConv(CallingConv::C);
pCall->setTailCall(false);
pCall->setAttributes(emptySet);
CastInst * pCast = CastInst::CreateIntegerCast(pCall, this->LongType, true, "", II);
pStore = new StoreInst(pCast, this->CURRENT_SAMPLE, false, II);
pStore->setAlignment(8);
vector<Value *> vecParam;
vecParam.push_back(this->Output_Format_String);
vecParam.push_back(pCall);
pCall = CallInst::Create(this->printf, vecParam, "", II);
pCall->setCallingConv(CallingConv::C);
pCall->setTailCall(false);
pCall->setAttributes(emptySet);
break;
}
}
for (Function::iterator BB = pMain->begin(); BB != pMain->end(); ++BB)
{
for (BasicBlock::iterator Ins = BB->begin(); Ins != BB->end(); ++Ins)
{
if (isa<ReturnInst>(Ins) || isa<ResumeInst>(Ins))
{
vector<Value*> vecParams;
pLoad = new LoadInst(numIterations, "", false, Ins);
pLoad->setAlignment(8);
vecParams.push_back(pLoad);
//.........这里部分代码省略.........
示例14: if
formatted_raw_ostream *ObjectGenerator::GetOutputStream(const char *TargetName, const char *ProgName) {
if (OutputFilename != "") {
if (OutputFilename == "-")
return &fouts();
//
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
//
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
std::string error;
raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error, raw_fd_ostream::F_Binary);
if (! error.empty()) {
errs() << error << '\n';
delete FDOut;
return 0;
}
formatted_raw_ostream *Out = new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
return Out;
}
if (InputFilename == "-") {
OutputFilename = "-";
return &fouts();
}
OutputFilename = GetFileNameRoot(InputFilename);
bool Binary = false;
switch (FileType) {
default: assert(0 && "Unknown file type");
case TargetMachine::CGFT_AssemblyFile:
if (TargetName[0] == 'c') {
if (TargetName[1] == 0)
OutputFilename += ".cbe.c";
else if (TargetName[1] == 'p' && TargetName[2] == 'p')
OutputFilename += ".cpp";
else OutputFilename += ".s";
}
else OutputFilename += ".s";
break;
case TargetMachine::CGFT_ObjectFile:
OutputFilename += ".o";
Binary = true;
break;
// case TargetMachine::CGFT_Null:
// OutputFilename += ".null";
// Binary = true;
// break;
}
//
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
//
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
std::string error;
unsigned OpenFlags = 0;
if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error, OpenFlags);
if (!error.empty()) {
errs() << error << '\n';
delete FDOut;
return 0;
}
formatted_raw_ostream *Out = new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
return Out;
}
示例15: 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 .bc -> .ll disassembler\n");
std::string ErrorMessage;
std::auto_ptr<Module> M;
{
OwningPtr<MemoryBuffer> BufferPtr;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr))
ErrorMessage = ec.message();
else
M.reset(ParseBitcodeFile(BufferPtr.get(), Context, &ErrorMessage));
}
if (M.get() == 0) {
errs() << argv[0] << ": ";
if (ErrorMessage.size())
errs() << ErrorMessage << "\n";
else
errs() << "bitcode didn't read correctly.\n";
return 1;
}
// Just use stdout. We won't actually print anything on it.
if (DontPrint)
OutputFilename = "-";
if (OutputFilename.empty()) { // Unspecified output, infer it.
if (InputFilename == "-") {
OutputFilename = "-";
} else {
const std::string &IFN = InputFilename;
int Len = IFN.length();
// If the source ends in .bc, strip it off.
if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c')
OutputFilename = std::string(IFN.begin(), IFN.end()-3)+".ll";
else
OutputFilename = IFN+".ll";
}
}
std::string ErrorInfo;
OwningPtr<tool_output_file>
Out(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
raw_fd_ostream::F_Binary));
if (!ErrorInfo.empty()) {
errs() << ErrorInfo << '\n';
return 1;
}
OwningPtr<AssemblyAnnotationWriter> Annotator;
if (ShowAnnotations)
Annotator.reset(new CommentWriter());
// All that llvm-dis does is write the assembly to a file.
if (!DontPrint)
M->print(Out->os(), Annotator.get());
// Declare success.
Out->keep();
return 0;
}