5

I'm trying to add a metadata string to my LLVM module. The stripped down version of what I'm trying is

#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Metadata.h>

using namespace llvm;

int main() {
    Module* module = new Module("test", getGlobalContext());
    MDString::get(module->getContext(), "test");
    module->dump();
}

I can compile and run it:

Desktop% g++ llvm.cc -o llvm `llvm-config --cppflags --ldflags --libs all`
Desktop% ./llvm 
; ModuleID = 'test'

But as one can see, the metadata does not show up.

Can I somehow add the string to the module? The module itself only seems to offer access to named metadata. Now I don't know where else I could look. Any suggestions?

Supplement: I got the feeling that you can't just have a metadata string "floating around" in your module, it seems like you have to add it to a named metadata node. Is that right?

Thomas Schaub
  • 418
  • 2
  • 9

1 Answers1

4

Try this:

#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Metadata.h>

using namespace llvm;

int main() {
  Module* module = new Module("test", getGlobalContext());

  Value *Elts[] = {
    MDString::get(module->getContext(), "test1")
  };
  MDNode *Node = MDNode::get(getGlobalContext(), Elts);

  NamedMDNode *NMD = module->getOrInsertNamedMetadata("test2");
  NMD->addOperand(Node);

  module->dump();
}

I am not sure if you are able to have metadata "floating around" as you say. If it's not attached to any part of your program then what good is it doing? I've been looking into MD a bit lately... I found similar code in lib/Analysis/DIBuilder.cpp. Good luck.

laprej
  • 138
  • 1
  • 5
  • Thank you, this looks good. I thought I could just attach it to the module, but if I think about it its clear: If it doesn't have a name, how can I find it at later stages? – Thomas Schaub Aug 09 '11 at 08:43