Paul Schutte
Paul Schutte

Reputation: 386

How to use inline assembly using the llvm-c API

I can not figure out how to piece everything together.

I want to generate llvm-ir for the following "C" instruction:

asm volatile("nop");

In the future I would like to include more advanced inline assembly, but this will be a good start.

I have read:

https://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html

https://llvm.org/docs/LangRef.html#inline-assembler-expressions

My last attempt is the following:

char myasm[256]="nop";
char myconstraint[256]={0};

LLVMTypeRef voidty=LLVMVoidType();
LLVMValueRef asmcall=LLVMGetInlineAsm(voidty,myasm,strlen(myasm),
             myconstraint,strlen(myconstraint),1,1,LLVMInlineAsmDialectIntel);
LLVMSetVolatile(asmcall,1);
LLVMValueRef call = LLVMBuildCall( llbuilder, asmcall, (LLVMValueRef *)dummy->data,
             dummy->size, "acall");

I just get a segfault. The problem is not the "dummy" array. I use it in other places without any problems. In this case it is just an empty list of 0 size.

Help would be appreciated.

Upvotes: 2

Views: 2930

Answers (1)

Paul Schutte
Paul Schutte

Reputation: 386

The missing ingredient was:

LLVMTypeRef functy = LLVMFunctionType(voidty, (LLVMTypeRef *)ptypes->data, ptypes->size, 0);

Whole answer is therefore:

char myasm[256]="nop";
char myconstraint[256]={0};

LLVMTypeRef voidty = LLVMVoidType();
LLVMTypeRef functy = LLVMFunctionType(voidty, (LLVMTypeRef *)ptypes->data, ptypes->size, 0);
LLVMValueRef asmcall = LLVMGetInlineAsm(functy,myasm,strlen(myasm),
         myconstraint,strlen(myconstraint),1,1,LLVMInlineAsmDialectIntel);
LLVMValueRef call = LLVMBuildCall2( llbuilder, functy, asmcall,
         (LLVMValueRef *)pvalues->data,pvalues->size, "");

Upvotes: 6

Related Questions