Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

c - -O2 optimizes printf("%s ", str) to puts(str)

Toying around with clang, I compiled a C program containing this line:

printf("%s
", argv[0]);

When compiling without optimization, the assembly output called printf after setting up the registers:

movq    (%rcx), %rsi
movq    %rax, %rdi
movb    $0, %al
callq   _printf

I tried compiling with clang -O2. The printf call was replaced to a puts call:

movq    (%rsi), %rdi
callq   _puts

While this makes perfect sense in this case, it raises two questions:

  1. How often does function call substitution happen in optimized compilation? Is this frequent or is stdio an exception?
  2. Could I write compiler optimizations for my own libraries? How would I do that?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. How often does function call substitution happen in optimized compilation? Is this frequent or is stdio an exception?

The optimization that replaces printf with puts in LLVM is in the class LibCallSimplifier. You can see the header file in llvm/include/llvm/Transforms/Utils/SimplifyLibCalls.h and the implementation in llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp. Looking at the files will give an example of some of the other library call replacement optimizations that are done (the header file is probably easier to start with). And of course there are other many other optimizations that LLVM does, you can get an idea of some of them by looking at the list of LLVM passes.

  1. Could I write compiler optimizations for my own libraries? How would I do that?

Yes you could. LLVM is very modular and performs transformation on the IR in a series of passes. So if you wanted to add a custom pass yourself for your own library you could do so (although it is still a fair amount of work to understand how the LLVM compiler flow works). A good starting point is the document: Writing an LLVM Pass.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...