How do I print out an Instruction in LLVM? - c++

for (BasicBlock::iterator i = bb->begin(), e = bb->end(); i != e; ++i) {
i.print(errs()); ???
I am writing an LLVM PASS and I want to get the list of instructions inside the basic block, but how do print them out on the console so I can see them? The code above shows the code i have tried, it iterates through every instruction in the basic block but I get the error below for the print function.
error: ‘llvm::BasicBlock::iterator’ has no member named ‘print’
i.print(errs());
Is there a better approach to printing out instructions?

The problem is that you are trying to print the iterator and not an instruction. You can try one of the following approaches. You can print the instructions in a basic block by either printing the basic block or printing each instruction:
BasicBlock* bb = ...; //
errs() << *bb;
for (BasicBlock::iterator i = bb->begin(), e = bb->end(); i != e; ++i) {
Instruction* ii = &*i;
errs() << *ii << "\n";
Both prints will output the same results.

Related

LLVM non local memory dependency analyis

I am writing a LLVM pass which needs to analyse memory dependencies. The pass needs to find for a memory read every instruction that could have defined this memory. For example:
int foo(){
int x = 123;
if(getchar()){
x = 321;
}
return x;
}
In this case the pass needs to find both definitions of x when it loads x from memory on the return. I used the following code in my pass.
MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
if (isa<LoadInst>(i)) {
MemDepResult d = MDA.getDependency(&i);
if (d.isNonLocal()) {
SmallVector<NonLocalDepResult, 4> result;
MDA.getNonLocalPointerDependency(&i, result);
for (SmallVectorImpl<NonLocalDepResult>::iterator it=result.begin() ; it < result.end(); it++ ) {
MemDepResult dd = it->getResult();
if (dd.isUnknown())
errs() << "Unknown\n"; //result always unknown
}
}
}
}
MDA.getDependency() gives me the right results for dependencies that a local (in the same basic block). But getNonLocalPointerDependency() always return null pointers.
How do I get LLVM to find every store that could have defined the memory of a load instruction?

How do you determine what kind of node you are dealing with in yaml-cpp?

I'm reading the tutorial code here: https://code.google.com/p/yaml-cpp/wiki/Tutorial
One example goes like this:
YAML::Node primes = YAML::Load("[2, 3, 5, 7, 11]");
for (YAML::const_iterator it=primes.begin();it!=primes.end();++it) {
std::cout << it->as<int>() << "\n";
}
And the next like this:
YAML::Node lineup = YAML::Load("{1B: Prince Fielder, 2B: Rickie Weeks, LF: Ryan Braun}");
for(YAML::const_iterator it=lineup.begin();it!=lineup.end();++it) {
std::cout << "Playing at " << it->first.as<std::string>() << " is " << it->second.as<std::string>() << "\n";
}
However, if you swap the YAML files between these two cases, you will get an error, as you are accessing a map iterator for a sequence or vice versa:
terminate called after throwing an instance of 'YAML::InvalidNode'
what(): yaml-cpp: error at line 0, column 0: invalid node; this may result from using a map iterator as a sequence iterator, or vice-versa
For an arbitrary YAML input, how can I determine whether I am dealing with a sequence or a map in the loop (ie whether I should be using ->first or not) without using a try/catch block?
I tried looking for the documentation, but I could not find it.
UPDATE:
This is what I am trying to do:
YAML::Node config = YAML::LoadFile(filename);
for (YAML::const_iterator it=config.begin();it!=config.end();++it) {
if (it->Type() == YAML::NodeType::Map) { // exception
std::cout << it->first.as<std::string>();
} else if (it->Type() == YAML::NodeType::Sequence) {
std::cout << it->as<std::string>();
}
}
But when I run the code I get the exception as above. It compiles fine.
I am using the yaml-cpp which comes with ubuntu 14.04 (0.5.1).
You can either
switch (node.Type()) {
case Null: // ...
case Scalar: // ...
case Sequence: // ...
case Map: // ...
case Undefined: // ...
}
or query explicitly, e.g.:
if (node.IsSequence()) {
// ...
}
(I added this bit to the Tutorial.)
Edit: In your specific example, you should check config.Type() before you iterate, not the type of any of the nodes during your iteration.

How to Insert a LLVM Instruction?

I've been searching for hours and I can't find anything that could help me. I'm working on a project that involves a FunctionPass. I've implemented a runOnFunction(Function &f) method and that's working fine. Basically it needs to:
1) Detect a store instruction
2) Convert the memory address of the store instruction to an Integer
3) Alter the integer using a bitwise AND operation (0000FFFF)
4) Convert the integer back into the pointer
So far I've got the following:
virtual bool runOnFunction(Function &F) {
for (Function::iterator bb = F.begin(), bbe = F.end(); bb != bbe; ++bb) {
BasicBlock& b = *bb;
for (BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i) {
if(StoreInst *si = dyn_cast<StoreInst>(&*i)) {
PtrToIntInst* ptrToInt = new PtrToIntInst(si->getPointerOperand(), IntegerType::get(si->getContext(), 32), "", si);
}
}
}
return true;
}
I can't for the life of me figure out how to actually insert the instruction, or even find a way to create an AND instruction. If anyone could point me in the right direction, that would be great.
Thanks in advance.
I recommend taking a look at the Programmer's Manual - it has a pretty decent coverage of the basics.
In particular, there's a section about creating and inserting new instructions. The simplest way is just to provide an existing instruction as the last argument for the new instruction's constructor, which will then insert that instruction immediately before the existing one.
Alternatively, you can pass the enclosing basic block if you just want to add to its end (but remember you need to take care of the terminator!). Finally, you can just call getInstList() on the enclosing basic block, then insert or push_back to insert new instructions there.
As an aside, you don't have to iterate over all blocks and then over all instructions in each, you can just iterate over the instructions directly; see the section about the instruction iterator in the programmer's manual.
virtual bool runOnFunction(Function &F) {
for (Function::iterator bb = F.begin(), bbe = F.end(); bb != bbe; ++bb) {
BasicBlock &b = *bb;
for (BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i) {
if (StoreInst *si = dyn_cast<StoreInst>(&*i)) {
IRBuilder Builder(si);
Value *StoreAddr = Builder.CreatePtrToInt(si->getPointerOperand(), Builder.getInt32Ty());
Value *Masked = Builder.CreateAnd(StoreAddr, 0xffff);
Value *AlignedAddr = Builder.CreateIntToPtr(Masked, si->getPointerOperand()->getType());
// ...
}
}
}
return true;
}
You can use an IRBuilder to easily insert new instructions before another instruction or at the end of a basic block.
Alternatively, if you need to insert an instruction after another one, you need to use the instruction list in the containing basic block:
BasicBlock *pb = ...;
Instruction *pi = ...;
Instruction *newInst = new Instruction(...);
pb->getInstList().insertAfter(pi, newInst);
Code and solution taken from here.

delete loop by eraseFromParent command in llvm

*I would delete the Loop. I used the following code:
cout << "begin to delete loop" << endl;
for (Loop::block_iterator bi = L->block_begin(), bi2; bi != L->block_end(); bi = bi2) {
bi2 = bi;
bi2++;
BasicBlock * BB = *bi;
for (BasicBlock::iterator ii = BB->begin(), ii2; ii != BB->end(); ii= ii2) {
ii2 = ii;
ii2++;
Instruction *inst = ii;
inst->eraseFromParent();
}
BB->eraseFromParent();
}
But I get the following error:
Use still stuck around after Def is destroyed: %t1 = icmp sle i32 %t0, 9
opt: /home/llvm/src/lib/VMCore/Value.cpp:75: virtual llvm::Value::~Value(): Assertion `use_empty() && "Uses remain when a value is destroyed!"' failed.
0 opt 0x0848e569
Stack dump:
What suggestions do you have for solve this problem?*
The solution of you problem is as follows:
make sure that for each instruction in the loop to drop all references, then simply erase all the BasicBlocks of the loop.
here is my sample code
for (Loop::block_iterator block = CPLoop->block_begin(), end = CPLoop->block_end(); block != end; block++) {
BasicBlock * bb = *block;
for (BasicBlock::iterator II = bb->begin(); II != bb->end(); ++II) {
Instruction * insII = &(*II);
insII->dropAllReferences();
}
}
for (Loop::block_iterator block = CPLoop->block_begin(), end = CPLoop->block_end(); block != end; block++) {
BasicBlock * bb = *block;
bb->removeFromParent();
}
I hope this helps
What I write is only a guess, cause I am just starting with LLVM, but I hope it will be helpful.
In SSA form each instruction:
uses values provided by previously executed instructions
provides value (with is result of executing this instruction), which is used by others.
Those are called use-def and def-use chains.
If you try to remove instruction which result (a.k.a. "provided Value") is used by other instructions, than you break instruction chain.
You might be interested in iteratating over users of instruction you remove, using :
LLVM Programmer's Manual : Iterating over def-use & use-def chains. Thanks to that, you can iterate over users (u) of value provided by instruction, you want to remove (inst), and change their reference to another one (like inst: add u v --> add X v). Ones you make sure no one is using instruction you want to remove, remove it. (Depending if analysis passes are already made you might be required to let llvm pass manager know that CFG analysis needs to be updated - unless you update them by yourself).
You are invalidating the iterator with the call to
inst->eraseFromParent();
Store all Instruction* in an std::vector or similar and batch delete them at the end of your pass.
This should solve your problem.
There is an alternative solution for "deleting" a loop: Just permanently disable it. I.e. modify the IR code from sth. like this:
...
br label %loop
loop:
<loop body>
br i1 %exitcond, label %exit, label %loop
exit:
...
to sth. like this:
...
br i1 0, label %loop, label %exit
loop:
<loop body>
br i1 %exitcond, label %exit, label %loop
exit:
...
You will probably run optimizations (like dead code elimination) on your generated IR anyways, so why fight with all the references to the loop (e.g. in LoopInfos or ValueMaps)?

C++ program halts after dynamic memory allocation

I'm having problem with a copying method in a simple C++ program.
Everytime I call copy:
Sudoku::SudokuNode** Sudoku::copy(SudokuNode** sudokuBoard)
{
SudokuNode** tempSudokuBoard = new SudokuNode*[9];
for(int i = 0; i<9; i++)
{
tempSudokuBoard[i] = new SudokuNode[9];
for(int j = 0; j<9; j++)
{
tempSudokuBoard[i][j].currentInteger = sudokuBoard[i][j].currentInteger;
for(vector<int>::iterator iter = sudokuBoard[i][j].possibleIntegers.begin(); iter!= sudokuBoard[i][j].possibleIntegers.end();)
{
tempSudokuBoard[i][j].possibleIntegers.push_back(*iter);
}
}
}
return tempSudokuBoard;
}
The program seems to completely halt, not returning a a visible error.
If I try to debug the program, the debugger works fine until I arrive at the copy method. Then the debugger displays a dialog box saying:
There is no source code available for the current location.
Any idea what is wrong?
for(vector<int>::iterator iter = sudokuBoard[i][j].possibleIntegers.begin(); iter!= sudokuBoard[i][j].possibleIntegers.end();)
You don't seem to be advancing the iterator in that loop, so it will never end. Add ++iter to the counting expression (after the last ; in the for loop).
As to why your debugger can't find source for that location, that's platform dependent. What debugger are you using?
You do not increase the iterator on the inside loop:
for(vector<int>::iterator iter = sudokuBoard[i][j].possibleIntegers.begin(); iter!= sudokuBoard[i][j].possibleIntegers.end(); ++iter)
Resulting an infinate for loop (Compiler knows this and "optimized" it for an infinite loop, which is why there is no code available).
I suggest you recode it to use ...
class SudokuBoard
{
SudokuNode nodes[9];
};