how to use llvm intrinsics #llvm.read_register? - llvm

I noticed that llvm.read_register() could read the value of stack pointer, as well as llvm.write_register() could set the value of stack pointer. I add main function to the stackpointer.ll which could be found in the llvm src:
;stackpointer.ll
define i32 #get_stack() nounwind {
 %sp = call i32 #llvm.read_register.i32(metadata !0)
 ret i32 %sp
}
declare i32 #llvm.read_register.i32(metadata) nounwind
!0 = metadata !{metadata !"sp\00"}
define i32 #main() {
 %1 = call i32 #get_stack()
 ret i32 %1
}
I tested on an armv7 board running ubuntu 11.04:
lli stackpointer.ll
then, I get a stack dump:
ARMCodeEmitter::emitPseudoInstruction
UNREACHABLE executed at ARMCodeEmitter.cpp:847!
Stack dump:
0.  Program arguments: lli stackpointer.ll
1.  Running pass 'ARM Machine Code Emitter' on function '#main'
Aborted
I also tried llc:
llc stackpointer.ll -o stackpointer.s
The error messege:
Can't get register for value!
UNREACHABLE executed at ARMCodeEmitter.cpp:1183!
Stack dump:
0.  Program arguments: llc stackpointer.ll -o stackpointer.s
1.  Running pass 'Function Pass Manager' on moulude 'stackpointer.ll'
2.  Running pass 'ARM Instruction Selection' on function '#get_stack'
Aborted
I also tried on x86-64 platform, it didn't work. What is the correct way to use these intrinsics?

My lli didn't like your metadata definition.
I cnagned your
!0 = metadata !{metadata !"sp\00"}
to
!0 = !{!"sp\00"}
And it worked. (Well, since I'm on x86-64, I have also changed everywhere i32 to i64 and sp to rsp).
Plus there were bad whitespace symbols in your formatting, but I think it might be due to StackOverflow/html or something).

Related

what llvm store instruction pattern do i need?

im trying to make an llvm backend and i dont know what i need to fix this error
LLVM ERROR: Cannot select: t5: ch = store<ST4[%retval]> t0, Constant:i32<0>, FrameIndex:i64<0>, undef:i64
this is the ir im trying to process
define i32 #main() #0 {
%retval = alloca i32, align 4
store i32 0, i32* %retval, align 4
ret i32 0
}
but i don't know what dag pattern i need to be able to match it.
a tablegen file that contains some of the instructions my arch supports is here https://github.com/jfmherokiller/customllvm/blob/master/llvm/lib/Target/ZCPU/zcpuInstr.td
i just figured out the issue i was looking at the issue wrong
store<ST4[%retval]> t0, Constant:i32<0>, FrameIndex:i64<0>, undef:i64
can be expessed in function form as store(Constant:i32<0>,FrameIndex:i64<0>) or store constant i32 0 in
stack frame index 0.
The information i wasnt getting was that FrameIndex:i64<0> directly related to this line in TargetSelectionDAG.td def frameindex :SDNode<"ISD::FrameIndex",SDTPtrLeaf, [],"FrameIndexSDNode">;
so FrameIndex = frameindex

Printf float with LLVM segfaults

I am trying to call printf to print a float number from LLVM. While it works fine with int, it segfaults when using double.
Here is the code (generated from clang but slightly modified so that it works fine with llc) :
#.str = private unnamed_addr constant [3 x i8] c"%f\00", align 1
; Function Attrs: nounwind uwtable
define i32 #main() #0 {
%1 = alloca i32, align 4
store i32 0, i32* %1
%2 = call i32 (i8*, ...)* #printf(i8* getelementptr inbounds ([3 x i8]* #.str, i32 0, i32 0), double 3.140000e+00)
ret i32 0
}
declare i32 #printf(i8*, ...) #1
attributes #0 = { nounwind uwtable "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+sse,+sse2" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+sse,+sse2" "unsafe-fp-math"="false" "use-soft-float"="false" }
Here is how I produce an executable:
llc main.ll --filetype=obj
ld -lc -e main -dynamic-linker /lib64/ld-linux-x86-64.so.2 main.o -o main
When I run main within valgrind, I get:
Process terminating with default action of signal 11 (SIGSEGV): dumping core
General Protection Fault
I read somewhere on this site that I need to align the stack to use printf.
If this is the issue, how can I do this in LLVM.
Otherwise, what is causing this segfault?
I run Linux 64-bits.
This is NOT llvm issue.
when you ran,
llc main.ll --filetype=obj
ld -lc -e main -dynamic-linker /lib64/ld-linux-x86-64.so.2 main.o -o main
here after creating objact file main.o you are trying to link it saying that main is its entry point for execution, which is not correct.
from the c programmer point of view main is the entry point for our program while execution which is not, some extra startup code is added by compiler which is _start, this is the function which is executed first and then interns call main function.
the startup code is relocatable objects and those are passed by compiler to linker. search for crti.o crtn.o and crt1.o, also the printf function is in library libc.so/libc.a which you need to provide while linking.
if you want the easy solution then use gcc for converting object files to executable
gcc main.o -o main
also you can have look here for more clarification,
ref http://blog.techveda.org/building-executables-with-gnu-linker/

Understanding how memory allocation works (LLVM)

I'm making progress on a toy compiler (first time), and trying to understand how to allocate/construct an LLVM struct type.
The Kaleidoscope tutorial doesn't include or even mention this and I don't know what I'm looking for in the LLVM source/tests to find possible examples.
So I've written a simply C++ example, dumped the IR with clang in an effort to try to understand what it produces but to be honest I don't follow it all. The things obvious to me are the function definition/declarations and some function calls and a memset call so I get pieces of it but it doesn't all come together for me yet. (P.S my interpretation of the alloca instruction docs is that it anything created from that gets freed on return so I can't use that right, it's essentially only for local variables?)
What I've done is:
alloc.cpp
struct Alloc {
int age;
};
//Alloc allocCpy() {
// return *new Alloc();
//}
Alloc *allocPtr() {
return new Alloc();
}
int main() {
Alloc *ptr = allocPtr();
// ptr->name = "Courtney";
// Alloc cpy = allocCpy();
// cpy.name = "Robinson";
// std::cout << ptr->name << std::endl;
// std::cout << cpy.name << std::endl;
return 0;
}
Then run clang -S -emit-llvm alloc.cpp to produce alloc.ll
; ModuleID = 'alloc.cpp'
target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.11.0"
%struct.Alloc = type { i32 }
; Function Attrs: ssp uwtable
define %struct.Alloc* #_Z8allocPtrv() #0 {
entry:
%call = call noalias i8* #_Znwm(i64 4) #3
%0 = bitcast i8* %call to %struct.Alloc*
%1 = bitcast %struct.Alloc* %0 to i8*
call void #llvm.memset.p0i8.i64(i8* %1, i8 0, i64 4, i32 4, i1 false)
ret %struct.Alloc* %0
}
; Function Attrs: nobuiltin
declare noalias i8* #_Znwm(i64) #1
; Function Attrs: nounwind
declare void #llvm.memset.p0i8.i64(i8* nocapture, i8, i64, i32, i1) #2
; Function Attrs: ssp uwtable
define i32 #main() #0 {
entry:
%retval = alloca i32, align 4
%ptr = alloca %struct.Alloc*, align 8
store i32 0, i32* %retval
%call = call %struct.Alloc* #_Z8allocPtrv()
store %struct.Alloc* %call, %struct.Alloc** %ptr, align 8
ret i32 0
}
attributes #0 = { ssp uwtable "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+cx16,+sse,+sse2,+sse3,+ssse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { nobuiltin "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="core2" "target-features"="+cx16,+sse,+sse2,+sse3,+ssse3" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #2 = { nounwind }
attributes #3 = { builtin }
!llvm.module.flags = !{!0}
!llvm.ident = !{!1}
!0 = !{i32 1, !"PIC Level", i32 2}
!1 = !{!"clang version 3.7.0 (tags/RELEASE_370/final)"}
Can someone explain what's happening in this IR and how it maps back to the C++? Or ignoring this specific example how one would/should go about allocating heap memory for an LLVM StructType that out lives the function within which it was created (and if you're feeling generous, how to later release the memory).
The bits I've commented out are from my original example but being a total novice the IR from that was even less insightful...
my interpretation of the alloca instruction docs is that it anything
created from that gets freed on return so I can't use that right, it's
essentially only for local variables?
Yes. Furthermore, the current advice on LLVM IR is that although alloca works as you expect it to, optimizations are another case. They advise that you alloca all of your locals in the entry block right away, even if you don't allow the user access to them or they don't always contain meaningful data.
Heap allocation is a library feature. It is not a feature of LLVM or the compiler. When you use new T(), the compiler simply calls operator new to get the memory and then constructs T there. There is no magic involved. Most of the junk that you see there is C++-ABI specific rather than any requirement of LLVM. It eventually lowers into something like void* p = malloc(size); new(p) T();. For pretty much all types T, this pretty much boils down to a series of stores into p or calling a user-defined function.
You can use the memory allocation function from the runtime library of your choice.
trying to understand how to allocate/construct an LLVM struct type
The LLVM type system does not include the notion of construction. That is a notion of the source language.
As far as LLVM is concerned, a struct is just a bunch of bits, and all memory locations are more-or-less the same. If you want the bits to be a particular thing, then store the bits you want to that location. If you want to put the bits on the heap, then call a runtime library heap allocation function and store the bits into that location.
Note that garbage collection, however, is a somewhat different story, as there is some awkward stuff going on w.r.t. finding locals on the stack for marking.
For the record, you will not get far trying to understand Clang's LLVM IR. I've been doing that for several years now and it is batshit crazy and will take you that long to start to get a grip, not to mention full of C++-specific ABI details that you don't want to know about. You will get a lot further asking in #llvm in their IRC channel or asking specific questions here than in trying to reverse-engineer that.
I don't recommend looking at unoptimized IR emitted by Clang - it's way too verbose. -O1 makes it a lot more readable - here's the -O1 version with comments annotating the lines (also I've reordered two lines to make it slightly more readable):
%struct.Alloc = type { i32 } ; Define the Alloc type.
define noalias %struct.Alloc* #_Z8allocPtrv() #0 {
%1 = tail call noalias i8* #_Znwj(i32 4) #2 ; Call _Znwj(4). This retuns i8*.
%3 = bitcast i8* %1 to i32* ; Cast the returned value to i32* (int*)...
store i32 0, i32* %3, align 4 ; ...and zero its content.
%2 = bitcast i8* %1 to %struct.Alloc* ; Cast the returned value to Alloc*...
ret %struct.Alloc* %2 ; ...and return it.
}
; Declare the _Znwj function. This doesn't need to be defined since it's already defined
; in libstdc++: this is 'operator new'. You can see this by passing this string through a
; C++ demangler, for example the one at http://demangler.com/.
declare noalias i8* #_Znwj(i32) #1
define i32 #main() #0 {
%1 = tail call %struct.Alloc* #_Z8allocPtrv() ; Call _Z8allocPtrv (Defined above).
ret i32 0
}
This is a new call, not a local allocation, so it will not be cleared when leaving #_Z8allocPtrv. Local allocations are indeed performed in LLVM IR with the alloca instruction, and not a new call.
If you're curious how new works, I believe its standard implementation uses malloc, which is translated by the compiler that compiled the library to some function that includes system call(s).

why it is asking for a token?

I've written a very simple llvm IR code. However when I try to run it through llc, I get the following error:
llc: add_test.ll:10:16: error: expected value token
%r = load i32, i32* %retval
^
Here is the code:
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-unknown-linux-gnu"
; Function Attrs: nounwind uwtable
define i32 #main() #0 {
entry:
%retval = alloca i32, align 4
store i32 0, i32* %retval
%r = load i32, i32* %retval
ret i32 0
}
attributes #0 = { nounwind uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.ident = !{!0}
!0 = metadata !{metadata !"clang version 3.5.0 "}
The command that i'm running is llc add-test.ll
Does anybody know what could be the problem?
The syntax for load (among others) was changed in LLVM version 3.7. The syntax you're using is the new one. Since you're using version 3.5, you need to use the old syntax, which is:
%r = load i32* %retval
In other words you only specify the type of the parameter, not of the result.
I assume the problem occurred because you're using the current version of the documentation while using an old version of LLVM. The documentation for LLVM 3.5.0 can be found here.

How can I add reference to a variable defined in previous function in LLVM IR?

I'm new to LLVM IR and I'm implementing PL0 language. http://en.wikipedia.org/wiki/PL/0
I'm generating the testfile as following:
const a = 10;
var b, c;
procedure check1;
var dd;
procedure check2;
c := 2;
begin
dd := 1
end;
begin
b := -1024+53*(-514-766)/93+100;
c := b
end.
And the LLVM IR I generated is like this:
; ModuleID = 'LLVM Module'
define void #__global_main_entry__() {
BlockUnitEntry:
%b = alloca i32
%c = alloca i32
store i32 -1653, i32* %b
%b1 = load i32* %b
store i32 %b1, i32* %c
ret void
}
define void #check1() {
ProcedureEntry:
%dd = alloca i32
store i32 1, i32* %dd
ret void
}
define void #check2() {
ProcedureEntry:
store i32 2, i32* %c
ret void
}
I got a painful error here (at destruction):
While deleting: i32* %c
Use still stuck around after Def is destroyed: store i32 2, i32* %c
test004_llvm_generate: /files/Install/LLVM_Framework/llvm/lib/IR/Value.cpp:79: virtual llvm::Value::~Value(): Assertion `use_empty() && "Uses remain when a value is destroyed!"' failed.
I guess that using variable c(defined in __global_main_entry__) in procedure check2 adds a ref in llvm::Value, when destructing __global_main_entry__ the ref at check2 is causing the error.
I do not know how to solve the problem, and if you have time to be specific, please~
(Moreover, except for the official documentation of llvm. Are there any more resources on LLVM? I found that most tutorials are outdated.)
My full list of code is here: https://github.com/adamcavendish/PL0Compiler
Thanks in advance.
Your IR is malformed - you cannot refer to an instruction from the body of a function different from the one in which the instruction appears, so referring to %c in #check2 is illegal. The failure just happened to occur during module destruction, but it can occur in other circumstances as well.
In general, I recommend running opt -verify on your IR if you're not sure it's legal, it will give you nice error messages. My Eclipse plugin might also help if you want to experiment with IR to see when it is and isn't legal.
As for a solution, it looks like you should create a global variable to represent c, not an instruction. Then you can store into it and load from it in every function in the module.