How to you add platform specific function definitions in LLVM pass?

Viewed 220

I was trying to add a function declaration for something provided by the system.
However, the function prototype returns size_t, which is int32 on 32bit platform and int64 on 64bit platform.
I'd like to know if there is a method to detect target platform and add the declaration accordingly?

1 Answers

After a bit of research, LLVM IR as a target neutral language cannot possibly know target-specific type sizes. Have a look at this relevant discussion where Chris Lattner comments on the subject. Also, at this relevant SO question.

So, this is the job of the front-end and this causes extra bookkeeping information that front-ends need to "know" for a target and its ABI. So, for example, you might have needs for projects like this in the case of the Loci programming language.

Now, specifically for size_t according to this:

[...] std::size_t can safely store the value of any non-member pointer, in which case it is synonymous with std::uintptr_t.

So, you could use the getIntPtrType method of DataLayout class.

For any other data types, I'm not sure how far "guessing" can get you (probably not very far judging from the previous references).

Lastly, another alternative could be extending LLVM with a custom intrinsic (see memcpy for example), which inevitably goes through specific definition per target.


For actually adapting your integer type creation you could use the sizeof operator along with the use of CHAR_BIT, in order to provide the correct number of bits in the getIntNType call.

This will get you as far as using the right size for integer type on the platform where your module pass is built on.

For detecting a type's size 'dynamically' on the platform where your pass is being run, I know of none other way than providing that info in some sort of configuration file.

However, this can be automated and using the example of various build systems (e.g. cmake which is also used by LLVM), you can craft a simple program that can be compiled and automate that generation.

To that end, and to make this as portable as possible and avoid reinventing the wheel, you can use cmake's CheckTypeSize module.

Related