How to add metadata nodes using LLVM bindings C Api / llvm-fs

I am trying to add metadata nodes to a program, either in an instruction or as global metadata. How to do this using the LLVM C API? Now it provides the LLVMAddNamedMetadataOperand function (as found from this question ), but I don't seem to see how to use it. This is due to addNamedMetadataOperand in llvm-fs bindings. I tried this:

 addNamedMetadataOperand myModule "foobar" (mDString "cat" 3u) 

expecting it to do some node metadata called foobar , but it doesn't work - it complains about startup errors. I thought that maybe you should use addNamedMetadataOperand in the instruction, so I tried:

 let ret = buildRet bldr (constInt i32 0UL) addNamedMetadataOperand myModule "foobar" ret 

but I didn’t like it either.

+1
source share
1 answer

I added two new “friendly F # functions”: mdNode and mdNodeInContext to this commit . With this commit, I can change your sample code:

 open LLVM.Core open LLVM.Generated.Core open LLVM.Generated.BitWriter let i32 = int32Type () let i32zero = constInt i32 0UL false [<EntryPoint>] let main argv = // Set up the module/function let module_ = moduleCreateWithName "foobar" //let context = getModuleContext module_ let funcTy = functionType i32 [||] let func = addFunction module_ "main" funcTy let bldr = createBuilder () let entry = appendBasicBlock func "entry" positionBuilderAtEnd bldr entry // Make a Metadata node and try and attach it to a ret //let mdnode = mDStringInContext context "bazquux" 7u let mdstring = mDString "bazquux" 7u let ret = buildRet bldr i32zero // From http://llvm.org/docs/doxygen/html/classllvm_1_1LLVMContext.html // MD_dbg = 0, MD_tbaa = 1, MD_prof = 2, MD_fpmath = 3, MD_range = 4, MD_tbaa_struct = 5 // Fails here //setMetadata ret 0u mdnode let myMDName = "my_MD_kind" setMetadata ret (getMDKindID myMDName (uint32 myMDName.Length)) (mdNode [|mdstring|]) // Save bitcode to file writeBitcodeToFile module_ "metadatatest.bc" 

What gives the bitcode:

 ; ModuleID = 'metadatatest.bc' define i32 @main() { entry: ret i32 0, !my_MD_kind !0 } !0 = metadata !{metadata !"bazquux"} 

I used getMDKindID, not one of the predefined MD types, because when I used 0u, I did not get any metadata output. I did not think about why, but looking at http://llvm.org/docs/LangRef.html#metadata , it seems that the predefined types of metadata have some limitations that the instruction did not meet. Anyway, let me know if you see more problems with this. This is not part of the API that I am currently using, but I want it to work as best as possible.

+1
source

Source: https://habr.com/ru/post/1441376/


All Articles