LLVM get constant integer back from Value*

醉酒当歌 提交于 2019-11-28 08:59:44

Given llvm::Value* foo and you know that foo is actually a ConstantInt, I believe that the idiomatic LLVM code approach is to use dyn_cast as follows:

if (llvm::ConstantInt* CI = dyn_cast<llvm::ConstantInt>(foo)) {
  // foo indeed is a ConstantInt, we can use CI here
}
else {
  // foo was not actually a ConstantInt
}

If you're absolutely sure that foo is a ConstantInt and are ready to be hit with an assertion failure if it isn't, you can use cast instead of dyn_cast.


P.S. Do note that cast and dyn_cast are part of LLVM's own implementation of RTTI. dyn_cast acts somewhat similarly to the standard C++ dynamic_cast, though there are differences in implementation and performance (as can be read here).

Eli's answer is great, but it's missing the final part, which is getting the integer back. The full picture should look like this:

if (ConstantInt* CI = dyn_cast<ConstantInt>(Val)) {
  if (CI->getBitWidth() <= 32) {
    constIntValue = CI->getSExtValue();
  }
}

Of course, you can also change it to <= 64 if constIntValue is a 64-bit integer, etc.

And as Eli wrote, if you are confident the value is indeed of type ConstInt, you can use cast<ConstantInt> instead of dyn_cast.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!