How to find variable names from LLVM IR?

If I have an operand as a Value from an instruction like: Value* V = opnd->get(); and I am sure this is a variable, I want to know the variable name (in source code) for this Value object. I am doing it like this:

const Function* Func;
if (const Argument* Arg = dyn_cast(V))
{
Func = Arg->getParent();
}
else if (const Instruction* I = dyn_cast(V))
{
Func = I->getParent()->getParent();
}

StringRef name;
if (!Func)
name = V->getName();

else
{
const DILocalVariable* Var = NULL;

for (const_inst_iterator Iter = inst_begin(Func), End = inst_end(Func); Iter != End; ++Iter)
{
if (const DbgDeclareInst* DbgDeclare = dyn_cast(&Iter))
{
if (DbgDeclare->getAddress() == V) Var = DbgDeclare->getVariable();
}
else if (const DbgValueInst
DbgValue = dyn_cast(&*Iter))
{
if (DbgValue->getValue() == V) Var = DbgValue->getVariable();
}
}

name = Var->getName();
}
errs() << "\nVariableName: " << name.str() << “\n”;

But this condition: if(DbgDeclare->getAddress() == V) produces false result as the address for the Value object differs from every Value object found in dbg.declare intrinsic. Is this not how one finds the variable name??
What am I doing wrong?

Optimized debug info is best effort & not terribly accurate in LLVM currently (it’ll always be best effort, it’s just that best could be better than it is today), so it’s quite possible that a Value you know is in a variable isn’t being tracked by debug info anymore because it got lost somewhere along the way.

When you look at the IR, does it seem that it has debug info intrinsics describing the value you’re interested in? If not, did it start out that way & lose it due to optimization somewhere? Which optimization? (print-after-all can help track this sort of thing through an optimization pipeline) Perhaps you can improve the debug info quality of the optimization so it preserves what you need. But realize/remember it’ll never be perfect, there’s lots of lossy things that optimizations do.