LLVM. How to access to struct fields based on their names? - llvm

I have little example code in C++:
struct RecordTest
{
int value1;
int value2;
};
void test()
{
RecordTest rt;
rt.value1 = 15;
rt.value2 = 75;
}
and LLVM 3.4 IR for it:
%struct.RecordTest = type { i32, i32 }
; Function Attrs: nounwind
define void #_Z4testv() #0 {
entry:
%rt = alloca %struct.RecordTest, align 4
%value1 = getelementptr inbounds %struct.RecordTest* %rt, i32 0, i32 0
store i32 15, i32* %value1, align 4
%value2 = getelementptr inbounds %struct.RecordTest* %rt, i32 0, i32 1
store i32 75, i32* %value2, align 4
ret void
}
and a pretty easy question: How can I access to RecordTest fields (when I parsing .cpp), without their indexes, with only names (value1 and value2)?
I know only one way (from llc -march=cpp) - with indexes:
AllocaInst* ptr_rt = new AllocaInst(StructTy_struct_RecordTest, "rt", label_entry);
ptr_rt->setAlignment(4);
std::vector<Value*> ptr_value1_indices;
ptr_value1_indices.push_back(const_int32_6);
ptr_value1_indices.push_back(const_int32_6);
Instruction* ptr_value1 = GetElementPtrInst::Create(ptr_rt, ptr_value1_indices, "value1", label_entry);
StoreInst* void_9 = new StoreInst(const_int32_7, ptr_value1, false, label_entry);
void_9->setAlignment(4);
std::vector<Value*> ptr_value2_indices;
ptr_value2_indices.push_back(const_int32_6);
ptr_value2_indices.push_back(const_int32_5);
Instruction* ptr_value2 = GetElementPtrInst::Create(ptr_rt, ptr_value2_indices, "value2", label_entry);
StoreInst* void_10 = new StoreInst(const_int32_8, ptr_value2, false, label_entry);
void_10->setAlignment(4);
So, can I translate from C++ to LLVM IR, if I don't know the indexes of the fields (const_int32_5 and const_int32_6 in code above) ?
UPD================================
So, we can't access to field names. And if we need it (and we do, if we parse .cpp),
we can write something like this:
// It can be some kind of singletone
static std::map<std::string, std::vector<std::string>> mymap;
// Some function, where we first time meet RecordTest
std::vector<std::string> fieldNames;
fieldNames.push_back("value1");
fieldNames.push_back("value2");
mymap["RecordTest"] = fieldNames;
// Some function, where we need to access to RecordTest field
std::vector<std::string> fieldNamesAgain = mymap.find("RecordTest")->second;
std::string fieldName = "value1";
int idxValue1 = -1;
for (int i = 0, e = fieldNamesAgain.size(); i < e; i++) // little ugly search
{
if (fieldName == fieldNamesAgain[i])
{
// we get field index, and now we can build code
// as in example above (llc -march=cpp)
idxValue1 = i;
break;
}
}
Is this right ?

You cannot access the fields of the struct by name, only by index. This information is just normally not there when you compile with Clang.
There is one exception to this, and this is if you compiled with debug information. In that case, you'll have ample data about the type; specifically, you'll get the order of the fields, along with a metadata entry for each field which contains its name (and other useful stuff, such as its offset from the beginning of the type).
Read more about this on the Source Level Debugging guide - and particularly, see this section about struct encoding, with its very nice example.
Take a look at DebugInfo.h for classes to help on querying debug info, though I think you're going to have to do some manually digging anyway.

Related

Acquiring the name(or the number) of the debug info in LLVM-IR

I want to print the exact number of the debug information in IR, how could I do it?
For example, consider an IR chunk as below,
call void #llvm.dbg.declare(metadata i32* %a, metadata !10, metadata !11), !dbg !12!
!12 = !DILocation(line: 19, column: 7, scope: !6)
I want to print the !12 as a string for debugging purpose. I can acquire the object of DILocation by doing
Instruction::getDebugLoc()->get()
but all I get is a pointer and there is no such interface for acquiring the number. I can assume that LLVM gives the number when it is actually generating the bitcode, since dumping the DILocation gives a result something like
<0x7342628> = !DILocation(line: 23, column: 3, scope: <0x733e5f8>)
this. But when I use Instruction::dump(), it gives me something that looks like
call void #llvm.dbg.declare(metadata i32* %a, metadata !10, metadata !11), !dbg !12
this, So I am confused whether it has the numbering information of a debug-info or not during runtime.
Does it have the numbering information or not? If so, how can I acquire that info? If not, where should I inspect to look for the generation of the bitcode in LLVM?
Are you talking about line/column numbers? If so, then you can easily access them directly from the debugLoc:
instruction->getDebugLoc()->getLine()
instruction->getDebugLoc()->getColumn()
See the definition at DebugInfoMetadata:
unsigned getLine() const { return SubclassData32; }
unsigned getColumn() const { return SubclassData16; }
It is probably not too late to answer this question.
if (instruction->hasMetadata()) {
instruction->dump();
// one way
SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
instruction->getAllMetadata(MDs);
for (auto &MD : MDs) {
if (MDNode *N = MD.second) {
N->printAsOperand(errs(), instruction->getModule());
errs() << "\n";
}
}
// second way
instruction->getDebugLoc()->printAsOperand(errs(), instruction->getModule());
errs() << "\n";
// third way
int debugInfoKindID = 0;
MDNode *debug = instruction->getMetadata(debugInfoKindID);
debug->printAsOperand(errs(), instruction->getModule());
errs() << "\n";
}
Output is:
%11 = add nsw i32 %9, %10, !dbg !29
!29
!29
!29
I found this by looking at llvm//unittests/IR/MetadataTest.cpp, its test TEST_F(MDNodeTest, PrintFromMetadataAsValue).

LLVM error: invalid redefinition of function

I'm writing a LLVM IR generator for a pseudo code language. This language should allow redefinition of function.
Here is one case that I have two functions both named "f" but they have different parameters.
function f(int i, float r) returns int { return i; }
function f(float r, float r2) returns int {return i; }
I thought LLVM could distinct that, but I get
error: invalid redefinition of function
And the code I generated is:
define i32 #f(i32 %i, float %r) {
%var.i.0 = alloca i32
store i32 %i, i32* %var.i.0
%var.r.1 = alloca float
store float %r, float* %var.r.1
%int.2 = load i32* %var.i.0
ret i32 %int.2
; -- 0 :: i32
%int.3 = add i32 0, 0
ret i32 %int.3
}
define i32 #f(float %r, float %r2) {
%var.r.2 = alloca float
store float %r, float* %var.r.2
%var.r2.3 = alloca float
store float %r2, float* %var.r2.3
%var.i.4 = alloca i32
%float.3 = load float* %var.r.2
%int.7 = fptosi float %float.3 to i32
store i32 %int.7, i32* %var.i.4
%int.8 = load i32* %var.i.4
ret i32 %int.8
; -- 0 :: i32
%int.9 = add i32 0, 0
ret i32 %int.9
}
So, I think LLVM do not allow function overloading? Then is it a good idea that I generate a sequential counter, and distinct all these functions by adding this sequential counter as a suffix i.e define i32 #f.1() and define i32 #f.2()?
You're correct that LLVM IR doesn't have function overloading.
Using a sequential counter is probably not a good idea depending on how code in your language is organized. If you're just assigning incrementing integers, those may not be deterministic across the compilation of different files. For example, in C++, you might imagine something like
// library.cpp
int f(int i, float r) { ... }
int f(float r, float r2) { ... }
// user.cpp
extern int f(float r, float r2);
int foo() { return f(1.0, 2.0); }
When compiling user.cpp, there would be no way for the compiler to know that the f being referenced will actually be named f.2.
The typical way to implement function overloading is to use name mangling, somehow encoding the type signature of the function into its name so that it'll be unique in the presence of overloads.
My generator was written in java, so every time I parse a function definition, I will increase the counter for the same function name if the function name has already existed in the scope table.
My table is defined by Map with function name as key, and a list of function def as value:
Map<String,ArrayList<functionSymbol>> = new HashMap<>();
and then the constructor will look like:
static int counter = 0;
public FunctionSymbol(String functionName, Type retType, List<Variable> paramList){
this.functionName = functionName+counter;
this.paramList = paramList;
this.retType = retType;
counter++;
}

LLVM IR - Can someone explain this behavior?

I'm trying to build a compiler for my language at the moment. In my language, I want to have implicit pointer usage for objects/structs just like in Java. In the program below, I am testing out this feature. However, the program does not run as I had expected. I do not expect you guys to read through my entire compiler code because that would be a waste of time. Instead I was hoping I could explain what I intended for the program to do and you guys could spot in the llvm ir what went wrong. That way, I can adjust the compiler to generate proper llvm ir.
Flow:
[Function] Main - [Return: Int] {
-> Allocates space for structure of one i32
-> Calls createObj function and stores the returning value inside previous allocated space
-> Returns the i32 of the structure
}
[Function] createObj - [Return: struct { i32 }] {
-> Allocates space for structure of one i32
-> Calls Object function on this space (pointer really)
-> Returns this space (pointer really)
}
[Function] Object - [Return: void] {
-> Stores the i32 value of 5 inside of the struct pointer argument
}
The program is that main keeps returning some random number instead of 5. One such number is 159383856. I'm guessing that this is the decimal representation of a pointer address, but I'm not sure why it is printing out the pointer address.
; ModuleID = 'main'
%Object = type { i32 }
define i32 #main() {
entry:
%0 = call %Object* #createObj()
%o = alloca %Object*
store %Object* %0, %Object** %o
%1 = load %Object** %o
%2 = getelementptr inbounds %Object* %1, i32 0, i32 0
%3 = load i32* %2
ret i32 %3
}
define %Object* #createObj() {
entry:
%0 = alloca %Object
call void #-Object(%Object* %0)
%o = alloca %Object*
store %Object* %0, %Object** %o
%1 = load %Object** %o
ret %Object* %1
}
define void #-Object(%Object* %this) {
entry:
%0 = getelementptr inbounds %Object* %this, i32 0, i32 0
store i32 5, i32* %0
ret void
}
This llvm ir is generated from this syntax.
func () > main > (int) {
Object o = createObj();
return o.id;
}
// Create an object and returns it
func () > createObj > (Object) {
Object o = make Object < ();
return o;
}
// Object decl
tmpl Object {
int id; // Property
// This is run every time an object is created.
constructor < () {
this.id = 5;
}
}
It seems like in createObj you're returning a pointer to a stack variable which will no longer be valid after function return.
If you're doing implicit object pointers like Java at minimum you're going to need a call to a heap allocation like malloc which I don't think you have.

llvm: How to get the label of Basic Blocks

I have written a pass to detect and print the label of basicblocks in a function, for I want to use splitBasicBlock() further. I wrote that like this:
virtual bool runOnModule(Module &M)
{
for(Module::iterator F = M.begin(), E = M.end(); F!= E; ++F)
{
errs()<<"Function:"<<F->getName()<<"\n";
//for(Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (iplist<BasicBlock>::iterator iter = F->getBasicBlockList().begin();
iter != F->getBasicBlockList().end();
iter++)
{
BasicBlock* currBB = iter;
errs() << "BasicBlock: " << currBB->getName() << "\n";
}
}
return true;
}
IR file looks like this:
; <label>:63 ; preds = %43
%64 = load i32* %j, align 4
%65 = sext i32 %64 to i64
%66 = load i8** %tempdst, align 8
%67 = getelementptr inbounds i8* %66, i64 %65
store i8 -1, i8* %67, align 1
br label %73
; <label>:68 ; preds = %43
%69 = load i32* %j, align 4
%70 = sext i32 %69 to i64
%71 = load i8** %tempdst, align 8
%72 = getelementptr inbounds i8* %71, i64 %70
store i8 0, i8* %72, align 1
br label %73
; <label>:73 ; preds = %68, %63
br label %74
However, I got nothing about the label:
Function:main
BasicBlock:
BasicBlock:
BasicBlock:
What's wrong with these "unnamed" basic block? What should I do?
While BasicBlocks may be with no name (as indicated by hasName() method) one may print unique BasicBlock identifier by using currBB->printAsOperand(errs(), false) instead of streaming into errs() the value of currBB->getName(). For unnamed BasicBlock this would provide the numerical basic block representation, such as %68 .
Values in LLVM IR are not required to have a name; and indeed, those basic blocks don't have names, which is why you get an empty string from currBB->getName().
The reason that they have names in the LLVM IR printout is because when you print to the textual format of LLVM IR (as it appears in .ll files), you have to assign a name to them to make them referable, so the printer assigns sequential numeric names to basic blocks (and other values). Those numeric names are only created by the printer, though, and don't actually exist in the module.
While compiling source code to bitcode using clang use the below flag
-fno-discard-value-names
You will get the name of basic block as a unique string
I think the behavior of LLVM now is different.
I use similar lines of code and can get the label's name on LLVM-4.0
for (auto &funct : m) {
for (auto &basic_block : funct) {
StringRef bbName(basic_block.getName());
errs() << "BasicBlock: " << bbName << "\n";
}
}
As ElazarR said, currBB->printAsOperand(errs(), false) will print such ID in the error stream, but it is possible to store it in a string as well if this is more interesting to your logic.
In the LLVM CFG generation pass -dot-cfg, they always name the basic block using the BB's name (if any) or its representation as a string. This logic is present in the CFGPrinter.h header (http://llvm.org/doxygen/CFGPrinter_8h_source.html#l00063):
static std::string getSimpleNodeLabel(const BasicBlock *Node,
const Function *) {
if (!Node->getName().empty())
return Node->getName().str();
std::string Str;
raw_string_ostream OS(Str);
Node->printAsOperand(OS, false);
return OS.str();
}
You can use this logic to always return a valid name for the basic block.

LLVM extract i8* out of structure value

I'm writing a compiler using LLVM as a backend, I've written the front-end (parser, etc.) and now I've come to a crossroads.
I have a structure (%Primitive) which contains a single field, an i8* value, a pointer to a character array.
%Primitive = type { i8* }
In the compiler, instances of Primitive are passed around on the stack. I'm trying to write this character array to standard output using the puts function, but it isn't working quite like I was hoping.
declare i32 #puts(i8*) ; Declare the libc function 'puts'
define void #WritePrimitive(%Primitive) {
entry:
%1 = extractvalue %Primitive %0, 0 ; Extract the character array from the primitive.
%2 = call i32 #puts(i8* %1) ; Write it
ret void
}
When I try to run the code (either using an ExecutionEngine or the LLVM interpreter program lli), I get the same error; a segmentation fault.
The error lies in the fact that the address passed to puts is somehow the ASCII character code of the first character in the array. It seems the address passed, rather than being a pointer to an array of 8 bit chars, is instead an 8 bit wide pointer that equals the dereferenced string.
For example, if I call #WritePrimitive with a primitive where the i8* member points to the string "hello", puts is called with the string address being 0x68.
Any ideas?
Thanks
EDIT: You were right, I was initializing my Primitive incorrectly, my new initialization function is:
llvm::Value* PrimitiveHelper::getConstantPrimitive(const std::string& str, llvm::BasicBlock* bb)
{
ConstantInt* int0 = ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0);
Constant* strConstant = ConstantDataArray::getString(getGlobalContext(), str, true);
GlobalVariable* global = new GlobalVariable(module,
strConstant->getType(),
true, // Constant
GlobalValue::ExternalLinkage,
strConstant,
"str");
Value* allocated = new AllocaInst(m_primitiveType, "allocated", bb);
LoadInst* onStack1 = new LoadInst(allocated, "onStack1", bb);
GetElementPtrInst* ptr = GetElementPtrInst::Create(global, std::vector<Value*>(2,int0), "", bb);
InsertValueInst* onStack2 = InsertValueInst::Create(onStack1, ptr, std::vector<unsigned>(1, 0), "", bb);
return onStack2;
}
I missed that, Thank You!
There's nothing wrong with the code you pasted above; I just tried it myself and it worked fine. I'm guessing the issue is that you did not initialize the pointer properly, or did not set it properly into the struct.
The full code I used is:
#str = private unnamed_addr constant [13 x i8] c"hello world\0A\00"
; Your code
%Primitive = type { i8* }
declare i32 #puts(i8*) ; Declare the libc function 'puts'
define void #WritePrimitive(%Primitive) {
entry:
%1 = extractvalue %Primitive %0, 0 ; Extract the character array from the primitive.
%2 = call i32 #puts(i8* %1) ; Write it
ret void
}
; /Your code
define void #main() {
%allocated = alloca %Primitive
%onstack1 = load %Primitive* %allocated
%onstack2 = insertvalue %Primitive %onstack1, i8* getelementptr ([13 x i8]* #str, i64 0, i64 0), 0
call void #WritePrimitive(%Primitive %onstack2)
ret void
}