[LLVMdev] Annotating known pointer alignment

Clemens Hammacher hammacher at cs.uni-saarland.de
Sun Oct 28 05:52:43 PDT 2012


Hi all,

I'm instrumenting IR by replacing loads and stores by calls to a 
library, which I have compiled to bitcode such that inlining can take 
place. My problem is: If I could retain the alignment information on the 
load/store, this would open many optimization opportunities after 
inlining. Unfortunately, I don't know how.

After thinking about it, and trying different things, I now have several 
questions.

First, consider this function:
   #include <stdint.h>
   uint64_t foo(uint64_t *bar) {
     *bar = 42;
     return (uint64_t)bar & 3;
   }

Which is compiled to
   define i64 @foo(i64* %bar) nounwind uwtable ssp {
     store i64 42, i64* %bar, align 8
     %0 = ptrtoint i64* %bar to i64
     %and = and i64 %0, 3
     ret i64 %and
   }

1) How can clang deduce the alignment on the store? It emits a store 
without alignment information, and instcombine adds the explicit 
alignment according to the langref (pref alignment).

2) If we know that the store is aligned, shouldn't instcombine deduce 
that the pointer %bar itself must be aligned (set low bits in 
KnownZero), and use this information for other uses, at least those that 
are dominated by the store? This would fold the three instructions to 
"ret i64 0".

3) If instcombine cannot deduce it, is there a way to annotate that a 
specific pointer value is aligned? In my case it should work to add this 
sequence:
   %A = ptrtoint i64* %ptr to i64
   %B = and i64 %A, -8
   %C = inttoptr i64 %B to i64*
and replacing all uses of %ptr by %C, then running optimizations, and 
then replacing %C by %ptr again. But this is neither efficient nor nice, 
and optimizations could cause other instructions to use my dummy 
instructions too such that I cannot remove them afterwards.
Nick Lewycky once proposed to add an alignment field to ptrtoint (for 
bug 9120), following the principle that pointer uses know the alignment. 
That would also help for my example. After inlining, I could visit all 
uses of the pointer (load/store/ptrtoint) and add the alignment accordingly.

Also clang could set an alignment for ptrtoint, since it seems to know 
that some pointers are always aligned.

Thanks for any help to solve my problem or answer my questions!

Clemens



More information about the llvm-dev mailing list