LLVM: Updating a Data structure at runtime - c++

I want to store data about each stack memory that is being allocated and changed.
To do so, I thought I'd need a data structure of some sort in which I can store the related data, such as the value of the local variable, and any change of it, e.g. before a store instruction.
Moreover, I should be able to check the value with the one saved in the data structure before any read of the local variable (e.g. load instruction).
If we assume that the IR looks like this
%1 = alloca i32,
[...]
%20 = store i32 0, %1
I need to change the above code to look like the below
%18 = call __Checking
%19 = <storing the return value from __Checking into a data structure>
%20 = store i32 0, %1
My problem is I cannot figure out how to store the returned value from the library called __Checking into a StructType I defined at the beginning.
My relevant code
if (StoreInst *SI = dyn_cast<StoreInst>(&I)){
Value* newValue = IRB.CreateCall(....);
Type* strTy[] = { Type::getInt64Ty(m.getContext()),
Type::getInt64Ty(m.getContext()) };
Type* t = StructType::create(strTy);
}

You didn't provide any specific information on the type returned by __Checking (or even where does __Checking come from) and the internals of the StructType, so I'm going to suggest to abstract that behaviour away in a runtime library (most likely in C).
This will allow you to setup function calls in those parts of the IR that you require to store (or compare, etc.) a value. The function(s) would take as arguments the value and the StructType (and anything else required) and perform the desired action in plain C (e.g. store the value).
For example, using part of your posted IR (names prefixed with myruntime_ should be defined in your runtime library):
%0 = alloca %myruntime_struct
[...]
%18 = call #__Checking
%19 = call #myruntime_storevalue(%2, %18, /* other arguments? */)
%20 = store i32 0, %1

Related

Adding instrumentation to perform a null check in LLVM IR when dereferencing a pointer

I am writing an LLVM pass where I want to print out the values of function arguments. I am only focusing on integers and pointers to integers (which will also involve char, I guess but that is not a problem for my purposes). If the argument is a pointer, I want to dereference it and print the value that is pointed to by the pointer. To guard against null pointers, in normal C code I can do:
function foo(int* bar, int** baz) {
if (bar) {
printf("bar: %d\n", *bar);
}
if (baz) {
printf("baz: %d\n", **baz);
}
}
Is there a way to do something similar in LLVM? Currently I am doing the following to actually load the value by dereferencing the pointer. I am working off a StoreInst that LLVM generates to set up the values of function parameters. For example, for the function above, there would be something like:
%bar.addr = alloca i32*, align 8
%baz.addr = alloca i32**, align 8
store i32* %bar, i32** %bar.addr, align 8
store i32** %baz, i32*** %baz.addr, align 8
So using that StoreInst, I am doing something like this:
auto *value = store->getValueOperand();
auto *type = value->getType();
int indirection = 0;
while (type->isPointerTy()) {
indirection++;
type = type->getPointerElementType();
}
Value* load = value;
unsigned int bitWidth = type->getIntegerBitWidth(); // I have already verified earlier on that
// this eventually resolves to an IntegerType
while (indirection > 0) {
load = (indirection == 1) ? irb.CreateLoad(getIntegerType(bitWidth), load)
: irb.CreateLoad(getPointerToIntegerType(indirection - 1, bitWidth), load);
--indirection;
}
value = load;
The getIntegerType is just a convenience function that returns an IntegerType with the provided bit-width and using the current LLVM context. The getPointerToIntegerType function is as follows:
Type* getPointerToIntegerType(int indirection, unsigned int bitWidth) {
Type* type = getIntegerType(bitWidth);
while (indirection > 0) {
type = PointerType::get(type, 0);
--indirection;
}
return type;
}
Using this I get the following load instructions after the store instructions (I've omitted some stuff from the call instructions for brevity):
store i32* %bar, i32** %bar.addr, align 8
%1 = load i32, i32* %bar
call void (i8, ...) #__print_argument_value(...)
store i32** %baz, i32*** %baz.addr, align 8
%2 = load i32*, i32** %baz
%3 = load i32, i32* %2
call void (i8, ...) #__print_argument_value(...)
This works perfectly as long as the pointers are not null. Is there an easy way I can generate IR to guard the call to __print_argument_value? I did write out an explicit if (bar) { ... } and a if (baz) { ... } and then looked at the generated IR to see how LLVM generates it. I saw that it performs an icmp ne of the pointer (the .addr variable) against null. Then if the result is true, it breaks to a label if.then where it calls the function, or else to the label if.end which skips over it.
The problem is that I'm having a hard time trying to figure out how I can generate IR like that from my LLVM pass. Are there any examples I can look at? I did look up the documentation but I still can't figure out how to put the pieces together using the LLVM API even though I know what the IR should look like. I saw some documentation about to PHI nodes which I don't see in my IR from the explicit null check, but I am not entirely clear on what they are and how they would help me.
PS: Please excuse any weirdness in the C/C++ code; I usually program in Java.

LLVM IR: How to get size of array, in llvm ir-code, when passed as argument to function?

I have a function that takes an array as argument and I need to get the size of the array first thing in the function. I need to do this in LLVM IR. Is this possible? I can access the array but I don't know the size.
void test(int[] a) {
}
is right now translating to
define void #test(i32* %__p__a) {
entry:
%a = alloca i32*, align 4
store i32* %__p__a , i32** %a, align 4
ret void
}
I need to get the size of the array first thing in the function. I need to do this in LLVM IR. Is this possible?
If all you have is an i32* with no additional information about what it points to, then no, it's not possible. In order to get an array's size, you'll need to store that information somewhere where the test function can access it.
Since this is your own language and you control what the generated LLVM IR looks like, you could for example represent arrays as structs that contain the array's size and a pointer to the data.

LLVM store operand must be a pointer

I'm trying to store the value of a global variable into a local variable in a function in my custom LLVM Pass.
the global variable is defined as
GlobalVariable* gvar_int32_test = new GlobalVariable(
/*Module=*/ M,
/*Type=*/ IntegerType::get(M.getContext(), 32),
/*isConstant=*/ false,
/*Linkage=*/ GlobalValue::CommonLinkage,
/*Initializer=*/0, // has initializer, specified below
/*Name=*/"global_test_var");
gvar_int32_test->setAlignment(4);
The local variable I intend to store into is originally being used as the store location for a call instruction. I attempt to get this value using
Value* localVar = ci->getOperand(0) //ci is the call instruction
using an IR builder, I attempt to write a store instruction as:
StoreInst* strLocIns = builder.CreateStore(gvar_int32_test, localVar, false);
//my intent is to create an instruction that means localvar = globalvar;
Similarly, earlier in the code I attempt to store the value in the return instruction of a called function to the global variable
Value* value = ri->getReturnValue(); //ri is the return instruction
// Some more code, including setting the IR builder insertion point
StoreInst* strIns = builder.CreateStore(value, gvar_int32_test, false);
//here the intention is globalvar = localvar
when I try to compile my with my pass included, I get the error:
Store operand must be a pointer.
store i32* #global_test_var, i32 %5
I'm not sure what I am doing wrong. Both of the arguments for the variables that I pass to the IR builder are pointers, but the IR is somehow broken. I think that i32 %5 should be i32* %5 to indicate that %5 points to an i32, but I don't know how to fix my code to make that happen. How do I fix this error?
Swap the operands of store: first is what and second - where.

Get pointer to llvm::Value previously allocated for CreateLoad function

I'm new to llvm and I'm writing a small llvm IR Builder.
I use the IRBuilder and all these Create* functions to generate my IR.
What I'm trying to do is to create a load instruction which create a new SSA local variable with value of a previously allocated llvm::Value.
What I expected to have :
%2 = load i32* %1
With %2 results of load instruction and %1 my previously allocated Value (CreateAlloca)
Here is what I tried :
// Get Ptr from Val
Value* ptr = ConstantExpr::getIntToPtr((Constant*)loc[n],PointerType::getUnqual(builder->getInt32Ty()));
// Générate load instruction with the new Ptr
builder->CreateLoad(ptr);
And here is what I have :
%2 = load i32* null
loc is an array which contains all my llvm::Value*
Can you please tell me what I'm doing wrong ? Or maybe if I'm on a bad way ?
Thanks.
ConstantExpr::getIntToPtr() creates a constant expression. So in effect, what you're trying to generate is equivalent to this IR:
%2 = load i32* inttoptr (i32 %1 to i32*)
But this is illegal since a constant expression, as hinted by its name, only supports constants, and %1 isn't a constant. ConstantExpr::getIntToPtr() requires a Constant as a first argument to verify it, but you passed it a non-constant value which was forcefully cast to a constant.
The correct way to convert a non-constant integer to a pointer is with IRBuilder::createIntToPtr. However, since you say the previous value (loc[n]) was created via an alloca then it's already a pointer, and you don't need to perform any conversion: just do builder->CreateLoad(loc[n]).
By the way, the proper way to cast a Value to a Constant in LLVM is not via a c-style cast but via cast<>, like so: cast<Constant>(loc[n]).

Emmiting llvm bytecode from clang: 'byval' attribute for passing objects with nontrivial destructor into a function

I have a source C++ code which I parse using clang, producing llvm bytecode. From this point I want to process the file myself...
However I encoudered a problem. Consider the following scenario:
- I create a class with a nontrivial destructor or copy constructor.
- I define a function, where an object of this class is passed as a parameter, by value (no reference or pointer).
In the produced bytecode, I get a pointer instead. For classes without the destructor, the parameter is annotated as 'byval', but it is not so in this case.
As a result, I cannot distinguish if the parameter is passed by value, or really by a pointer.
Consider the following example:
Input file - cpass.cpp:
class C {
public:
int x;
~C() {}
};
void set(C val, int x) {val.x=x;};
void set(C *ptr, int x) {ptr->x=x;}
Compilation command line:
clang++ -c cpass.cpp -emit-llvm -o cpass.bc; llvm-dis cpass.bc
Produced output file (cpass.ll):
; ModuleID = 'cpass.bc'
target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64"
target triple = "x86_64-unknown-linux-gnu"
%class.C = type { i32 }
define void #_Z3set1Ci(%class.C* %val, i32 %x) nounwind {
%1 = alloca i32, align 4
store i32 %x, i32* %1, align 4
%2 = load i32* %1, align 4
%3 = getelementptr inbounds %class.C* %val, i32 0, i32 0
store i32 %2, i32* %3, align 4
ret void
}
define void #_Z3setP1Ci(%class.C* %ptr, i32 %x) nounwind {
%1 = alloca %class.C*, align 8
%2 = alloca i32, align 4
store %class.C* %ptr, %class.C** %1, align 8
store i32 %x, i32* %2, align 4
%3 = load i32* %2, align 4
%4 = load %class.C** %1, align 8
%5 = getelementptr inbounds %class.C* %4, i32 0, i32 0
store i32 %3, i32* %5, align 4
ret void
}
As you can see, the parameters of both set functions look exactly the same. So how can I tell that the first function was meant to take the parameter by value, instead of a pointer?
One solution could be to somehow parse the mangled function name, but it may not be always viable. What if somebody puts extern "C" before the function?
Is there a way to tell clang to keep the byval annotation, or to produce an extra annotation for each function parameter passed by a value?
Anton Korobeynikov suggests that I should dig into clang's LLVM IR emission. Unfortunately I know almost nothing about clang internals, the documentation is rather sparse. The Internals Manual of clang does not talk about IR emission. So I don't really know how to start, where to go to get the problem solved, hopefully without actually going through all of clang source code. Any pointers? Hints? Further reading?
In response to Anton Korobeynikov:
I know more-or-less how C++ ABI looks like with respect of parameter passing. Found some good reading here: http://agner.org./optimize/calling_conventions.pdf. But this is very platform dependent! This approach might not be feasable on different architectures or in some special circumstances.
In my case, for example, the function is going to be run on a different device than where it is being called from. The two devices don't share memory, so they don't even share the stack. Unless the user is passing a pointer (in which case we assume he knows what he is doing), an object should always be passed within the function-parameters message. If it has a nontrivial copy constructor, it should be executed by the caller, but the object should be created in the parameter area as well.
So, what I would like to do is to somehow override the ABI in clang, without too much intrusion into their source code. Or maybe add some additional annotation, which would be ignored in a normal compilation pipeline, but I could detect when parsing the .bc/.ll file. Or somehow differently reconstruct the function signature.
Unfortunately, "byval" is not just "annotation", it's parameter attribute which means a alot for optimizers and backends. Basically, the rules how to pass small structs / classes with and without non-trivial functions are government by platform C++ ABI, so you cannot just always use byval here.
In fact, byval here is just a result of minor optimization at frontend level. When you're passing stuff by value, then temporary object should be constructed on stack (via the default copy ctor). When you have a class which is something POD-like, then clang can deduce that copy ctor will be trivial and will optimize the pair of ctor / dtor out, passing just the "contents".
For non-trivial classes (like in your case) clang cannot perform such optimization and have to call both ctor and dtor. Thus you're seeing the pointer to temporary object is created.
Try to call your set() functions and you'll see what's going there.