What exactly is the LLVM C++ API

ぃ、小莉子 提交于 2020-06-24 22:10:19

问题


I found it hard to understand the LLVM C++ API.
Is there any relationship between LLVM C++ API and LLVM IR? Also, how could one use the LLVM C++ API?


回答1:


To (greatly) simplify, LLVM is a C++ library for writing compilers. Its C++ API is the external interface users of the library employ to implement their compiler.

There's a degree of symmetry between LLVM IR and part of the LLVM C++ API - the part used to build IR. A very good resource for getting a feel for this symmetry is http://llvm.org/demo/. For example, you can compile this C code:

int factorial(int X) {
  if (X == 0) return 1;
  return X*factorial(X-1);
}

Into LLVM IR:

define i32 @factorial(i32 %X) nounwind uwtable readnone {
  %1 = icmp eq i32 %X, 0
  br i1 %1, label %tailrecurse._crit_edge, label %tailrecurse

tailrecurse:                                      ; preds = %tailrecurse, %0
  %X.tr2 = phi i32 [ %2, %tailrecurse ], [ %X, %0 ]
  %accumulator.tr1 = phi i32 [ %3, %tailrecurse ], [ 1, %0 ]
  %2 = add nsw i32 %X.tr2, -1
  %3 = mul nsw i32 %X.tr2, %accumulator.tr1
  %4 = icmp eq i32 %2, 0
  br i1 %4, label %tailrecurse._crit_edge, label %tailrecurse

tailrecurse._crit_edge:                           ; preds = %tailrecurse, %0
  %accumulator.tr.lcssa = phi i32 [ 1, %0 ], [ %3, %tailrecurse ]
  ret i32 %accumulator.tr.lcssa
}

As well as to C++ API calls (I won't paste it here because the output is long, but you can try it yourself). Doing this, you'll see, for example the icmp instruction from the IR code above done as:

ICmpInst* int1_5 = new ICmpInst(*label_4, ICmpInst::ICMP_EQ, int32_X, const_int32_1, "");

ICmpInst is a class that's part of the C++ API used to create icmp instructions. A good reference for the C++ API is the Programmer's manual.




回答2:


You can use the CPP backend (llc -march=cpp) to find out the mapping from any given IR to the C++ API.



来源:https://stackoverflow.com/questions/10675661/what-exactly-is-the-llvm-c-api

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