About llc compiler with -fPIC

I want to run a end2end .mlir demo on host with C API. And I use mnist for example.
I use this mlir-opt mnist-12.onnx-global.mlir --lower-affine -convert-scf-to-cf -convert-linalg-to-llvm -convert-memref-to-llvm -llvm-request-c-wrappers -convert-func-to-llvm -reconcile-unrealized-casts | mlir-translate --mlir-to-llvmir | llc -o mnist-gloabl.o -filetype=obj to produce object file and use follow C code to call it

static float img_data[] = ... 

extern "C" {
void _mlir_ciface_entry(MemRef<float, 4> *, MemRef<float, 2> *);
}

int main() {
    intptr_t size[4] = {1, 1, 28, 28};
    MemRef<float, 4> inputs(img_data, size, 0);

    intptr_t outsize[2] = {1, 10};
    MemRef<float, 2> outputs(outsize);
    for (size_t i = 0; i < 1000; i++)
    {
        _mlir_ciface_entry(&inputs, &outputs);
    }

    int digit = -1;
    float prob = 0.;
    for (int i = 0; i < 10; i++) {
        printf("prediction[%d] = %f\n", i, outputs[i]);
        if (outputs[i] > prob) {
            digit = i;
            prob = outputs[i];
        }
    }
    printf("The digit is %d\n", digit);
    return 0;
}

and compiler it with

g++ mnist.cpp Container.cpp mnist-global.o

But with error of /usr/bin/ld: mnist-global.o: relocation R_X86_64_32S against `.rodata’ can not be used when making a PIE object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status

how to recompiler it with llc? or other methods?

And I use follow code to compiler it

(base) ➜  mlir-opt mnist-12.onnx-global.mlir --lower-affine -convert-scf-to-cf -convert-linalg-to-llvm -convert-memref-to-llvm -llvm-request-c-wrappers -convert-func-to-llvm  -reconcile-unrealized-casts | mlir-translate --mlir-to-llvmir | llc -o mnist.s
(base) ➜  clang++ -fPIC -c -o mnist-global.o mnist.s                                                                                                                                                                                                                  
(base) ➜  clang++ mnist.cpp Container.cpp mnist-global.o                                                                                                                                                                                                                              
/usr/bin/ld: mnist-global.o: relocation R_X86_64_32S against `.rodata' can not be used when making a PIE object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status

but with same error.

Can you try to replace llc with clang -fPIC directly?

mlir-opt ... | mlir-translate --mlir-to-llvmir | clang -x ir - -fPIC -c -o mnist-global.o

(also ultimately don’t forget to throw the LLVM optimizer in there by adding -O2 to the clang invocation)

1 Like

It is successful for me. Thank you for your reply.