Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is C++ function template implemented in assembly?

Tags:

c++

assembly

I am trying to implement C++ function using assembly code -- ARMv7-a, to be specific. Now I encounter a program that I don't know how C++ function template should be implemented in assembly. I try to compile the source code with -S -O1 flag to see the generated assembly but couldn't understand it. Can any one give me a brief idea how the C++ template is translated into assembly code? Just use the following simple function as an example:

template<typename T>
T f(T a) {
   return a + 1;
}

If you found any other function is easier to do the explain, please do so. Thanks!

like image 227
Da Teng Avatar asked May 28 '14 16:05

Da Teng


2 Answers

It would help, to phrase it correctly. It's not template function, it's function template ... noticed the difference?

A template, is to generate code upon instantiation. So in this case, if you instantiate your f for int the assembly would be identical with

int f(int a) { // Note that having a return type void is wrong here
   return a + 1;
}

There's lack of binary code generation for non instantiated templates. That's why lots of errors in template code remain dormant until instantiation for the problematic types is performed.

So for a real example, here are the 2 versions, one generated out of a function template and one out of a function (both for int); if it wasn't for the hint at the right one couldn't tell the differene:

    f2(1);
00BA25BE  push        1  
00BA25C0  call        f2<int> (0BA12F3h)  
00BA25C5  add         esp,4  
    f(1);
00BA25C8  push        1  
00BA25CA  call        f (0BA12EEh)  
00BA25CF  add         esp,4  

More on templates (types this time) and binary code representation here

like image 104
Nikos Athanasiou Avatar answered Oct 01 '22 16:10

Nikos Athanasiou


You should implement each instance of the template in separate assembly.

Fundamentally, each template instance is a different type. You'll also need to deal with specialisations; partial or otherwise.

(Of course that means that you need to know in advance which set of Ts you need, but that is essentially what a C++ compiler does.)

like image 24
Bathsheba Avatar answered Oct 01 '22 16:10

Bathsheba