[LLVMdev] dyn_cast<Instruction *> returns NULL where it should return a valid instruction

John Criswell criswell at illinois.edu
Mon May 16 07:50:10 PDT 2011


On 5/16/11 9:35 AM, Chuck Zhao wrote:
> I have the following prototype for a function:
> void bkp_memory(char *, int);
>
> Inside my LLVM IR, I have a callsite looks like the following:
> tail call void @bkp_memory(i8* bitcast (i32** @P to i8*), i32 4) nounwind
>
>
> When I try to obtain its 1st argument and check whether it is a valid 
> instruction, using:
> Instruction *Inst = dyn_cast<Instruction *>(I->getOperand(0));
>
> it gives me a NULL Ptr, which is quite a surprise to me.
>
> Am I doing anything wrong here?

The bitcast you see above is not an instruction.  Rather, it is a 
constant expression and is represented by a ConstExpr object in the C++ 
API.  That is most likely because @P is a constant (a function pointer, 
global value, or something similar).

So,

1) Use the stripPointerCasts() method of llvm::Value to strip away all 
pointer casts (whether they are cast instructions or ConstExpr casts):

I->getOperand(0)->stripPointerCasts()

2) Realize that not all operands are instructions.  In this case, the 
operand is probably a global variable.  Chances are good that:

dyn_cast<Instruction>(I->getOperand(0)->stripPointerCasts())

... will return NULL because the operand is a constant and not an 
instruction.


>
>
> Note that in many other cases, the bkp_memory() callsite won't have 
> the embedded form. They look like:
>    store i32* %21, i32** @P, align 4
>    %22 = bitcast i32* %21 to i8*
>    tail call void @bkp_memory(i8* %22, i32 4) nounwind
>
> And the dyn_cast<>  conversion is fine in these cases.
> Would that be the problem?

The "embedded" form is a constant expression.  The "unembedded" form is 
an instruction.  LLVM has several constant expressions that are modeled 
after instructions; the difference is that a constant expression's 
operands are all constants, and therefore the constant expression can 
also be used like a constant.

For more details, please see the LLVM Language Reference manual.

-- John T.

>
>
> Thank you
>
> Chuck
>
>
> _______________________________________________
> LLVM Developers mailing list
> LLVMdev at cs.uiuc.edu         http://llvm.cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20110516/0a29d68d/attachment.html>


More information about the llvm-dev mailing list