%4 = icmp sgt i32 %2, %3
For the above instruction, how can I check whether the icmp instruction contains sgt or slt?
%4 = icmp sgt i32 %2, %3
For the above instruction, how can I check whether the icmp instruction contains sgt or slt?
A direct answer to your question is to place this code in a custom FunctionPass
:
virtual bool runOnFunction(Function &F) {
for (Function::iterator bb = F.begin(), bb_e = F.end(); bb != bb_e; ++bb) {
for (BasicBlock::iterator ii = bb->begin(), ii_e = bb->end(); ii != ii_e; ++ii) {
if (CmpInst *cmpInst = dyn_cast<CmpInst>(&*ii)) {
handle_cmp(cmpInst);
}
}
}
return false;
}
void handle_cmp(CmpInst *cmpInst) {
if (cmpInst->getPredicate() == CmpInst::ICMP_SGT) {
errs() << "In the following instruction, SGT predicate\n";
cmpInst->dump();
}
}
You seem to be asking a lot of similar questions lately, so I want to give a more general piece of advice.
Each instruction you see in LLVM IR is just a textual representation of an instruction class that exists in the LLVM code base. In this case icmp
represents ICmpInst
, which is a subclass of CmpInst
. Once you know you're dealing with CmpInst
, it's easy to see how to access its attributes just by reading the class declaration in the header file. For instance, it's obvious that the "predicate" parameter of this instruction represents that sgt
and other predicates.
But how do you know which class to look at. This is easily done with the LLVM C++ backend which dumps the equivalent C++ code needed to build some IR. For instance, given this piece of IR:
%0 = load i32* %argc.addr, align 4
%cmp = icmp sgt i32 %0, 0
It will dump:
LoadInst* int32_19 = new LoadInst(ptr_argc_addr, "", false, label_entry_15);
int32_19->setAlignment(4);
ICmpInst* int1_cmp = new ICmpInst(*label_entry_15, ICmpInst::ICMP_SGT, int32_19, const_int32_8, "cmp");
BranchInst::Create(label_if_then, label_if_else, int1_cmp, label_entry_15);
So you know just from looking at it that you need ICmpInst
, and also that the predicate is ICMP_SGT
.
To run the C++ backend on some textual IR in a .ll
file you just do:
llc -march=cpp -cppgen=program irfile.ll
Hope this helps!
Here is the solution for your question:
ICmpInst *ICC=dyn_cast<ICmpInst>(inst);
llvm::CmpInst::Predicate pr=ICC->getSignedPredicate();
switch(pr){
case CmpInst::ICMP_SGT: errs()<<"------>SGT\n"; break;
case CmpInst::ICMP_SLT: errs()<<"------>SLT\n"; break;
case CmpInst::ICMP_SGE: errs()<<"------>SGE\n"; break;
case CmpInst::ICMP_SLE: errs()<<"------>SLE\n"; break;
}
Let say you have "inst" an instruction pointer which is pointing to this instruction (%4 = icmp sgt i32 %2, %3). After doing dyanamic casting of inst to ICC which is an instance of ICmpInst class. Then call getSignedPredicate() as above it will return a predicate. Based on that there is switch case . Hope it will work for you.