Using Tools Properly (Analyzing Performance with LLVM Intermediates)
- Kiranbir Sodhia
- Apr 18, 2013
- 2 min read
I was looking at some code using a macro to read a uint32_t from a buffer received from a remote device. It looked something like this, give or take a few casts:
#define rd_uint32( p ) ( p[0] | ( p[1] << 8 ) | ( p[2] << 16 ) | ( p[3] << 24 ) )
uint32_t n = rd_uint32( buffer );At first I didn’t realize why the author overcomplicated this, as they could’ve just written something like below:
uint32_t n = *( (uint32_t *) buffer );It took me a while to realize they were writing endian-independent code. So I started questioning why we didn’t use the built-in EndianU32_BtoN or EndianU32_LtoN, and whether the compiler was smart enough to know it could perform a direct access based on the endianess of the host. I wrote two small programs with each snippet and tried to disassemble them. Since I recently transitioned to clang, I was trying to find equivalent commandline options as gcc -S. I kept on getting LLVM intermediates and eventually saw the disassembly was the same. It then hit me to check what was actually in the LLVM intermediate. What I found was an easily readable, architecture-indpendent code listing. Both snippets of course had the same listing.
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-S128"
target triple = "x86_64-apple-macosx10.8.2"
define i32 @main(i32 %argc, i8** nocapture %argv) nounwind uwtable ssp {
%n = alloca i32, align 4
store volatile i32 19088743, i32* %n, align 4
ret i32 0
}So I learned a lesson. When you’re transitioning to new tools like clang or lldb, or just trying to find a git command equivalent to the svn command you are used to, take a step back. There’s a reason why people designed these tools differently from their predecessors, and it might be beneficial to you. In this case, LLVM showed me what I wanted without having to dive into bare-knuckle assembly code.
You can find more information on the LLVM language at http://llvm.org/docs/LangRef.html.


Comments