//===- AnalysisWrappers.cpp - Wrappers around non-pass analyses -----------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines pass wrappers around LLVM analyses that don't make sense to
}
void print(std::ostream &OS) const {}
-
+
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
//===- GraphPrinters.cpp - DOT printers for various graph types -----------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines several printers for various different types of graphs used
std::string Filename = GraphName + ".dot";
O << "Writing '" << Filename << "'...";
std::ofstream F(Filename.c_str());
-
+
if (F.good())
WriteGraph(F, GT);
else
static std::string getGraphName(CallGraph *F) {
return "Call Graph";
}
-
+
static std::string getNodeLabel(CallGraphNode *Node, CallGraph *Graph) {
if (Node->getFunction())
return ((Value*)Node->getFunction())->getName();
}
void print(std::ostream &OS) const {}
-
+
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<CallGraph>();
AU.setPreservesAll();
//===- analyze.cpp - The LLVM analyze utility -----------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility is designed to print out the results of running various analysis
-// passes on a program. This is useful for understanding a program, or for
+// passes on a program. This is useful for understanding a program, or for
// debugging an analysis pass.
//
// analyze --help - Output information about command line switches
virtual bool runOnModule(Module &M) {
std::cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
getAnalysisID<Pass>(PassToPrint).print(std::cout, &M);
-
+
// Get and print pass...
return false;
}
-
+
virtual const char *getPassName() const { return "'Pass' Printer"; }
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
// Create a new optimization pass for each one specified on the command line
for (unsigned i = 0; i < AnalysesList.size(); ++i) {
const PassInfo *Analysis = AnalysesList[i];
-
+
if (Analysis->getNormalCtor()) {
Pass *P = Analysis->getNormalCtor()();
Passes.add(P);
//===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This class contains all of the shared state and information that is used by
// otherwise the raw input run through an interpreter is used as the reference
// source.
//
- cl::opt<std::string>
+ cl::opt<std::string>
OutputFile("output", cl::desc("Specify a reference program output "
"(for miscompilation detection)"));
}
//===- BugDriver.h - Top-Level BugPoint class -------------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This class contains all of the shared state and information that is used by
/// reasonable, and figure out exactly which pass is crashing.
///
bool debugOptimizerCrash();
-
+
/// debugCodeGeneratorCrash - This method is called when the code generator
/// crashes on an input. It attempts to reduce the input as much as possible
/// while still causing the code generator to crash.
void switchToInterpreter(AbstractInterpreter *AI) {
Interpreter = AI;
}
-
+
/// setNewProgram - If we reduce or update the program somehow, call this
/// method to update bugdriver with it. This deletes the old module and sets
/// the specified one as the current program.
//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines the bugpoint internals that narrow down compilation crashes
BugDriver &BD;
public:
ReducePassList(BugDriver &bd) : BD(bd) {}
-
+
// doTest - Return true iff running the "removed" passes succeeds, and
// running the "Kept" passes fail when run on the output of the "removed"
// passes. If we return true, we update the current module of bugpoint.
std::cout << "Checking to see if these passes crash: "
<< getPassesString(Suffix) << ": ";
-
+
if (BD.runPasses(Suffix)) {
delete OrigProgram; // The suffix crashes alone...
return KeepSuffix;
ReduceCrashingFunctions(BugDriver &bd,
bool (*testFn)(BugDriver &, Module *))
: BD(bd), TestFn(testFn) {}
-
+
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Kept) {
if (!Kept.empty() && TestFuncs(Kept))
return KeepPrefix;
return NoFailure;
}
-
+
bool TestFuncs(std::vector<Function*> &Prefix);
};
}
bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
// Clone the program to try hacking it apart...
Module *M = CloneModule(BD.getProgram());
-
+
// Convert list to set for fast lookup...
std::set<Function*> Functions;
for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
- Function *CMF = M->getFunction(Funcs[i]->getName(),
+ Function *CMF = M->getFunction(Funcs[i]->getName(),
Funcs[i]->getFunctionType());
assert(CMF && "Function not in module?!");
Functions.insert(CMF);
public:
ReduceCrashingBlocks(BugDriver &bd, bool (*testFn)(BugDriver &, Module *))
: BD(bd), TestFn(testFn) {}
-
+
virtual TestResult doTest(std::vector<const BasicBlock*> &Prefix,
std::vector<const BasicBlock*> &Kept) {
if (!Kept.empty() && TestBlocks(Kept))
return KeepPrefix;
return NoFailure;
}
-
+
bool TestBlocks(std::vector<const BasicBlock*> &Prefix);
};
}
bool ReduceCrashingBlocks::TestBlocks(std::vector<const BasicBlock*> &BBs) {
// Clone the program to try hacking it apart...
Module *M = CloneModule(BD.getProgram());
-
+
// Convert list to set for fast lookup...
std::set<BasicBlock*> Blocks;
for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
// Delete the old terminator instruction...
BB->getInstList().pop_back();
-
+
// Add a new return instruction of the appropriate type...
const Type *RetTy = BB->getParent()->getReturnType();
new ReturnInst(RetTy == Type::VoidTy ? 0 :
I->setLinkage(GlobalValue::ExternalLinkage);
DeletedInit = true;
}
-
+
if (!DeletedInit) {
delete M; // No change made...
} else {
}
}
}
-
+
// Now try to reduce the number of functions in the module to something small.
std::vector<Function*> Functions;
for (Module::iterator I = BD.getProgram()->begin(),
//
unsigned InstructionsToSkipBeforeDeleting = 0;
TryAgain:
-
+
// Loop over all of the (non-terminator) instructions remaining in the
// function, attempting to delete them.
unsigned CurInstructionNum = 0;
} else {
std::cout << "Checking instruction '" << I->getName() << "': ";
Module *M = BD.deleteInstructionFromProgram(I, Simplification);
-
+
// Find out if the pass still crashes on this pass...
if (TestFn(BD, M)) {
// Yup, it does, we delete the old module, and continue trying
InstructionsToSkipBeforeDeleting = CurInstructionNum;
goto TryAgain; // I wish I had a multi-level break here!
}
-
+
// This pass didn't crash without this instruction, try the next
// one.
delete M;
InstructionsToSkipBeforeDeleting = 0;
goto TryAgain;
}
-
+
} while (Simplification);
// Try to clean up the testcase by running funcresolve and globaldce...
std::cout << "\n*** Attempting to perform final cleanups: ";
Module *M = CloneModule(BD.getProgram());
M = BD.performFinalCleanups(M, true);
-
+
// Find out if the pass still crashes on the cleaned up program...
if (TestFn(BD, M)) {
BD.setNewProgram(M); // Yup, it does, keep the reduced version...
if (AnyReduction)
BD.EmitProgressBytecode("reduced-simplified");
- return false;
+ return false;
}
static bool TestForOptimizerCrash(BugDriver &BD, Module *M) {
//===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file contains code used to execute the program utilizing one of the
#endif
std::string SharedObjectFile;
- if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
+ if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
SharedObjectFile))
exit(1);
// If we're checking the program exit code, assume anything nonzero is bad.
if (CheckProgramExitCode && ProgramExitedNonzero) {
Output.destroyFile();
- if (RemoveBytecode)
+ if (RemoveBytecode)
sys::Path(BytecodeFile).destroyFile();
return true;
}
}
FilesDifferent = true;
}
-
+
// Remove the generated output.
Output.destroyFile();
//===- ExtractFunction.cpp - Extract a function from Program --------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file implements several methods that are used to extract functions,
// Make all functions external, so GlobalDCE doesn't delete them...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
I->setLinkage(GlobalValue::ExternalLinkage);
-
+
std::vector<const PassInfo*> CleanupPasses;
CleanupPasses.push_back(getPI(createFunctionResolvingPass()));
CleanupPasses.push_back(getPI(createGlobalDCEPass()));
for (unsigned i = 0, e = M->size(); i != e; ++i)
++MI;
}
-
+
return NewM;
}
for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
ExtractBasicBlock(BlocksToExtract[i]);
-
+
return !BlocksToExtract.empty();
}
//===- ListReducer.h - Trim down list while retaining property --*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This class is to be used as a base class for operations that want to zero in
case KeepPrefix:
if (TheList.size() == 1) // we are done, it's the base case and it fails
return true;
- else
+ else
break; // there's definitely an error, but we need to narrow it down
case KeepSuffix:
Changed = true;
}
}
- // This can take a long time if left uncontrolled. For now, don't
+ // This can take a long time if left uncontrolled. For now, don't
// iterate.
break;
}
//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file implements optimizer and code generation miscompilation debugging
BugDriver &BD;
public:
ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
-
+
virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
std::vector<const PassInfo*> &Suffix);
};
std::string BytecodeResult;
if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
- std::cerr << " Error running this sequence of passes"
+ std::cerr << " Error running this sequence of passes"
<< " on the input program!\n";
BD.setPassesToRun(Suffix);
BD.EmitProgressBytecode("pass-error", false);
// prefix passes, then discard the prefix passes.
//
if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
- std::cerr << " Error running this sequence of passes"
+ std::cerr << " Error running this sequence of passes"
<< " on the input program!\n";
BD.setPassesToRun(Prefix);
BD.EmitProgressBytecode("pass-error", false);
// Don't check if there are no passes in the suffix.
if (Suffix.empty())
return NoFailure;
-
+
std::cout << "Checking to see if '" << getPassesString(Suffix)
<< "' passes compile correctly after the '"
<< getPassesString(Prefix) << "' passes: ";
Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
- std::cerr << " Error running this sequence of passes"
+ std::cerr << " Error running this sequence of passes"
<< " on the input program!\n";
BD.setPassesToRun(Suffix);
BD.EmitProgressBytecode("pass-error", false);
ReduceMiscompilingFunctions(BugDriver &bd,
bool (*F)(BugDriver &, Module *, Module *))
: BD(bd), TestFn(F) {}
-
+
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Suffix) {
if (!Suffix.empty() && TestFuncs(Suffix))
return KeepPrefix;
return NoFailure;
}
-
+
bool TestFuncs(const std::vector<Function*> &Prefix);
};
}
return MadeChange;
}
BD.switchToInterpreter(AI);
-
+
std::cout << " Testing after loop extraction:\n";
// Clone modules, the tester function will free them.
Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
bool (*F)(BugDriver &, Module *, Module *),
const std::vector<Function*> &Fns)
: BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
-
+
virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
std::vector<BasicBlock*> &Suffix) {
if (!Suffix.empty() && TestFuncs(Suffix))
return KeepPrefix;
return NoFailure;
}
-
+
bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
};
}
// Do the reduction...
ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
-
+
std::cout << "\n*** The following function"
<< (MiscompiledFunctions.size() == 1 ? " is" : "s are")
<< " being miscompiled: ";
// Do the reduction...
ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
-
+
std::cout << "\n*** The following function"
<< (MiscompiledFunctions.size() == 1 ? " is" : "s are")
<< " being miscompiled: ";
ToNotOptimize = swapProgramIn(ToNotOptimize);
EmitProgressBytecode("tonotoptimize", true);
setNewProgram(ToNotOptimize); // Delete hacked module.
-
+
std::cout << " Portion that is input to optimizer: ";
ToOptimize = swapProgramIn(ToOptimize);
EmitProgressBytecode("tooptimize");
// Rename it
oldMain->setName("llvm_bugpoint_old_main");
// Create a NEW `main' function with same type in the test module.
- Function *newMain = new Function(oldMain->getFunctionType(),
+ Function *newMain = new Function(oldMain->getFunctionType(),
GlobalValue::ExternalLinkage,
"main", Test);
// Create an `oldmain' prototype in the test module, which will
// corresponds to the real main function in the same module.
- Function *oldMainProto = new Function(oldMain->getFunctionType(),
+ Function *oldMainProto = new Function(oldMain->getFunctionType(),
GlobalValue::ExternalLinkage,
oldMain->getName(), Test);
// Set up and remember the argument list for the main function.
// Call the old main function and return its result
BasicBlock *BB = new BasicBlock("entry", newMain);
CallInst *call = new CallInst(oldMainProto, args, "", BB);
-
+
// If the type of old function wasn't void, return value of call
new ReturnInst(call, BB);
}
// module cannot directly reference any functions defined in the test
// module. Instead, we use a JIT API call to dynamically resolve the
// symbol.
-
+
// Add the resolver to the Safe module.
// Prototype: void *getPointerToNamedFunction(const char* Name)
- Function *resolverFunc =
+ Function *resolverFunc =
Safe->getOrInsertFunction("getPointerToNamedFunction",
PointerType::get(Type::SByteTy),
PointerType::get(Type::SByteTy), 0);
-
+
// Use the function we just added to get addresses of functions we need.
for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
Constant *InitArray = ConstantArray::get(F->getName());
GlobalVariable *funcName =
new GlobalVariable(InitArray->getType(), true /*isConstant*/,
- GlobalValue::InternalLinkage, InitArray,
+ GlobalValue::InternalLinkage, InitArray,
F->getName() + "_name", Safe);
// 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
// Resolve the call to function F via the JIT API:
//
// call resolver(GetElementPtr...)
- CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
+ CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
"resolver");
Header->getInstList().push_back(resolve);
// cast the result from the resolver to correctly-typed function
//===- OptimizerDriver.cpp - Allow BugPoint to run passes safely ----------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines an interface that allows bugpoint to run various passes
std::string BytecodeResult;
if (runPasses(Passes, BytecodeResult, false/*delete*/, true/*quiet*/)) {
if (AutoDebugCrashes) {
- std::cerr << " Error running this sequence of passes"
+ std::cerr << " Error running this sequence of passes"
<< " on the input program!\n";
delete OldProgram;
EmitProgressBytecode("pass-error", false);
//===- TestPasses.cpp - "buggy" passes used to test bugpoint --------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file contains "buggy" passes that are used to test bugpoint, to check
//===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This program is an automated compiler debugger tool. It is used to narrow
//===- extract.cpp - LLVM function extraction utility ---------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility changes the input module to only contain a single function,
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bytecode file>"),
cl::init("-"), cl::value_desc("filename"));
-
+
static cl::opt<std::string>
-OutputFilename("o", cl::desc("Specify output filename"),
+OutputFilename("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
static cl::opt<bool>
Out = new std::ofstream(OutputFilename.c_str(), io_mode);
} else { // Specified stdout
// FIXME: cout is not binary!
- Out = &std::cout;
+ Out = &std::cout;
}
Passes.add(new WriteBytecodePass(Out)); // Write bytecode to file...
//===-- gccas.cpp - The "optimizing assembler" used by the GCC frontend ---===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility is designed to be used by the GCC frontend for creating bytecode
cl::opt<std::string>
InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-"));
- cl::opt<std::string>
+ cl::opt<std::string>
OutputFilename("o", cl::desc("Override output filename"),
cl::value_desc("filename"));
- cl::opt<bool>
+ cl::opt<bool>
Verify("verify", cl::desc("Verify each pass result"));
cl::opt<bool>
StripDebug("strip-debug",
cl::desc("Strip debugger symbol info from translation unit"));
- cl::opt<bool>
+ cl::opt<bool>
NoCompress("disable-compression", cl::init(false),
cl::desc("Don't compress the generated bytecode"));
static inline void addPass(PassManager &PM, Pass *P) {
// Add the pass to the pass manager...
PM.add(P);
-
+
// If we are verifying all of the intermediate steps, add the verifier...
if (Verify) PM.add(createVerifierPass());
}
int main(int argc, char **argv) {
try {
- cl::ParseCommandLineOptions(argc, argv,
+ cl::ParseCommandLineOptions(argc, argv,
" llvm .s -> .o assembler for GCC\n");
sys::PrintStackTraceOnErrorSignal();
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
}
-
+
if (!Out->good()) {
std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
return 1;
//===- GenerateCode.cpp - Functions for generating executable files ------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file contains functions for generating executable files once linking
// Make sure the -L path has a '/' character
// because llvm-g++ passes them without the ending
- // '/' char and sys::Path doesn't think it is a
- // directory (see: sys::Path::isDirectory) without it
+ // '/' char and sys::Path doesn't think it is a
+ // directory (see: sys::Path::isDirectory) without it
std::string dir = LibPath;
if ( dir[dir.length()-1] != '/' )
dir.append("/");
//
// Note:
// When gccld is called from the llvm-gxx frontends, the -L paths for
- // the LLVM cfrontend install paths are appended. We don't want the
+ // the LLVM cfrontend install paths are appended. We don't want the
// native linker to use these -L paths as they contain bytecode files.
// Further, we don't want any -L paths that contain bytecode shared
// libraries or true bytecode archive files. We omit them in all such
args.push_back(LibPaths[index].c_str());
}
}
-
+
// Add in the libraries to link.
for (unsigned index = 0; index < Libraries.size(); index++) {
if (Libraries[index] != "crtend") {
//===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility is intended to be compatible with GCC, and follows standard
using namespace llvm;
namespace {
- cl::list<std::string>
+ cl::list<std::string>
InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
cl::OneOrMore);
- cl::opt<std::string>
+ cl::opt<std::string>
OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
cl::value_desc("filename"));
cl::opt<bool>
Verbose("v", cl::desc("Print information about actions taken"));
- cl::list<std::string>
+ cl::list<std::string>
LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
cl::value_desc("directory"));
- cl::list<std::string>
+ cl::list<std::string>
Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
cl::value_desc("library prefix"));
cl::opt<std::string>
RPath("rpath",
cl::desc("Set runtime shared library search path (requires -native or"
- " -native-cbe)"),
+ " -native-cbe)"),
cl::Prefix, cl::value_desc("directory"));
cl::opt<std::string>
SOName("soname",
cl::desc("Set internal name of shared library (requires -native or"
- " -native-cbe)"),
+ " -native-cbe)"),
cl::Prefix, cl::value_desc("name"));
// Compatibility options that are ignored but supported by LD
// We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
// shared object at all! See RH 8: plain text.
- std::vector<std::string>::iterator libc =
+ std::vector<std::string>::iterator libc =
std::find(Libraries.begin(), Libraries.end(), "c");
if (libc != Libraries.end()) Libraries.erase(libc);
// List all the shared object (native) libraries this executable will need
// on the command line, so that we don't have to do this manually!
- for (std::vector<std::string>::iterator i = Libraries.begin(),
+ for (std::vector<std::string>::iterator i = Libraries.begin(),
e = Libraries.end(); i != e; ++i) {
sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
const cl::list<std::string>& Files,
const cl::list<std::string>& Libraries) {
- // Build the list of linkage items for LinkItems.
+ // Build the list of linkage items for LinkItems.
cl::list<std::string>::const_iterator fileIt = Files.begin();
cl::list<std::string>::const_iterator libIt = Libraries.begin();
// The libraries aren't linked in but are noted as "dependent" in the
// module.
- for (cl::list<std::string>::const_iterator I = Libraries.begin(),
+ for (cl::list<std::string>::const_iterator I = Libraries.begin(),
E = Libraries.end(); I != E ; ++I) {
TheLinker.getModule()->addLibrary(*I);
}
// strip debug info.
int StripLevel = Strip ? 2 : (StripDebug ? 1 : 0);
- // Internalize the module if neither -disable-internalize nor
+ // Internalize the module if neither -disable-internalize nor
// -link-as-library are passed in.
bool ShouldInternalize = !NoInternalize & !LinkAsLibrary;
Out.close();
// Generate either a native file or a JIT shell script. If the user wants
- // to generate a native file, compile it from the bytecode file. Otherwise,
- // if the target is not a library, create a script that will run the
+ // to generate a native file, compile it from the bytecode file. Otherwise,
+ // if the target is not a library, create a script that will run the
// bytecode through the JIT.
if (Native) {
// Name of the Assembly Language output file
// Generate an assembly language file for the bytecode.
if (Verbose) std::cout << "Generating Assembly Code\n";
- GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc,
+ GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc,
Verbose);
if (Verbose) std::cout << "Generating Native Code\n";
- GenerateNative(OutputFilename, AssemblyFile.toString(),
+ GenerateNative(OutputFilename, AssemblyFile.toString(),
LibPaths, Libraries, gcc, envp, LinkAsLibrary, RPath,
SOName, Verbose);
//===- gccld.h - Utility functions header file ------------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file contains function prototypes for the functions in util.cpp.
const sys::Path &llc,
bool Verbose=false);
-int
-GenerateCFile (const std::string &OutputFile,
+int
+GenerateCFile (const std::string &OutputFile,
const std::string &InputFile,
const sys::Path &llc,
bool Verbose=false);
//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
-// command-line interface for generating native assembly-language code
+// command-line interface for generating native assembly-language code
// or C code, given LLVM bytecode.
//
//===----------------------------------------------------------------------===//
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
-//
+//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
MArch("march", cl::desc("Architecture to generate assembly for:"));
-
+
// GetFileNameRoot - Helper function to get the basename of a filename...
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
OutputFilename = "-";
Out = &std::cout;
} else {
- OutputFilename = GetFileNameRoot(InputFilename);
+ OutputFilename = GetFileNameRoot(InputFilename);
if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
OutputFilename += ".s";
else
OutputFilename += ".cbe.c";
-
+
if (!Force && std::ifstream(OutputFilename.c_str())) {
// If force is not specified, make sure not to overwrite a file!
std::cerr << argv[0] << ": error opening '" << OutputFilename
<< "Use -f command line argument to force output\n";
return 1;
}
-
+
Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good()) {
std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
delete Out;
return 1;
}
-
+
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility provides a simple wrapper around the LLVM Execution Engines,
//===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
-// Builds up (relatively) standard unix archive files (.a) containing LLVM
+// Builds up (relatively) standard unix archive files (.a) containing LLVM
// bytecode or other files.
//
//===----------------------------------------------------------------------===//
using namespace llvm;
// Option for compatibility with ASIX, not used but must allow it to be present.
-static cl::opt<bool>
-X32Option ("X32_64", cl::Hidden,
+static cl::opt<bool>
+X32Option ("X32_64", cl::Hidden,
cl::desc("Ignored option for compatibility with AIX"));
// llvm-ar operation code and modifier flags. This must come first.
-static cl::opt<std::string>
+static cl::opt<std::string>
Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
// llvm-ar remaining positional arguments.
-static cl::list<std::string>
-RestOfArgs(cl::Positional, cl::OneOrMore,
+static cl::list<std::string>
+RestOfArgs(cl::Positional, cl::OneOrMore,
cl::desc("[relpos] [count] <archive-file> [members]..."));
// MoreHelp - Provide additional help output explaining the operations and
// modifiers of llvm-ar. This object instructs the CommandLine library
// to print the text of the constructor when the --help option is given.
static cl::extrahelp MoreHelp(
- "\nOPERATIONS:\n"
+ "\nOPERATIONS:\n"
" d[NsS] - delete file(s) from the archive\n"
" m[abiSs] - move file(s) in the archive\n"
" p[kN] - print file(s) found in the archive\n"
// Modifiers to follow operation to vary behavior
bool AddAfter = false; ///< 'a' modifier
bool AddBefore = false; ///< 'b' modifier
-bool Create = false; ///< 'c' modifier
+bool Create = false; ///< 'c' modifier
bool TruncateNames = false; ///< 'f' modifier
bool InsertBefore = false; ///< 'i' modifier
bool DontSkipBytecode = false; ///< 'k' modifier
throw "Expected [relpos] for a, b, or i modifier";
}
-// getCount - Extract the [count] argument associated with the N modifier
+// getCount - Extract the [count] argument associated with the N modifier
// from the command line and check its value.
void getCount() {
if(RestOfArgs.size() > 0) {
// This is just for clarity.
void getMembers() {
if(RestOfArgs.size() > 0)
- Members = std::vector<std::string>(RestOfArgs);
+ Members = std::vector<std::string>(RestOfArgs);
}
// parseCommandLine - Parse the command line options as presented and return the
-// operation specified. Process all modifiers and check to make sure that
+// operation specified. Process all modifiers and check to make sure that
// constraints on modifier/operation pairs have not been violated.
ArchiveOperation parseCommandLine() {
case 'd': ++NumOperations; Operation = Delete; break;
case 'm': ++NumOperations; Operation = Move ; break;
case 'p': ++NumOperations; Operation = Print; break;
- case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
+ case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
case 't': ++NumOperations; Operation = DisplayTable; break;
case 'x': ++NumOperations; Operation = Extract; break;
case 'c': Create = true; break;
NumPositional++;
break;
case 'N':
- getCount();
+ getCount();
UseCount = true;
break;
default:
}
}
- // At this point, the next thing on the command line must be
+ // At this point, the next thing on the command line must be
// the archive name.
getArchive();
if (RecurseDirectories) {
std::set<sys::Path> content;
path.getDirectoryContents(content);
- for (std::set<sys::Path>::iterator I = content.begin(), E = content.end();
+ for (std::set<sys::Path>::iterator I = content.begin(), E = content.end();
I != E; ++I) {
if (I->isDirectory()) {
std::set<sys::Path> moreResults = recurseDirectories(*I);
}
// buildPaths - Convert the strings in the Members vector to sys::Path objects
-// and make sure they are valid and exist exist. This check is only needed for
+// and make sure they are valid and exist exist. This check is only needed for
// the operations that add/replace files to the archive ('q' and 'r')
void buildPaths(bool checkExistence = true) {
for (unsigned i = 0; i < Members.size(); i++) {
void printSymbolTable() {
std::cout << "\nArchive Symbol Table:\n";
const Archive::SymTabType& symtab = TheArchive->getSymbolTable();
- for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
+ for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
I != E; ++I ) {
unsigned offset = TheArchive->getFirstFileOffset() + I->second;
std::cout << " " << std::setw(9) << offset << "\t" << I->first <<"\n";
void doPrint() {
buildPaths(false);
unsigned countDown = Count;
- for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
+ for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
I != E; ++I ) {
- if (Paths.empty() ||
+ if (Paths.empty() ||
(std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
if (countDown == 1) {
const char* data = reinterpret_cast<const char*>(I->getData());
// Skip things that don't make sense to print
- if (I->isLLVMSymbolTable() || I->isSVR4SymbolTable() ||
- I->isBSD4SymbolTable() || (!DontSkipBytecode &&
+ if (I->isLLVMSymbolTable() || I->isSVR4SymbolTable() ||
+ I->isBSD4SymbolTable() || (!DontSkipBytecode &&
(I->isBytecode() || I->isCompressedBytecode())))
continue;
// putMode - utility function for printing out the file mode when the 't'
// operation is in verbose mode.
void printMode(unsigned mode) {
- if (mode & 004)
+ if (mode & 004)
std::cout << "r";
else
std::cout << "-";
// modification time are also printed.
void doDisplayTable() {
buildPaths(false);
- for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
+ for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
I != E; ++I ) {
- if (Paths.empty() ||
+ if (Paths.empty() ||
(std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
if (Verbose) {
// FIXME: Output should be this format:
std::cout << " " << std::setw(4) << I->getUser();
std::cout << "/" << std::setw(4) << I->getGroup();
std::cout << " " << std::setw(8) << I->getSize();
- std::cout << " " << std::setw(20) <<
+ std::cout << " " << std::setw(20) <<
I->getModTime().toString().substr(4);
std::cout << " " << I->getPath().toString() << "\n";
} else {
void doExtract() {
buildPaths(false);
unsigned countDown = Count;
- for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
+ for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
I != E; ++I ) {
if (Paths.empty() ||
(std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
buildPaths(false);
if (Paths.empty()) return;
unsigned countDown = Count;
- for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
+ for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
I != E; ) {
if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) {
if (countDown == 1) {
// the archive to find the member in question. If we don't find it, its no
// crime, we just move to the end.
if (AddBefore || InsertBefore || AddAfter) {
- for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
+ for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
I != E; ++I ) {
if (RelPos == I->getPath().toString()) {
if (AddAfter) {
// Scan the archive again, this time looking for the members to move to the
// moveto_spot.
- for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
+ for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
I != E && !remaining.empty(); ++I ) {
- std::set<sys::Path>::iterator found =
+ std::set<sys::Path>::iterator found =
std::find(remaining.begin(),remaining.end(),I->getPath());
if (found != remaining.end()) {
- if (I != moveto_spot)
+ if (I != moveto_spot)
TheArchive->splice(moveto_spot,*TheArchive,I);
remaining.erase(found);
}
}
// doReplaceOrInsert - Implements the 'r' operation. This function will replace
-// any existing files or insert new ones into the archive.
+// any existing files or insert new ones into the archive.
void doReplaceOrInsert() {
// Build the list of files to be added/replaced.
// to replace.
std::set<sys::Path>::iterator found = remaining.end();
- for (std::set<sys::Path>::iterator RI = remaining.begin(),
+ for (std::set<sys::Path>::iterator RI = remaining.begin(),
RE = remaining.end(); RI != RE; ++RI ) {
std::string compare(RI->toString());
if (TruncateNames && compare.length() > 15) {
nm += slashpos + 1;
len -= slashpos +1;
}
- if (len > 15)
+ if (len > 15)
len = 15;
compare.assign(nm,len);
}
// If we didn't replace all the members, some will remain and need to be
// inserted at the previously computed insert-spot.
if (!remaining.empty()) {
- for (std::set<sys::Path>::iterator PI = remaining.begin(),
+ for (std::set<sys::Path>::iterator PI = remaining.begin(),
PE = remaining.end(); PI != PE; ++PI) {
TheArchive->addFileBefore(*PI,insert_spot);
}
//===--- llvm-as.cpp - The low-level LLVM assembler -----------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
// llvm-as [options] - Read LLVM asm from stdin, write bytecode to stdout
// llvm-as [options] x.ll - Read LLVM asm from the x.ll file, write bytecode
// to the x.bc file.
-//
+//
//===------------------------------------------------------------------------===
#include "llvm/Module.h"
using namespace llvm;
-static cl::opt<std::string>
+static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input .llvm file>"), cl::init("-"));
static cl::opt<std::string>
static cl::opt<bool>
DumpAsm("d", cl::desc("Print assembly as parsed"), cl::Hidden);
-static cl::opt<bool>
+static cl::opt<bool>
NoCompress("disable-compression", cl::init(false),
cl::desc("Don't compress the generated bytecode"));
std::cerr << Err;
return 1;
}
-
+
if (DumpAsm) std::cerr << "Here's the assembly:\n" << *M.get();
if (OutputFilename != "") { // Specified an output filename?
<< "Use -f command line argument to force output\n";
return 1;
}
- Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
+ Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
std::ios::trunc | std::ios::binary);
} else { // Specified stdout
// FIXME: cout is not binary!
return 1;
}
- Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
+ Out = new std::ofstream(OutputFilename.c_str(), std::ios::out |
std::ios::trunc | std::ios::binary);
// Make sure that the Out file gets unlinked from the disk if we get a
// SIGINT
sys::RemoveFileOnSignal(sys::Path(OutputFilename));
}
}
-
+
if (!Out->good()) {
std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
return 1;
}
-
+
if (Force || !CheckBytecodeOutputToConsole(Out,true)) {
WriteBytecodeToFile(M.get(), *Out, !NoCompress);
}
//===-- llvm-bcanalyzer.cpp - Byte Code Analyzer --------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
-// This file was developed by Reid Spencer and is distributed under the
+// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tool may be invoked in the following manner:
//
// Options:
// --help - Output information about command line switches
-// --nodetails - Don't print out detailed informaton about individual
+// --nodetails - Don't print out detailed informaton about individual
// blocks and functions
// --dump - Dump low-level bytecode structure in readable format
//
// This tool provides analytical information about a bytecode file. It is
// intended as an aid to developers of bytecode reading and writing software. It
-// produces on std::out a summary of the bytecode file that shows various
+// produces on std::out a summary of the bytecode file that shows various
// statistics about the contents of the file. By default this information is
// detailed and contains information about individual bytecode blocks and the
-// functions in the module. To avoid this more detailed output, use the
+// functions in the module. To avoid this more detailed output, use the
// -nodetails option to limit the output to just module level information.
-// The tool is also able to print a bytecode file in a straight forward text
-// format that shows the containment and relationships of the information in
-// the bytecode file (-dump option).
+// The tool is also able to print a bytecode file in a straight forward text
+// format that shows the containment and relationships of the information in
+// the bytecode file (-dump option).
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/Verifier.h"
static cl::opt<bool> Dump ("dump", cl::desc("Dump low level bytecode trace"));
static cl::opt<bool> Verify ("verify", cl::desc("Progressively verify module"));
-int
+int
main(int argc, char **argv) {
try {
- cl::ParseCommandLineOptions(argc, argv,
+ cl::ParseCommandLineOptions(argc, argv,
" llvm-bcanalyzer Analysis of ByteCode Dumper\n");
sys::PrintStackTraceOnErrorSignal();
} catch (std::string& errmsg ) {
verificationMsg = errmsg;
}
- if ( verificationMsg.length() > 0 )
+ if ( verificationMsg.length() > 0 )
std::cerr << "Final Verification Message: " << verificationMsg << "\n";
}
std::cerr << argv[0] << ": " << ErrorMessage << "\n";
return 1;
}
-
+
if (Out != &std::cout) {
((std::ofstream*)Out)->close();
//===- CLICommand.h - Classes used to represent commands --------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines a small class hierarchy used to represent the various types
/// removeOptionName - Eliminate one of the names for this option.
///
void removeOptionName(const std::string &Name) {
- unsigned i = 0;
+ unsigned i = 0;
for (; OptionNames[i] != Name; ++i)
assert(i+1 < OptionNames.size() && "Didn't find option name!");
OptionNames.erase(OptionNames.begin()+i);
BuiltinCLICommand(const std::string &ShortHelp, const std::string &LongHelp,
void (CLIDebugger::*impl)(std::string&))
: CLICommand(ShortHelp, LongHelp), Impl(impl) {}
-
+
void runCommand(CLIDebugger &D, std::string &Arguments) {
(D.*Impl)(Arguments);
}
//===-- CLIDebugger.cpp - Command Line Interface to the Debugger ----------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
-//
+//
// This file contains the main implementation of the Command Line Interface to
// the debugger.
//
addCommand("next", C = new BuiltinCLICommand(
"Step program until it reaches a new source line, stepping over calls", "",
&CLIDebugger::nextCommand));
- addCommand("n", C);
+ addCommand("n", C);
addCommand("finish", new BuiltinCLICommand(
"Execute until the selected stack frame returns",
"Print backtrace of all stack frames, or innermost COUNT frames",
"FIXME: describe. Takes 'n', '-n' or 'full'\n",
&CLIDebugger::backtraceCommand));
- addCommand("bt", C);
-
+ addCommand("bt", C);
+
addCommand("up", new BuiltinCLICommand(
"Select and print stack frame that called this one",
"An argument says how many frames up to go.\n",
"With no argument, print the selected stack frame. (See also 'info frame').\n"
"An argument specifies the frame to select.\n",
&CLIDebugger::frameCommand));
- addCommand("f", C);
+ addCommand("f", C);
//===--------------------------------------------------------------------===//
// Breakpoint related commands
"Set breakpoint at specified line or function",
"FIXME: describe.\n",
&CLIDebugger::breakCommand));
- addCommand("b", C);
+ addCommand("b", C);
//===--------------------------------------------------------------------===//
// Look up the command in the table.
std::map<std::string, CLICommand*>::iterator CI =
CommandTable.lower_bound(Command);
-
+
if (Command == "") {
throw "Null command should not get here!";
} else if (CI == CommandTable.end() ||
// If the next command is a valid completion of this one, we are
// ambiguous.
if (++CI2 != CommandTable.end() && isValidPrefix(Command, CI2->first)) {
- std::string ErrorMsg =
+ std::string ErrorMsg =
"Ambiguous command '" + Command + "'. Options: " + CI->first;
for (++CI; CI != CommandTable.end() &&
isValidPrefix(Command, CI->first); ++CI)
try {
CLICommand *CurCommand;
-
+
if (Command == "") {
CurCommand = LastCommand;
Arguments = LastArgs;
// Finally, execute the command.
if (CurCommand)
- CurCommand->runCommand(*this, Arguments);
+ CurCommand->runCommand(*this, Arguments);
} catch (int RetVal) {
// The quit command exits the command loop by throwing an integer return
std::cout << "ERROR: Debugger caught unexpected exception!\n";
// Attempt to continue.
}
-
+
// Write the prompt to get the next bit of user input
std::cout << Prompt;
}
std::cout << "Please answer y or n.\n" << Message << " (y or n) "
<< std::flush;
}
-
+
// Ran out of input?
return false;
}
//===- CLIDebugger.h - LLVM Command Line Interface Debugger -----*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines the CLIDebugger class, which implements a command line
//
std::string Prompt; // set prompt, show prompt
unsigned ListSize; // set listsize, show listsize
-
+
//===------------------------------------------------------------------===//
// Data to support user interaction
//
-
+
/// CurrentFile - The current source file we are inspecting, or null if
/// none.
const SourceFile *CurrentFile;
//===-- Commands.cpp - Implement various commands for the CLI -------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
-//
+//
// This file implements many builtin user commands.
//
//===----------------------------------------------------------------------===//
std::cout << " ->";
}
- std::cout << "\t" << std::string(LineStart, LineEnd) << "\n";
+ std::cout << "\t" << std::string(LineStart, LineEnd) << "\n";
return false;
}
std::cout << getProgramInfo().getFunction(FuncDesc).getSymbolicName();
else
std::cout << "<unknown function>";
-
+
CurrentFile = &FileDesc->getSourceText();
-
+
std::cout << " at " << CurrentFile->getFilename() << ":" << LineNo;
if (ColNo) std::cout << ":" << ColNo;
std::cout << "\n";
std::string Tok = getToken(Val);
if (Tok.empty() || (isOnlyOption && !getToken(Val).empty()))
throw std::string(Msg) + " expects an unsigned integer argument.";
-
+
char *EndPtr;
unsigned Result = strtoul(Tok.c_str(), &EndPtr, 0);
if (EndPtr != Tok.c_str()+Tok.size())
/// getOptionalUnsignedIntegerOption - This method is just like
/// getUnsignedIntegerOption, but if the argument value is not specified, a
/// default is returned instead of causing an error.
-static unsigned
+static unsigned
getOptionalUnsignedIntegerOption(const char *Msg, unsigned Default,
std::string &Val, bool isOnlyOption = true) {
// Check to see if the value was specified...
// FIXME: tokenizing by whitespace is clearly incorrect. Instead we should
// honor quotes and other things that a shell would. Also in the future we
// should support redirection of standard IO.
-
+
std::vector<std::string> Arguments;
for (std::string A = getToken(Options); !A.empty(); A = getToken(Options))
Arguments.push_back(A);
Dbg.setProgramArguments(Arguments.begin(), Arguments.end());
}
-
+
//===----------------------------------------------------------------------===//
// Program startup and shutdown options
// Figure out where the user wants a breakpoint.
const SourceFile *File;
unsigned LineNo;
-
+
// Check to see if the user specified a line specifier.
std::string Option = getToken(Options); // strip whitespace
if (!Option.empty()) {
// Build a line specifier for the current stack frame.
throw "FIXME: breaking at the current location is not implemented yet!";
}
-
+
if (!File) File = CurrentFile;
if (File == 0)
throw "Unknown file to place breakpoint!";
std::cerr << "Break: " << File->getFilename() << ":" << LineNo << "\n";
-
+
throw "breakpoints not implemented yet!";
}
<< SF.getLanguage().getSourceLanguageName() << "\n";
} else if (What == "sources") {
- const std::map<const GlobalVariable*, SourceFileInfo*> &SourceFiles =
+ const std::map<const GlobalVariable*, SourceFileInfo*> &SourceFiles =
getProgramInfo().getSourceFiles();
std::cout << "Source files for the program:\n";
for (std::map<const GlobalVariable*, SourceFileInfo*>::const_iterator I =
std::string Name = getToken(FirstPart);
if (!getToken(FirstPart).empty())
throw "Extra junk in line specifier after '" + Name + "'.";
- SourceFunctionInfo *SFI =
+ SourceFunctionInfo *SFI =
getCurrentLanguage().lookupFunction(Name, getProgramInfo(),
TheRuntimeInfo);
if (SFI == 0)
// Handle "list foo," correctly, by returning " " as the second token
Options += " ";
-
+
std::string FirstLineSpec = getToken(Options, ",");
std::string SecondLineSpec = getToken(Options, ",");
if (!getToken(Options, ",").empty())
}
} else {
- // Parse two line specifiers...
+ // Parse two line specifiers...
const SourceFile *StartFile, *EndFile;
unsigned StartLineNo, EndLineNo;
parseLineSpec(FirstLineSpec, StartFile, StartLineNo);
//===- llvm-db.cpp - LLVM Debugger ----------------------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility implements a simple text-mode front-end to the LLVM debugger
cl::desc("Add directory to the search for source files"));
cl::alias SDA("d", cl::desc("Alias for --directory"),
cl::aliasopt(SourceDirectories));
-
+
cl::opt<std::string>
WorkingDirectory("cd", cl::desc("Use directory as current working directory"),
cl::value_desc("directory"));
Dbg.setWorkingDirectory(WorkingDirectory);
for (unsigned i = 0, e = SourceDirectories.size(); i != e; ++i)
D.addSourceDirectory(SourceDirectories[i]);
-
+
if (!InputArgs.empty()) {
try {
D.fileCommand(InputArgs[0]);
//===-- llvm-dis.cpp - The low-level LLVM disassembler --------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
static cl::opt<std::string>
-OutputFilename("o", cl::desc("Override output filename"),
+OutputFilename("o", cl::desc("Override output filename"),
cl::value_desc("filename"));
static cl::opt<bool>
std::cerr << "bytecode didn't read correctly.\n";
return 1;
}
-
+
if (OutputFilename != "") { // Specified an output filename?
if (OutputFilename != "-") { // Not stdout?
if (!Force && std::ifstream(OutputFilename.c_str())) {
//===- extract.cpp - LLVM function extraction utility ---------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility changes the input module to only contain a single function,
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bytecode file>"),
cl::init("-"), cl::value_desc("filename"));
-
+
static cl::opt<std::string>
-OutputFilename("o", cl::desc("Specify output filename"),
+OutputFilename("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
static cl::opt<bool>
Out = new std::ofstream(OutputFilename.c_str(), io_mode);
} else { // Specified stdout
// FIXME: cout is not binary!
- Out = &std::cout;
+ Out = &std::cout;
}
Passes.add(new WriteBytecodePass(Out)); // Write bytecode to file...
//===- Optimize.cpp - Optimize a complete program -------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
-// This file was developed by Reid Spencer and is distributed under the
+// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file implements all optimization of the linked module for llvm-ld.
)
);
-static cl::opt<bool> DisableInline("disable-inlining",
+static cl::opt<bool> DisableInline("disable-inlining",
cl::desc("Do not run the inliner pass"));
static cl::opt<bool>
static cl::opt<bool> DisableInternalize("disable-internalize",
cl::desc("Do not mark all symbols as internal"));
-static cl::opt<bool> Verify("verify",
+static cl::opt<bool> Verify("verify",
cl::desc("Verify intermediate results of all passes"));
-static cl::opt<bool> Strip("s",
+static cl::opt<bool> Strip("s",
cl::desc("Strip symbol info from executable"));
-static cl::alias ExportDynamic("export-dynamic",
+static cl::alias ExportDynamic("export-dynamic",
cl::aliasopt(DisableInternalize),
cl::desc("Alias for -disable-internalize"));
static inline void addPass(PassManager &PM, Pass *P) {
// Add the pass to the pass manager...
PM.add(P);
-
+
// If we are verifying all of the intermediate steps, add the verifier...
- if (Verify)
+ if (Verify)
PM.add(createVerifierPass());
}
namespace llvm {
-/// Optimize - Perform link time optimizations. This will run the scalar
-/// optimizations, any loaded plugin-optimization modules, and then the
+/// Optimize - Perform link time optimizations. This will run the scalar
+/// optimizations, any loaded plugin-optimization modules, and then the
/// inter-procedural optimizations if applicable.
void Optimize(Module* M) {
PassManager Passes;
// If we're verifying, start off with a verification pass.
- if (Verify)
+ if (Verify)
Passes.add(createVerifierPass());
// Add an appropriate TargetData instance for this module...
}
std::vector<std::string> plugins = LoadableModules;
- for (std::vector<std::string>::iterator I = plugins.begin(),
+ for (std::vector<std::string>::iterator I = plugins.begin(),
E = plugins.end(); I != E; ++I) {
sys::DynamicLibrary dll(I->c_str());
typedef void (*OptimizeFunc)(PassManager&,int);
OptimizeFunc OF = OptimizeFunc(
dll.GetAddressOfSymbol("RunOptimizations"));
if (OF == 0) {
- throw std::string("Optimization Module '") + *I +
+ throw std::string("Optimization Module '") + *I +
"' is missing the RunOptimizations symbol";
}
(*OF)(Passes,OptLevel);
//===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility is intended to be compatible with GCC, and follows standard
cl::desc("<input bytecode files>"));
static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
- cl::desc("Override output filename"),
+ cl::desc("Override output filename"),
cl::value_desc("filename"));
-static cl::opt<bool> Verbose("v",
+static cl::opt<bool> Verbose("v",
cl::desc("Print information about actions taken"));
-
+
static cl::list<std::string> LibPaths("L", cl::Prefix,
- cl::desc("Specify a library search path"),
+ cl::desc("Specify a library search path"),
cl::value_desc("directory"));
static cl::list<std::string> Libraries("l", cl::Prefix,
- cl::desc("Specify libraries to link to"),
+ cl::desc("Specify libraries to link to"),
cl::value_desc("library prefix"));
-static cl::opt<bool> LinkAsLibrary("link-as-library",
+static cl::opt<bool> LinkAsLibrary("link-as-library",
cl::desc("Link the .bc files together as a library, not an executable"));
static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
cl::desc("Disable writing of compressed bytecode files"));
-
+
// Compatibility options that are ignored but supported by LD
-static cl::opt<std::string> CO3("soname", cl::Hidden,
+static cl::opt<std::string> CO3("soname", cl::Hidden,
cl::desc("Compatibility option: ignored"));
-static cl::opt<std::string> CO4("version-script", cl::Hidden,
+static cl::opt<std::string> CO4("version-script", cl::Hidden,
cl::desc("Compatibility option: ignored"));
-static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
+static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
cl::desc("Compatibility option: ignored"));
-static cl::opt<std::string> CO6("h", cl::Hidden,
+static cl::opt<std::string> CO6("h", cl::Hidden,
cl::desc("Compatibility option: ignored"));
/// This is just for convenience so it doesn't have to be passed around
LibPaths.push_back("/usr/X11R6/lib");
// We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
// shared object at all! See RH 8: plain text.
- std::vector<std::string>::iterator libc =
+ std::vector<std::string>::iterator libc =
std::find(Libraries.begin(), Libraries.end(), "c");
if (libc != Libraries.end()) Libraries.erase(libc);
// List all the shared object (native) libraries this executable will need
// on the command line, so that we don't have to do this manually!
- for (std::vector<std::string>::iterator i = Libraries.begin(),
+ for (std::vector<std::string>::iterator i = Libraries.begin(),
e = Libraries.end(); i != e; ++i) {
sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
const cl::list<std::string>& Files,
const cl::list<std::string>& Libraries) {
- // Build the list of linkage items for LinkItems.
+ // Build the list of linkage items for LinkItems.
cl::list<std::string>::const_iterator fileIt = Files.begin();
cl::list<std::string>::const_iterator libIt = Libraries.begin();
// Initial global variable above for convenience printing of program name.
progname = sys::Path(argv[0]).getBasename();
Linker TheLinker(progname, Verbose);
-
+
// Set up the library paths for the Linker
TheLinker.addPaths(LibPaths);
TheLinker.addSystemPaths();
// The libraries aren't linked in but are noted as "dependent" in the
// module.
- for (cl::list<std::string>::const_iterator I = Libraries.begin(),
+ for (cl::list<std::string>::const_iterator I = Libraries.begin(),
E = Libraries.end(); I != E ; ++I) {
TheLinker.getModule()->addLibrary(*I);
}
if (Verbose) std::cout << "Generating Assembly Code\n";
GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
if (Verbose) std::cout << "Generating Native Code\n";
- GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
+ GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
gcc, envp);
// Remove the assembly language file.
} else {
EmitShellScript(argv);
}
-
+
// Make the script executable...
sys::Path(OutputFilename).makeExecutable();
//===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
std::cerr << "\n";
}
} else {
- std::cerr << "Bytecode file: '" << Filename.c_str()
+ std::cerr << "Bytecode file: '" << Filename.c_str()
<< "' does not exist.\n";
}
//===-- llvm-nm.cpp - Symbol table dumping utility for llvm ---------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This program is a utility that works like traditional Unix "nm",
// that is, it prints out the names of symbols in a bytecode file,
// along with some information about each symbol.
-//
+//
// This "nm" does not print symbols' addresses. It supports many of
// the features of GNU "nm", including its different output formats.
//
cl::desc("Specify output format"),
cl::values(clEnumVal(bsd, "BSD format"),
clEnumVal(sysv, "System V format"),
- clEnumVal(posix, "POSIX.2 format"),
+ clEnumVal(posix, "POSIX.2 format"),
clEnumValEnd), cl::init(bsd));
cl::alias OutputFormat2("f", cl::desc("Alias for --format"),
cl::aliasopt(OutputFormat));
- cl::list<std::string>
+ cl::list<std::string>
InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
cl::ZeroOrMore);
//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tools is meant for use with the various LLVM profiling instrumentation
using namespace llvm;
namespace {
- cl::opt<std::string>
+ cl::opt<std::string>
BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"),
cl::Required);
- cl::opt<std::string>
+ cl::opt<std::string>
ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
cl::Optional, cl::init("llvmprof.out"));
// Figure out how many times each successor executed.
std::vector<std::pair<const BasicBlock*, unsigned> > SuccCounts;
const TerminatorInst *TI = BB->getTerminator();
-
+
std::map<ProfileInfoLoader::Edge, unsigned>::iterator I =
EdgeFreqs.lower_bound(std::make_pair(const_cast<BasicBlock*>(BB), 0U));
for (; I != EdgeFreqs.end() && I->first.first == BB; ++I)
unsigned long long TotalExecutions = 0;
for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
TotalExecutions += FunctionCounts[i].second;
-
+
std::cout << "===" << std::string(73, '-') << "===\n"
<< "LLVM profiling output for execution";
if (PI.getNumExecutions() != 1) std::cout << "s";
std::cout << ":\n";
-
+
for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) {
std::cout << " ";
if (e != 1) std::cout << i+1 << ". ";
std::cout << PI.getExecution(i) << "\n";
}
-
+
std::cout << "\n===" << std::string(73, '-') << "===\n";
std::cout << "Function execution frequencies:\n\n";
// Sort by the frequency, backwards.
std::sort(Counts.begin(), Counts.end(),
PairSecondSortReverse<BasicBlock*>());
-
+
std::cout << "\n===" << std::string(73, '-') << "===\n";
std::cout << "Top 20 most frequently executed basic blocks:\n\n";
BlockFreqs.insert(Counts.begin(), Counts.end());
}
-
+
if (PI.hasAccurateEdgeCounts()) {
std::vector<std::pair<ProfileInfoLoader::Edge, unsigned> > Counts;
PI.getEdgeCounts(Counts);
if (PrintAnnotatedLLVM || PrintAllCode) {
std::cout << "\n===" << std::string(73, '-') << "===\n";
std::cout << "Annotated LLVM code for the module:\n\n";
-
+
ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs);
if (FunctionsToPrint.empty() || PrintAllCode)
//===-- llvm-ranlib.cpp - LLVM archive index generator --------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
-// This file was developed by Reid Spencer and is distributed under the
+// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// Adds or updates an index (symbol table) for an LLVM archive file.
using namespace llvm;
// llvm-ar operation code and modifier flags
-static cl::opt<std::string>
+static cl::opt<std::string>
ArchiveName(cl::Positional, cl::Optional, cl::desc("<archive-file>"));
static cl::opt<bool>
void printSymbolTable(Archive* TheArchive) {
std::cout << "\nArchive Symbol Table:\n";
const Archive::SymTabType& symtab = TheArchive->getSymbolTable();
- for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
+ for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
I != E; ++I ) {
unsigned offset = TheArchive->getFirstFileOffset() + I->second;
std::cout << " " << std::setw(9) << offset << "\t" << I->first <<"\n";
throw std::string("Archive file does not exist");
std::string err_msg;
- std::auto_ptr<Archive>
+ std::auto_ptr<Archive>
AutoArchive(Archive::OpenAndLoad(ArchivePath,&err_msg));
Archive* TheArchive = AutoArchive.get();
if (!TheArchive)
//===- CompilerDriver.cpp - The LLVM Compiler Driver ------------*- C++ -*-===//
//
-//
+//
// The LLVM Compiler Infrastructure
//
-// This file was developed by Reid Spencer and is distributed under the
+// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file implements the bulk of the LLVM Compiler Driver (llvmc).
}
void DumpConfigData(CompilerDriver::ConfigData* cd, const std::string& type ){
- std::cerr << "Configuration Data For '" << cd->langName << "' (" << type
+ std::cerr << "Configuration Data For '" << cd->langName << "' (" << type
<< ")\n";
std::cerr << "PreProcessor: ";
DumpAction(&cd->PreProcessor);
/// This specifies the passes to run for OPT_FAST_COMPILE (-O1)
/// which should reduce the volume of code and make compilation
-/// faster. This is also safe on any llvm module.
+/// faster. This is also safe on any llvm module.
static const char* DefaultFastCompileOptimizations[] = {
"-simplifycfg", "-mem2reg", "-instcombine"
};
CompilerDriverImpl(ConfigDataProvider& confDatProv )
: cdp(&confDatProv)
, finalPhase(LINKING)
- , optLevel(OPT_FAST_COMPILE)
+ , optLevel(OPT_FAST_COMPILE)
, Flags(0)
, machine()
, LibraryPaths()
/// @name Methods
/// @{
public:
- virtual void setFinalPhase( Phases phase ) {
- finalPhase = phase;
+ virtual void setFinalPhase( Phases phase ) {
+ finalPhase = phase;
}
- virtual void setOptimization( OptimizationLevels level ) {
- optLevel = level;
+ virtual void setOptimization( OptimizationLevels level ) {
+ optLevel = level;
}
virtual void setDriverFlags( unsigned flags ) {
- Flags = flags & DRIVER_FLAGS_MASK;
+ Flags = flags & DRIVER_FLAGS_MASK;
}
virtual void setOutputMachine( const std::string& machineName ) {
}
}
- sys::Path MakeTempFile(const std::string& basename,
+ sys::Path MakeTempFile(const std::string& basename,
const std::string& suffix ) {
sys::Path result(TempDir);
if (!result.appendFile(basename))
return result;
}
- Action* GetAction(ConfigData* cd,
- const sys::Path& input,
+ Action* GetAction(ConfigData* cd,
+ const sys::Path& input,
const sys::Path& output,
Phases phase)
{
// Get specific options for each kind of action type
StringVector& addargs = AdditionalArgs[phase];
// Add specific options for each kind of action type
- action->args.insert(action->args.end(), addargs.begin(),
+ action->args.insert(action->args.end(), addargs.begin(),
addargs.end());
}
} else
case 'f':
if (*PI == "%fOpts%") {
if (!fOptions.empty())
- action->args.insert(action->args.end(), fOptions.begin(),
+ action->args.insert(action->args.end(), fOptions.begin(),
fOptions.end());
} else
found = false;
action->args.push_back(output.toString());
} else if (*PI == "%opt%") {
if (!isSet(EMIT_RAW_FLAG)) {
- if (cd->opts.size() > static_cast<unsigned>(optLevel) &&
+ if (cd->opts.size() > static_cast<unsigned>(optLevel) &&
!cd->opts[optLevel].empty())
- action->args.insert(action->args.end(),
+ action->args.insert(action->args.end(),
cd->opts[optLevel].begin(),
cd->opts[optLevel].end());
else
- throw std::string("Optimization options for level ") +
+ throw std::string("Optimization options for level ") +
utostr(unsigned(optLevel)) + " were not specified";
}
} else
case 'M':
if (*PI == "%Mopts%") {
if (!MOptions.empty())
- action->args.insert(action->args.end(), MOptions.begin(),
+ action->args.insert(action->args.end(), MOptions.begin(),
MOptions.end());
} else
found = false;
}
if (!found) {
// Did it even look like a substitution?
- if (PI->length()>1 && (*PI)[0] == '%' &&
+ if (PI->length()>1 && (*PI)[0] == '%' &&
(*PI)[PI->length()-1] == '%') {
throw std::string("Invalid substitution token: '") + *PI +
"' for command '" + pat->program.toString() + "'";
"' is not executable.");
// Invoke the program
- const char** Args = (const char**)
+ const char** Args = (const char**)
alloca(sizeof(const char*)*(action->args.size()+2));
Args[0] = action->program.toString().c_str();
for (unsigned i = 1; i != action->args.size(); ++i)
fullpath.setFile(link_item);
if (fullpath.readable())
return fullpath;
- for (PathVector::iterator PI = LibraryPaths.begin(),
+ for (PathVector::iterator PI = LibraryPaths.begin(),
PE = LibraryPaths.end(); PI != PE; ++PI) {
fullpath.setDirectory(PI->toString());
fullpath.appendFile(link_item);
fullpath.appendSuffix("a");
} else {
fullpath.appendSuffix("bc");
- if (fullpath.readable())
+ if (fullpath.readable())
return fullpath;
fullpath.elideSuffix();
fullpath.appendSuffix("o");
- if (fullpath.readable())
+ if (fullpath.readable())
return fullpath;
fullpath = *PI;
fullpath.appendFile(std::string("lib") + link_item);
// If we didn't find the file in any of the library search paths
// we have to bail. No where else to look.
if (fullpath.isEmpty()) {
- err =
+ err =
std::string("Can't find linkage item '") + link_item.toString() + "'";
return false;
}
while ( LI != LE ) {
if (!ProcessLinkageItem(sys::Path(*LI),set,err)) {
if (err.empty()) {
- err = std::string("Library '") + *LI +
+ err = std::string("Library '") + *LI +
"' is not valid for linking but is required by file '" +
fullpath.toString() + "'";
} else {
}
} else if (err.empty()) {
err = std::string(
- "The dependent libraries could not be extracted from '") +
+ "The dependent libraries could not be extracted from '") +
fullpath.toString();
return false;
}
std::cerr << "OutputMachine = " << machine << "\n";
InputList::const_iterator I = InpList.begin();
while ( I != InpList.end() ) {
- std::cerr << "Input: " << I->first << "(" << I->second
+ std::cerr << "Input: " << I->first << "(" << I->second
<< ")\n";
++I;
}
// Get the suffix of the file name
const std::string& ftype = I->second;
- // If its a library, bytecode file, or object file, save
- // it for linking below and short circuit the
+ // If its a library, bytecode file, or object file, save
+ // it for linking below and short circuit the
// pre-processing/translation/assembly phases
if (ftype.empty() || ftype == "o" || ftype == "bc" || ftype=="a") {
- // We shouldn't get any of these types of files unless we're
+ // We shouldn't get any of these types of files unless we're
// later going to link. Enforce this limit now.
if (finalPhase != LINKING) {
throw std::string(
// for this kind of file.
ConfigData* cd = cdp->ProvideConfigData(I->second);
if (cd == 0)
- throw std::string("Files of type '") + I->second +
- "' are not recognized.";
+ throw std::string("Files of type '") + I->second +
+ "' are not recognized.";
if (isSet(DEBUG_FLAG))
DumpConfigData(cd,I->second);
} else if (finalPhase == PREPROCESSING) {
throw cd->langName + " does not support pre-processing";
} else if (action.isSet(REQUIRED_FLAG)) {
- throw std::string("Don't know how to pre-process ") +
+ throw std::string("Don't know how to pre-process ") +
cd->langName + " files";
}
- // Short-circuit remaining actions if all they want is
+ // Short-circuit remaining actions if all they want is
// pre-processing
if (finalPhase == PREPROCESSING) { continue; };
actions.push_back(GetAction(cd,InFile,Output,TRANSLATION));
}
} else {
- sys::Path TempFile(MakeTempFile(I->first.getBasename(),"trans"));
+ sys::Path TempFile(MakeTempFile(I->first.getBasename(),"trans"));
actions.push_back(GetAction(cd,InFile,TempFile,TRANSLATION));
InFile = TempFile;
}
} else if (finalPhase == TRANSLATION) {
throw cd->langName + " does not support translation";
} else if (action.isSet(REQUIRED_FLAG)) {
- throw std::string("Don't know how to translate ") +
+ throw std::string("Don't know how to translate ") +
cd->langName + " files";
}
} else if (finalPhase == OPTIMIZATION) {
throw cd->langName + " does not support optimization";
} else if (action.isSet(REQUIRED_FLAG)) {
- throw std::string("Don't know how to optimize ") +
+ throw std::string("Don't know how to optimize ") +
cd->langName + " files";
}
}
// Put the action on the list
actions.push_back(action);
- // Short circuit the rest of the loop, we don't want to link
+ // Short circuit the rest of the loop, we don't want to link
continue;
}
// Add in all the linkage items we generated. This includes the
// output from the translation/optimization phases as well as any
// -l arguments specified.
- for (PathVector::const_iterator I=LinkageItems.begin(),
+ for (PathVector::const_iterator I=LinkageItems.begin(),
E=LinkageItems.end(); I != E; ++I )
link->args.push_back(I->toString());
//===- CompilerDriver.h - Compiler Driver -----------------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
-// This file was developed by Reid Spencer and is distributed under the
+// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file declares the CompilerDriver class which implements the bulk of the
/// The driver's purpose is to make it easier for compiler writers and users
/// of LLVM to utilize the compiler toolkits and LLVM toolset by learning only
/// the interface of one program (llvmc).
- ///
+ ///
/// @see llvmc.cpp
/// @brief The interface to the LLVM Compiler Driver.
class CompilerDriver {
enum Phases {
PREPROCESSING, ///< Source language combining, filtering, substitution
TRANSLATION, ///< Translate source -> LLVM bytecode/assembly
- OPTIMIZATION, ///< Optimize translation result
+ OPTIMIZATION, ///< Optimize translation result
ASSEMBLY, ///< Convert program to executable
LINKING, ///< Link bytecode and native code
NUM_PHASES ///< Always last!
struct ConfigData {
ConfigData();
std::string version; ///< The version number.
- std::string langName; ///< The name of the source language
+ std::string langName; ///< The name of the source language
StringTable opts; ///< The o10n options for each level
StringVector libpaths; ///< The library paths
Action PreProcessor; ///< PreProcessor command line
/// This pure virtual interface class defines the interface between the
/// CompilerDriver and other software that provides ConfigData objects to
/// it. The CompilerDriver must be configured to use an object of this
- /// type so it can obtain the configuration data.
+ /// type so it can obtain the configuration data.
/// @see setConfigDataProvider
/// @brief Configuration Data Provider interface
class ConfigDataProvider {
/// These flags control various actions of the compiler driver. They are
/// used by adding the needed flag values together and passing them to the
- /// compiler driver's setDriverFlags method.
+ /// compiler driver's setDriverFlags method.
/// @see setDriverFlags
/// @brief Driver specific flags
enum DriverFlags {
virtual void setOutputMachine(const std::string& machineName) = 0;
/// @brief Set the options for a given phase.
- virtual void setPhaseArgs(Phases phase, const StringVector& opts) = 0;
+ virtual void setPhaseArgs(Phases phase, const StringVector& opts) = 0;
/// @brief Set Library Paths
virtual void setIncludePaths(const StringVector& paths) = 0;
//===- ConfigLexer.h - ConfigLexer Declarations -----------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
-// This file was developed by Reid Spencer and is distributed under the
+// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file declares the types and data needed by ConfigLexer.l
}
virtual ~InputProvider();
virtual unsigned read(char *buf, unsigned max_size) = 0;
- virtual void error(const std::string& msg);
+ virtual void error(const std::string& msg);
virtual void checkErrors();
private:
FOPTS_SUBST, ///< The substitution item %fOpts%
IN_SUBST, ///< The substitution item %in%
INCLS_SUBST, ///< The substitution item %incls%
- INTEGER, ///< An integer
+ INTEGER, ///< An integer
LANG, ///< The name "lang" (and variants)
LIBPATHS, ///< The name "libpaths" (and variants)
LIBS, ///< The name "libs" (and variants)
//===- Configuration.cpp - Configuration Data Mgmt --------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
-// This file was developed by Reid Spencer and is distributed under the
+// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file implements the parsing of configuration files for the LLVM Compiler
InputProvider::~InputProvider() {}
void InputProvider::error(const std::string& msg) {
- std::cerr << name << ":" << ConfigLexerState.lineNum << ": Error: " <<
+ std::cerr << name << ":" << ConfigLexerState.lineNum << ": Error: " <<
msg << "\n";
errCount++;
}
class FileInputProvider : public InputProvider {
public:
FileInputProvider(const std::string & fname)
- : InputProvider(fname)
+ : InputProvider(fname)
, F(fname.c_str()) {
ConfigLexerInput = this;
}
std::ifstream F;
};
- cl::opt<bool> DumpTokens("dump-tokens", cl::Optional, cl::Hidden,
+ cl::opt<bool> DumpTokens("dump-tokens", cl::Optional, cl::Hidden,
cl::init(false), cl::desc("Dump lexical tokens (debug use only)."));
struct Parser
InputProvider* provider;
CompilerDriver::ConfigData* confDat;
- inline int next() {
+ inline int next() {
token = Configlex();
- if (DumpTokens)
+ if (DumpTokens)
std::cerr << token << "\n";
return token;
}
- inline bool next_is_real() {
+ inline bool next_is_real() {
next();
return (token != EOLTOK) && (token != ERRORTOK) && (token != 0);
}
while (next_is_real()) {
switch (token ) {
case STRING :
- case OPTION :
+ case OPTION :
result += ConfigLexerState.StringVal;
break;
case SEPARATOR:
case LIBS:
parseLibs();
break;
- case NAME:
- confDat->langName = parseName();
+ case NAME:
+ confDat->langName = parseName();
break;
- case OPT1:
- parseOptionList(confDat->opts[CompilerDriver::OPT_FAST_COMPILE]);
+ case OPT1:
+ parseOptionList(confDat->opts[CompilerDriver::OPT_FAST_COMPILE]);
break;
- case OPT2:
- parseOptionList(confDat->opts[CompilerDriver::OPT_SIMPLE]);
+ case OPT2:
+ parseOptionList(confDat->opts[CompilerDriver::OPT_SIMPLE]);
break;
- case OPT3:
- parseOptionList(confDat->opts[CompilerDriver::OPT_AGGRESSIVE]);
+ case OPT3:
+ parseOptionList(confDat->opts[CompilerDriver::OPT_AGGRESSIVE]);
break;
- case OPT4:
- parseOptionList(confDat->opts[CompilerDriver::OPT_LINK_TIME]);
+ case OPT4:
+ parseOptionList(confDat->opts[CompilerDriver::OPT_LINK_TIME]);
break;
- case OPT5:
+ case OPT5:
parseOptionList(
confDat->opts[CompilerDriver::OPT_AGGRESSIVE_LINK_TIME]);
break;
- default:
- error("Expecting 'name' or 'optN' after 'lang.'");
+ default:
+ error("Expecting 'name' or 'optN' after 'lang.'");
break;
}
}
break;
}
next();
- } while (token != SPACE && token != EOFTOK && token != EOLTOK &&
+ } while (token != SPACE && token != EOFTOK && token != EOLTOK &&
token != ERRORTOK);
return !str.empty();
}
case SPACE:
next();
/* FALL THROUGH */
- default:
+ default:
{
std::string progname;
if (parseProgramName(progname))
if (next() != SEPARATOR)
error("Expecting '.'");
switch (next()) {
- case COMMAND:
+ case COMMAND:
parseCommand(confDat->Translator);
break;
case REQUIRED:
case PREPROCESSES:
if (parseBoolean())
confDat->Translator.set(CompilerDriver::PREPROCESSES_FLAG);
- else
+ else
confDat->Translator.clear(CompilerDriver::PREPROCESSES_FLAG);
break;
case OUTPUT:
confDat->Translator.clear(CompilerDriver::OUTPUT_IS_ASM_FLAG);
break;
default:
- error(std::string("Expecting 'command', 'preprocesses', "
- "'translates' or 'output' but found '") +
+ error(std::string("Expecting 'command', 'preprocesses', "
+ "'translates' or 'output' but found '") +
ConfigLexerState.StringVal + "' instead");
break;
}
case LINKER: parseLinker(); break;
case EOLTOK: break; // just ignore
case ERRORTOK:
- default:
+ default:
error("Invalid top level configuration item");
break;
}
confFile.setDirectory(conf);
confFile.appendFile(ftype);
if (!confFile.readable())
- throw std::string("Configuration file for '") + ftype +
+ throw std::string("Configuration file for '") + ftype +
"' is not available.";
} else {
// Try the user's home directory
confFile = sys::Path::GetLLVMDefaultConfigDir();
confFile.appendFile(ftype);
if (!confFile.readable()) {
- throw std::string("Configuration file for '") + ftype +
+ throw std::string("Configuration file for '") + ftype +
"' is not available.";
}
}
confFile = configDir;
confFile.appendFile(ftype);
if (!confFile.readable())
- throw std::string("Configuration file for '") + ftype +
+ throw std::string("Configuration file for '") + ftype +
"' is not available.";
}
FileInputProvider fip( confFile.toString() );
if (!fip.okay()) {
- throw std::string("Configuration file for '") + ftype +
+ throw std::string("Configuration file for '") + ftype +
"' is not available.";
}
result = new CompilerDriver::ConfigData();
Configurations.clear();
}
-CompilerDriver::ConfigData*
+CompilerDriver::ConfigData*
LLVMC_ConfigDataProvider::ProvideConfigData(const std::string& filetype) {
CompilerDriver::ConfigData* result = 0;
if (!Configurations.empty()) {
//===- Configuration.h - Configuration Data Mgmt ----------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
-// This file was developed by Reid Spencer and is distributed under the
+// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file declares the LLVMC_ConfigDataProvider class which implements the
/// The driver's purpose is to make it easier for compiler writers and users
/// of LLVM to utilize the compiler toolkits and LLVM toolset by learning only
/// the interface of one program (llvmc).
- ///
+ ///
/// @see llvmc.cpp
/// @brief The interface to the LLVM Compiler Driver.
class LLVMC_ConfigDataProvider : public CompilerDriver::ConfigDataProvider {
/// @{
public:
/// @brief Provide the configuration data to the CompilerDriver.
- virtual CompilerDriver::ConfigData*
+ virtual CompilerDriver::ConfigData*
ProvideConfigData(const std::string& filetype);
/// @brief Allow the configuration directory to be set
- virtual void setConfigDir(const sys::Path& dirName) {
- configDir = dirName;
+ virtual void setConfigDir(const sys::Path& dirName) {
+ configDir = dirName;
}
private:
//===--- llvmc.cpp - The LLVM Compiler Driver -------------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tool provides a single point of access to the LLVM compilation tools.
// It has many options. To discover the options supported please refer to the
// tools' manual page (docs/CommandGuide/html/llvmc.html) or run the tool with
// the --help option.
-//
+//
//===------------------------------------------------------------------------===
#include "CompilerDriver.h"
//=== PHASE OPTIONS
//===------------------------------------------------------------------------===
cl::opt<CompilerDriver::Phases> FinalPhase(cl::Optional,
- cl::desc("Choose final phase of compilation:"),
+ cl::desc("Choose final phase of compilation:"),
cl::init(CompilerDriver::LINKING),
cl::values(
clEnumValN(CompilerDriver::PREPROCESSING,"E",
//===------------------------------------------------------------------------===
cl::list<std::string> PreprocessorToolOpts("Tpre", cl::ZeroOrMore,
- cl::desc("Pass specific options to the pre-processor"),
+ cl::desc("Pass specific options to the pre-processor"),
cl::value_desc("option"));
cl::alias PreprocessorToolOptsAlias("Wp,", cl::ZeroOrMore,
cl::desc("Pass through -W options to compiler tools"),
cl::value_desc("option"));
-cl::list<std::string> BOpt("B", cl::ZeroOrMore, cl::Prefix,
+cl::list<std::string> BOpt("B", cl::ZeroOrMore, cl::Prefix,
cl::desc("Specify path to find llvmc sub-tools"),
cl::value_desc("dir"));
cl::desc("Specify base name of libraries to link to"), cl::value_desc("lib"));
cl::list<std::string> Includes("I", cl::Prefix,
- cl::desc("Specify location to search for included source"),
+ cl::desc("Specify location to search for included source"),
cl::value_desc("dir"));
cl::list<std::string> Defines("D", cl::Prefix,
//=== OUTPUT OPTIONS
//===------------------------------------------------------------------------===
-cl::opt<std::string> OutputFilename("o",
+cl::opt<std::string> OutputFilename("o",
cl::desc("Override output filename"), cl::value_desc("file"));
cl::opt<std::string> OutputMachine("m", cl::Prefix,
cl::opt<bool> Verbose("verbose", cl::Optional, cl::init(false),
cl::desc("Print out each action taken"));
-cl::alias VerboseAlias("v", cl::Optional,
+cl::alias VerboseAlias("v", cl::Optional,
cl::desc("Alias for -verbose"), cl::aliasopt(Verbose));
-cl::opt<bool> Debug("debug", cl::Optional, cl::init(false),
+cl::opt<bool> Debug("debug", cl::Optional, cl::init(false),
cl::Hidden, cl::desc("Print out debugging information"));
cl::alias DebugAlias("d", cl::Optional,
try {
// Parse the command line options
- cl::ParseCommandLineOptions(argc, argv,
+ cl::ParseCommandLineOptions(argc, argv,
" LLVM Compiler Driver (llvmc)\n\n"
" This program provides easy invocation of the LLVM tool set\n"
" and other compiler tools.\n"
//===- AnalysisWrappers.cpp - Wrappers around non-pass analyses -----------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines pass wrappers around LLVM analyses that don't make sense to
}
void print(std::ostream &OS) const {}
-
+
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
//===- GraphPrinters.cpp - DOT printers for various graph types -----------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines several printers for various different types of graphs used
std::string Filename = GraphName + ".dot";
O << "Writing '" << Filename << "'...";
std::ofstream F(Filename.c_str());
-
+
if (F.good())
WriteGraph(F, GT);
else
static std::string getGraphName(CallGraph *F) {
return "Call Graph";
}
-
+
static std::string getNodeLabel(CallGraphNode *Node, CallGraph *Graph) {
if (Node->getFunction())
return ((Value*)Node->getFunction())->getName();
}
void print(std::ostream &OS) const {}
-
+
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<CallGraph>();
AU.setPreservesAll();
//===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// Optimizations may be specified an arbitrary number of times on the command
// Create a new optimization pass for each one specified on the command line
for (unsigned i = 0; i < OptimizationList.size(); ++i) {
const PassInfo *Opt = OptimizationList[i];
-
+
if (Opt->getNormalCtor())
Passes.add(Opt->getNormalCtor()());
else if (Opt->getTargetCtor()) {
//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is emits an assembly printer for the current target.
struct AsmWriterInst {
std::vector<AsmWriterOperand> Operands;
const CodeGenInstruction *CGI;
-
+
AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
/// MatchesAllButOneOp - If this instruction is exactly identical to the
if (Operands[i] != Other.Operands[i])
if (MismatchOperand != ~0U) // Already have one mismatch?
return ~1U;
- else
+ else
MismatchOperand = i;
}
return MismatchOperand;
OpsToPrint.push_back(std::make_pair(Namespace+"::"+
FirstInst.CGI->TheDef->getName(),
FirstInst.Operands[i]));
-
+
for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
AsmWriterInst &AWI = SimilarInsts[si];
OpsToPrint.push_back(std::make_pair(Namespace+"::"+
// If all of the instructions start with a constant string (a very very common
// occurance), emit all of the constant strings as a big table lookup instead
- // of requiring a switch for them.
+ // of requiring a switch for them.
bool AllStartWithString = true;
for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
AllStartWithString = false;
break;
}
-
+
if (AllStartWithString) {
// Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
// all machine instructions are necessarily being printed, so there may be
O << " switch (MI->getOpcode()) {\n"
" default: return false;\n";
-
+
while (!Instructions.empty())
EmitInstructions(Instructions, O);
//===- AsmWriterEmitter.h - Generate an assembly writer ---------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting an assembly printer for the
RecordKeeper &Records;
public:
AsmWriterEmitter(RecordKeeper &R) : Records(R) {}
-
+
// run - Output the asmwriter, returning true on failure.
void run(std::ostream &o);
};
//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// CodeEmitterGen uses the descriptions of instructions and their fields to
}
BI = NewBI;
}
-
+
unsigned Value = 0;
const std::vector<RecordVal> &Vals = R->getValues();
DEBUG(o << " // " << *R->getValue("Inst") << "\n");
o << " Value = " << Value << "U;\n\n";
-
+
// Loop over all of the fields in the instruction, determining which are the
- // operands to the instruction.
+ // operands to the instruction.
unsigned op = 0;
std::map<std::string, unsigned> OpOrder;
std::map<std::string, bool> OpContinuous;
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
// Is the operand continuous? If so, we can just mask and OR it in
- // instead of doing it bit-by-bit, saving a lot in runtime cost.
+ // instead of doing it bit-by-bit, saving a lot in runtime cost.
BitsInit *InstInit = BI;
int beginBitInVar = -1, endBitInVar = -1;
int beginBitInInst = -1, endBitInInst = -1;
// this is not an operand!!
if (beginBitInInst != -1) {
o << " // op" << op << ": " << Vals[i].getName() << "\n"
- << " int64_t op" << op
+ << " int64_t op" << op
<<" = getMachineOpValue(MI, MI.getOperand("<<op<<"));\n";
//<< " MachineOperand &op" << op <<" = MI.getOperand("<<op<<");\n";
OpOrder[Vals[i].getName()] = op++;
-
- DEBUG(o << " // Var: begin = " << beginBitInVar
+
+ DEBUG(o << " // Var: begin = " << beginBitInVar
<< ", end = " << endBitInVar
<< "; Inst: begin = " << beginBitInInst
<< ", end = " << endBitInInst << "\n");
-
+
if (continuous) {
DEBUG(o << " // continuous: op" << OpOrder[Vals[i].getName()]
<< "\n");
-
+
// Mask off the right bits
// Low mask (ie. shift, if necessary)
assert(endBitInVar >= 0 && "Negative shift amount in masking!");
beginBitInVar -= endBitInVar;
endBitInVar = 0;
}
-
+
// High mask
o << " op" << OpOrder[Vals[i].getName()]
<< " &= (1<<" << beginBitInVar+1 << ") - 1;\n";
-
+
// Shift the value to the correct place (according to place in inst)
assert(endBitInInst >= 0 && "Negative shift amount!");
if (endBitInInst != 0)
o << " op" << OpOrder[Vals[i].getName()]
<< " <<= " << endBitInInst << ";\n";
-
+
// Just OR in the result
o << " Value |= op" << OpOrder[Vals[i].getName()] << ";\n";
}
-
+
// otherwise, will be taken care of in the loop below using this
// value:
OpContinuous[Vals[i].getName()] = continuous;
//===- CodeEmitterGen.h - Code Emitter Generator ----------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// FIXME: document
RecordKeeper &Records;
public:
CodeEmitterGen(RecordKeeper &R) : Records(R) {}
-
+
// run - Output the code emitter
void run(std::ostream &o);
private:
//===- CodeGenInstruction.h - Instruction Class Wrapper ---------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines a wrapper class for the 'Instruction' TableGen class.
const std::string &PMN, unsigned MION)
: Rec(R), Ty(T), Name(N), PrinterMethodName(PMN), MIOperandNo(MION) {}
};
-
+
/// OperandList - The list of declared operands, along with their declared
/// type (which is a record).
std::vector<OperandInfo> OperandList;
//===- CodeGenRegisters.h - Register and RegisterClass Info -----*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines structures to encapsulate information gleaned from the
//===- CodeGenTarget.cpp - CodeGen Target Class Wrapper ---------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This class wrap target description classes used by the various code
CodeGenTarget::CodeGenTarget() : PointerType(MVT::Other) {
std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
if (Targets.size() == 0)
- throw std::string("ERROR: No 'Target' subclasses defined!");
+ throw std::string("ERROR: No 'Target' subclasses defined!");
if (Targets.size() != 1)
throw std::string("ERROR: Multiple subclasses of Target defined!");
TargetRec = Targets[0];
ListInit *RegList = R->getValueAsListInit("MemberList");
for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {
DefInit *RegDef = dynamic_cast<DefInit*>(RegList->getElement(i));
- if (!RegDef) throw "Register class member is not a record!";
+ if (!RegDef) throw "Register class member is not a record!";
Record *Reg = RegDef->getDef();
if (!Reg->isSubClassOf("Register"))
} else
throw "Unknown operand class '" + Rec->getName() +
"' in instruction '" + R->getName() + "' instruction!";
-
+
OperandList.push_back(OperandInfo(Rec, Ty, DI->getArgName(i),
PrintMethod, MIOperandNo));
MIOperandNo += NumOps;
//===- CodeGenTarget.h - Target Class Wrapper -------------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines wrappers for the Target class and related global
//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
LI = Inst.TheDef->getValueAsListInit("Uses");
if (!LI->getSize())
OS << "EmptyImpUses, ";
- else
+ else
OS << Inst.TheDef->getName() << "ImpUses, ";
LI = Inst.TheDef->getValueAsListInit("Defs");
if (!LI->getSize())
OS << "EmptyImpDefs ";
- else
+ else
OS << Inst.TheDef->getName() << "ImpDefs ";
OS << " }, // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
//===- InstrInfoEmitter.h - Generate a Instruction Set Desc. ----*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
RecordKeeper &Records;
public:
InstrInfoEmitter(RecordKeeper &R) : Records(R) {}
-
+
// run - Output the instruction set description, returning true on failure.
void run(std::ostream &OS);
//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
getChild(i)->InstantiateNonterminals(ISE);
return;
}
-
+
// If this is a leaf, it might be a reference to a nonterminal! Check now.
Record *R = getValueRecord();
if (R->isSubClassOf("Nonterminal")) {
// We found an unresolved nonterminal reference. Ask the ISE to clone
// it for us, then update our reference to the fresh, new, resolved,
// nonterminal.
-
+
Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
}
}
return OS << N.getType() << ":" << *N.getValue();
OS << "(" << N.getType() << ":";
OS << N.getOperator()->getName();
-
+
if (N.getNumChildren() != 0) {
OS << " " << *N.getChild(0);
for (unsigned i = 1, e = N.getNumChildren(); i != e; ++i)
OS << ", " << *N.getChild(i);
- }
+ }
return OS << ")";
}
case Instruction: M += "instruction "; break;
case Expander : M += "expander "; break;
}
- throw M + TheRecord->getName() + ": " + Msg;
+ throw M + TheRecord->getName() + ": " + Msg;
}
/// calculateArgs - Compute the list of all of the arguments to this pattern,
// node.
if (Dag->getNumArgs() != 1)
error("Type cast only valid for a leaf node!");
-
+
Init *Arg = Dag->getArg(0);
TreePatternNode *New;
if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
error("Unrecognized node '" + Operator->getName() + "'!");
std::vector<std::pair<TreePatternNode*, std::string> > Children;
-
+
for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
Init *Arg = Dag->getArg(i);
if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
DEBUG(std::cerr << "Getting node types: ");
for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
Record *Node = Nodes[i];
-
+
// Translate the return type...
NodeType::ArgResultTypes RetTy =
NodeType::Translate(Node->getValueAsDef("RetType"));
// Check to see if we have already instantiated this pair...
Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
if (Slot) return Slot;
-
+
Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
// Copy over the superclasses...
unsigned IndentAmt) {
assert(!Patterns.empty() && "No patterns to emit matchers for!");
std::string Indent(IndentAmt, ' ');
-
+
// Load all of the operands of the root node into scalars for fast access
const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
std::string LocCostName = VarPrefix + "_Cost";
OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
<< Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
-
+
#if 0
// Separate out all of the patterns into groups based on what their top-level
// signature looks like...
OS << Indent << " if (" << LocCostName << " < " << LocCostName << "Min) { "
<< LocCostName << "Min = " << LocCostName << "; " << VarPrefix
<< "_PatternMin = " << VarPrefix << "_Pattern; }\n";
-
+
OS << Indent << "}\n";
}
#endif
P->error("Unknown operand type to expander!");
}
-static std::string getArgName(Pattern *P, const std::string &ArgName,
+static std::string getArgName(Pattern *P, const std::string &ArgName,
const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
if (ArgName.empty()) return "";
void InstrSelectorEmitter::run(std::ostream &OS) {
// Type-check all of the node types to ensure we "understand" them.
ReadNodeTypes();
-
+
// Read in all of the nonterminals, instructions, and expanders...
ReadNonterminals();
ReadInstructionPatterns();
DEBUG(std::cerr << " " << *I->second << "\n");
CalculateComputableValues();
-
+
OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
<< " unsigned Pattern = NoMatchPattern;\n"
<< " unsigned MinCost = ~0U >> 1;\n";
-
+
std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
for (unsigned i = 0, e = J->second.size(); i != e; ++i)
Patterns.push_back(std::make_pair(J->second[i],
J->second[i]->getTree()));
EmitMatchCosters(OS, Patterns, "N", 2);
-
+
OS << "\n N->setPatternCostFor(" << SlotName
<< "_Slot, Pattern, MinCost, NumSlots);\n"
<< " return MinCost;\n"
// Loop over the operands, reducing them...
std::vector<std::pair<TreePatternNode*, std::string> > Operands;
ReduceAllOperands(P->getTree(), "N", Operands, OS);
-
+
// Now that we have reduced all of our operands, and have the values
// that reduction produces, perform the reduction action for this
// pattern.
<< "->Val";
});
DEBUG(OS << " << \"\\n\";\n");
-
+
// Generate the reduction code appropriate to the particular type of
// pattern that this is...
switch (P->getPatternType()) {
Pattern *InstPat = getPattern(InstRec);
if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
P->error("Instruction list must contain Instruction patterns!");
-
+
bool hasResult = InstPat->getResult() != 0;
if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
P->error("Incorrect number of arguments specified for inst '" +
<< " break;\n"
<< " }\n";
}
-
-
+
+
OS << " default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
<< " }\n\n N->addValue(Val); // Do not ever recalculate this\n"
<< " return Val;\n}\n\n";
//===- InstrInfoEmitter.h - Generate a Instruction Set Desc. ----*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
/// there was a (set) node on the outside level that it has been stripped off.
///
TreePatternNode *Tree;
-
+
/// Result - If this is an instruction or expander pattern, this is the
/// register result, specified with a (set) in the pattern.
///
/// getTree - Return the tree pattern which corresponds to this pattern.
///
TreePatternNode *getTree() const { return Tree; }
-
+
Record *getResult() const {
return ResultNode ? ResultNode->getValueRecord() : 0;
}
public:
InstrSelectorEmitter(RecordKeeper &R) : Records(R) {}
-
+
// run - Output the instruction set description, returning true on failure.
void run(std::ostream &OS);
// InstantiateNonterminals - Instantiate any unresolved nonterminals with
// information from the context that they are used in.
void InstantiateNonterminals();
-
+
// CalculateComputableValues - Fill in the ComputableValues map through
// analysis of the patterns we are playing with.
void CalculateComputableValues();
void EmitMatchCosters(std::ostream &OS,
const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
const std::string &VarPrefix, unsigned Indent);
-
+
/// PrintExpanderOperand - Print out Arg as part of the instruction emission
/// process for the expander pattern P. This argument may be referencing some
/// values defined in P, or may just be physical register references or
//===- Record.cpp - Record implementation ---------------------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
//
Init *BitRecTy::convertValue(IntInit *II) {
int Val = II->getValue();
if (Val != 0 && Val != 1) return 0; // Only accept 0 or 1 for a bit!
-
- return new BitInit(Val != 0);
+
+ return new BitInit(Val != 0);
}
Init *BitRecTy::convertValue(TypedInit *VI) {
Ret->setBit(0, VI);
return Ret;
}
-
+
return 0;
}
Init *IntRecTy::convertValue(BitsInit *BI) {
int Result = 0;
- for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
+ for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
if (BitInit *Bit = dynamic_cast<BitInit*>(BI->getBit(i))) {
Result |= Bit->getValue() << i;
} else {
bool BitsInit::printInHex(std::ostream &OS) const {
// First, attempt to convert the value into an integer value...
int Result = 0;
- for (unsigned i = 0, e = getNumBits(); i != e; ++i)
+ for (unsigned i = 0, e = getNumBits(); i != e; ++i)
if (BitInit *Bit = dynamic_cast<BitInit*>(getBit(i))) {
Result |= Bit->getValue() << i;
} else {
}
bool BitsInit::printAsUnset(std::ostream &OS) const {
- for (unsigned i = 0, e = getNumBits(); i != e; ++i)
+ for (unsigned i = 0, e = getNumBits(); i != e; ++i)
if (!dynamic_cast<UnsetInit*>(getBit(i)))
return true;
OS << "?";
assert(RV && "Reference to a non-existant variable?");
assert(dynamic_cast<BitsInit*>(RV->getValue()));
BitsInit *BI = (BitsInit*)RV->getValue();
-
+
assert(Bit < BI->getNumBits() && "Bit reference out of range!");
Init *B = BI->getBit(Bit);
return Val->getValue();
return this;
}
-
+
Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) {
if (Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
if (BitsInit *BI = dynamic_cast<BitsInit*>(BitsVal)) {
assert(Bit < BI->getNumBits() && "Bit reference out of range!");
Init *B = BI->getBit(Bit);
-
+
if (dynamic_cast<BitInit*>(B)) // If the bit is set...
return B; // Replace the VarBitInit with it.
}
for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
E = Classes.end(); I != E; ++I)
OS << "class " << *I->second;
-
+
OS << "------------- Defs -----------------\n";
const std::map<std::string, Record*> &Defs = RK.getDefs();
for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
//===- Record.h - Classes to represent Table Records ------------*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines the main TableGen data structures, including the TableGen
virtual Init *convertValue( TypedInit *TI);
virtual Init *convertValue( VarInit *VI) { return RecTy::convertValue(VI);}
virtual Init *convertValue( FieldInit *FI) { return RecTy::convertValue(FI);}
-
+
void print(std::ostream &OS) const;
bool typeIsConvertibleTo(const RecTy *RHS) const {
virtual bool baseClassOf(const IntRecTy *RHS) const { return false; }
virtual bool baseClassOf(const StringRecTy *RHS) const { return false; }
virtual bool baseClassOf(const ListRecTy *RHS) const {
- return RHS->getElementType()->typeIsConvertibleTo(Ty);
+ return RHS->getElementType()->typeIsConvertibleTo(Ty);
}
virtual bool baseClassOf(const CodeRecTy *RHS) const { return false; }
virtual bool baseClassOf(const DagRecTy *RHS) const { return false; }
virtual Init *convertValue(VarBitInit *VB) { return 0; }
virtual Init *convertValue( DefInit *DI);
virtual Init *convertValue( DagInit *DI) { return 0; }
- virtual Init *convertValue( TypedInit *VI);
+ virtual Init *convertValue( TypedInit *VI);
virtual Init *convertValue( VarInit *VI) { return RecTy::convertValue(VI);}
virtual Init *convertValue( FieldInit *FI) { return RecTy::convertValue(FI);}
virtual Init *getFieldInit(Record &R, const std::string &FieldName) const {
return 0;
}
-
+
enum BinaryOp { SHL, SRA, SRL };
virtual Init *getBinaryOp(BinaryOp Op, Init *RHS) {
return 0;
///
class TypedInit : public Init {
RecTy *Ty;
-public:
+public:
TypedInit(RecTy *T) : Ty(T) {}
RecTy *getType() const { return Ty; }
std::string VarName;
public:
VarInit(const std::string &VN, RecTy *T) : TypedInit(T), VarName(VN) {}
-
+
virtual Init *convertInitializerTo(RecTy *Ty) {
return Ty->convertValue(this);
}
/// users of the value to allow the value to propagate out.
///
virtual Init *resolveReferences(Record &R, const RecordVal *RV);
-
+
virtual void print(std::ostream &OS) const { OS << VarName; }
};
TypedInit *getVariable() const { return TI; }
unsigned getBitNum() const { return Bit; }
-
+
virtual void print(std::ostream &OS) const {
TI->print(OS); OS << "{" << Bit << "}";
}
virtual Init *resolveReferences(Record &R, const RecordVal *RV);
};
-/// VarListElementInit - List[4] - Represent access to one element of a var or
+/// VarListElementInit - List[4] - Represent access to one element of a var or
/// field.
class VarListElementInit : public TypedInit {
TypedInit *TI;
Record *Def;
public:
DefInit(Record *D) : Def(D) {}
-
+
virtual Init *convertInitializerTo(RecTy *Ty) {
return Ty->convertValue(this);
}
virtual RecTy *getFieldType(const std::string &FieldName) const;
virtual Init *getFieldInit(Record &R, const std::string &FieldName) const;
-
+
virtual void print(std::ostream &OS) const;
};
ArgNames.push_back(args[i].second);
}
}
-
+
virtual Init *convertInitializerTo(RecTy *Ty) {
return Ty->convertValue(this);
}
E = Defs.end(); I != E; ++I)
delete I->second;
}
-
+
const std::map<std::string, Record*> &getClasses() const { return Classes; }
const std::map<std::string, Record*> &getDefs() const { return Defs; }
//===- RegisterInfoEmitter.cpp - Generate a Register File Desc. -*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of a target
for (unsigned i = 0, e = Registers.size(); i != e; ++i)
OS << " " << Registers[i].getName() << ", \t// " << i+1 << "\n";
-
+
OS << " };\n";
if (!Namespace.empty())
OS << "}\n";
<< " specified multiple times!\n";
RegisterAliases[Reg->getDef()].insert(R);
}
- }
+ }
if (!RegisterAliases.empty())
OS << "\n\n // Register Alias Sets...\n";
-
+
// Emit the empty alias list
OS << " const unsigned Empty_AliasSet[] = { 0 };\n";
// Loop over all of the registers which have aliases, emitting the alias list
Reg.getName() + "'!";
}
- OS << SpillSize << ", " << SpillAlign << " },\n";
+ OS << SpillSize << ", " << SpillAlign << " },\n";
}
OS << " };\n"; // End of register descriptors...
OS << "}\n\n"; // End of anonymous namespace...
std::string ClassName = Target.getName() + "GenRegisterInfo";
-
+
// Emit the constructor of the class...
OS << ClassName << "::" << ClassName
<< "(int CallFrameSetupOpcode, int CallFrameDestroyOpcode)\n"
<< " : MRegisterInfo(RegisterDescriptors, " << Registers.size()+1
<< ", RegisterClasses, RegisterClasses+" << RegClassNames.size() << ",\n "
<< " CallFrameSetupOpcode, CallFrameDestroyOpcode) {}\n\n";
-
+
// Emit the getCalleeSaveRegs method...
OS << "const unsigned* " << ClassName << "::getCalleeSaveRegs() const {\n"
<< " static const unsigned CalleeSaveRegs[] = {\n ";
const std::vector<Record*> &CSR = Target.getCalleeSavedRegisters();
for (unsigned i = 0, e = CSR.size(); i != e; ++i)
- OS << getQualifiedName(CSR[i]) << ", ";
+ OS << getQualifiedName(CSR[i]) << ", ";
OS << " 0\n };\n return CalleeSaveRegs;\n}\n\n";
OS << "} // End llvm namespace \n";
}
//===- RegisterInfoEmitter.h - Generate a Register File Desc. ---*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of a target
RecordKeeper &Records;
public:
RegisterInfoEmitter(RecordKeeper &R) : Records(R) {}
-
+
// run - Output the register file description, returning true on failure.
void run(std::ostream &o);
//===- TableGen.cpp - Top-Level TableGen implementation -------------------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// TableGen is a tool which can be used to build up a description of something,
unsigned LastFixedBit = FirstVaryingBit;
while (LastFixedBit < MaxBits && BitsAreFixed(I1, I2, LastFixedBit))
++LastFixedBit;
-
+
if (FirstVaryingBit < FirstVaryingBitOverall)
FirstVaryingBitOverall = FirstVaryingBit;
if (LastFixedBit < LastFixedBitOverall)
}
};
-static void PrintRange(std::vector<Record*>::iterator I,
+static void PrintRange(std::vector<Record*>::iterator I,
std::vector<Record*>::iterator E) {
while (I != E) std::cerr << **I++;
}
// instructions that we may have found. Eventually, this list will get pared
// down to zero or one instruction, in which case we have a match or failure.
//
-static Record *ParseMachineCode(std::vector<Record*>::iterator InstsB,
+static Record *ParseMachineCode(std::vector<Record*>::iterator InstsB,
std::vector<Record*>::iterator InstsE,
unsigned char *M) {
assert(InstsB != InstsE && "Empty range?");
while (RangeEnd != InstsE &&
BitRangesEqual(*RangeBegin, *RangeEnd, FirstVaryingBit, LastFixedBit))
++RangeEnd;
-
+
// We just identified a range of equal instructions. If this range is the
// input range, we were not able to distinguish between the instructions in
// the set. Print an error and exit!
PrintRange(InstsB, InstsE);
exit(1);
}
-
+
#if 0
std::cerr << "FVB: " << FirstVaryingBit << " - " << LastFixedBit
<< ": [" << RangeEnd-RangeBegin << "] - ";
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(i)))
Value |= B->getValue() << i;
-
+
// Loop over all of the fields in the instruction adding in any
// contributions to this value (due to bit references).
//
Value |= getMemoryBit(Ptr, Offset+i) << i;
break;
}
-
+
// Scan through the field looking for bit initializers of the current
// variable...
for (unsigned i = 0, e = FieldInitializer->getNumBits(); i != e; ++i)
std::cout << "Inst " << getNumBits(I)/8 << " bytes: "
<< "\t" << I->getName() << "\t" << *I->getValue("Name")->getValue()
<< "\t";
-
+
const std::vector<RecordVal> &Vals = I->getValues();
for (unsigned i = 0, e = Vals.size(); i != e; ++i)
if (!Vals[i].getValue()->isComplete()) {
PrintValue(I, Ptr, Vals[i]);
std::cout << "\t";
}
-
+
std::cout << "\n";// << *I;
}
#if 0
// SparcV9 code
- unsigned char Buffer[] = { 0xbf, 0xe0, 0x20, 0x1f, 0x1, 0x0, 0x0, 0x1,
+ unsigned char Buffer[] = { 0xbf, 0xe0, 0x20, 0x1f, 0x1, 0x0, 0x0, 0x1,
0x0, 0x0, 0x0, 0x0, 0xc1, 0x0, 0x20, 0x1, 0x1,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0, 0x1,
//===- TableGenBackend.cpp - Base class for TableGen Backends ---*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file provides useful services for TableGen backends...
//===- TableGenBackend.h - Base class for TableGen Backends -----*- C++ -*-===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// The TableGenBackend class is provided as a common interface for all TableGen
//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// fpcmp is a tool that basically works like the 'cmp' tool, except that it can