Pattern Matching in LLVM

Hi,

Are there any in-built library functions available in LLVM to pattern match lexically the same arithmetic LLVM IR instructions? These arithmetic instructions can involve any operands, like normal variables, pointers, structures, arrays, etc.
Thanks.

maybe llvm::PatternMatch can help you?

1 Like

Thanks @mshockwave. I think it will work from the initial read. But I find the description for llvm:PatternMatch a bit difficult.
In the following snippet of LLVM IR, whether %10 = add nsw i32 %8, %9 and %18 = add nsw i32 %16, %17 will be matched the same as they represent the same expression ( x+y) using this PatternMatch? This was what I wanted.

 define dso_local i32 @main() #0 {
  %1 = alloca i32, align 4
  %2 = alloca i32, align 4
  %3 = alloca i32, align 4
  :
  :
  %8 = load i32, ptr %2, align 4
  %9 = load i32, ptr %3, align 4
  %10 = add nsw i32 %8, %9
  store i32 %10, ptr %4, align 4
  :
  :
  %16 = load i32, ptr %2, align 4
  %17 = load i32, ptr %3, align 4
  %18 = add nsw i32 %16, %17
  store i32 %18, ptr %6, align 4

Thanks in advance for your help.

Value *X, *Y; // These two are unused.
match(/*Value to be matched*/, m_BinOp(Instruction::Add, m_Value(X), m_Value(Y))

m_Value will bind the matched operand Value-s to X and Y.

I agree that the (doxygen) reference is kind of incomplete, you can checkout its source code in llvm/include/llvm/IR/PatternMatch.h.

2 Likes

Thanks @mshockwave for the detailed explanation. I will implement and check.