How can I generated C code from codegen.cc

Hello everyone,

I’ve looked few related previous post, but I found few information, but I don’t exactly find the answer to my question, so here it is.

In this article, Bring Your Own Codegen To TVM, explains how codegen.cc does the C code generation.

I can add this line to test_target_codegen_c_host.py to see the generated code, and I can check the generated cod by this line print(mhost.get_source())

However the generated code doesn’t seem like it is from codegen.cc.

So my question is what target should I put in tvm.buil to generate the C code from codegen.cc .

Thanks a lot.

They are different stories.

The C codegen you pointed out in BYOC is only used to demonstrate how BYOC works, so TVM backend for CPU doesn’t go through it.

Instead, TVM backend for CPU directly generates LLVM IR, so you won’t get the generated C source code. Although TVM does have C codgen base class, it is an abstract class and derived for OpenCL code generation for GPUs.

1 Like

Hi @comaniac,

Thank you very much for the clarification.

So the generated output from test_target_codegen_c_host.py using target="c" is from LLVM IR.

         mhost = tvm.build(s, [A, B, C], "c", name="fadd")
         print(mhost.get_source()) # added line
$ python `find . -name test_target_codegen_c_host.py`
#include "tvm/runtime/c_runtime_api.h"
#include "tvm/runtime/c_backend_api.h"
void* __tvm_module_ctx = NULL;
#ifdef __cplusplus
extern "C"
#endif
TVM_DLL int32_t fadd(void* args, void* arg_type_ids, int32_t num_args, void* out_ret_value, void* out_ret_tcode, void* resource_handle) {
  void* arg0 = (((TVMValue*)args)[0].v_handle);
  int32_t arg0_code = ((int32_t*)arg_type_ids)[(0)];
  void* arg1 = (((TVMValue*)args)[1].v_handle);
  int32_t arg1_code = ((int32_t*)arg_type_ids)[(1)];
  void* arg2 = (((TVMValue*)args)[2].v_handle);
  int32_t arg2_code = ((int32_t*)arg_type_ids)[(2)];
  void* A = (((DLTensor*)arg0)[0].data);
  void* arg0_shape = (((DLTensor*)arg0)[0].shape);
  void* arg0_strides = (((DLTensor*)arg0)[0].strides);
  int32_t dev_id = (((DLTensor*)arg0)[0].ctx.device_id);
  void* B = (((DLTensor*)arg1)[0].data);
  void* arg1_shape = (((DLTensor*)arg1)[0].shape);
  void* arg1_strides = (((DLTensor*)arg1)[0].strides);
  void* C = (((DLTensor*)arg2)[0].data);
  void* arg2_shape = (((DLTensor*)arg2)[0].shape);
  void* arg2_strides = (((DLTensor*)arg2)[0].strides);
  if (!(arg0_strides == NULL)) {
  }
  if (!(arg1_strides == NULL)) {
  }
  if (!(arg2_strides == NULL)) {
  }
  for (int32_t i0 = 0; i0 < 1024; ++i0) {
    ((float*)C)[(i0)] = (((float*)A)[(i0)] + ((float*)B)[(i0)]);
  }
  return 0;
}

Thank you.

1 Like