B.Gen.Jack.O.Neill
B.Gen.Jack.O.Neill

Reputation: 8397

Why compilers creates one variable "twice"?

I know this is more "heavy" question, but I think its interesting too. It was part of my previous questions about compiler functions, but back than I explained it very badly, and many answered just my first question, so ther it is:

So, if my knowledge is correct, modern Windows systems use paging as a way to switch tasks and secure that each task has propriate place in memory. So, every process gets its own place starting from 0.

When multitasking goes into effect, Kernel has to save all important registers to the task´s stack i believe than save the current stack pointer, change page entry to switch to another proces´s physical adress space, load new process stack pointer, pop saved registers and continue by call to poped instruction pointer adress.

Becouse of this nice feature (paging) every process thinks it has nice flat memory within reach. So, there is no far jumps, far pointers, memory segment or data segment. All is nice and linear.

But, when there is no more segmentation for the process, why does still compilers create variables on the stack, or when global directly in other memory space, than directly in program code?

Let me give an example, I have a C code:int a=10;

which gets translated into (Intel syntax):mov [position of a],#10

But than, you actually ocupy more bytes in RAM than needed. Becouse, first few bytes takes the actuall instruction, and after that instruction is done, there is new byte containing the value 10.

Why, instead of this, when there is no need to switch any segment (thus slowing the process speed) isn´t just a value of 10 coded directly into program like this:

xor eax,eax //just some instruction
10 //the value iserted to the program
call end //just some instruction

Becouse compiler know the exact position of every instruction, when operating with that variable, it would just use it´s adress.

I know, that const variables do this, but they are not really variables, when you cannot change them.

I hope I eplained my question well, but I am still learning English, so forgive my sytactical and even semantical errors.

EDIT:

I have read your answers, and it seems that based on those I can modify my question:

So, someone told here that global variable is actually that piece of values attached directly into program, I mean, when variable is global, is it atached to the end of program, or just created like the local one at the time of execution, but instead of on stack on heap directly?

If the first case - attached to the program itself, why is there even existence of local variables? I know, you will tell me becouse of recursion, but that is not the case. When you call function, you can push any memory space on stack, so there is no program there.

I hope you do understand me, there always is ineficient use of memory, when some value (even 0) is created on stack from some instruction, becouse you need space in program for that instruction and than for the actual var. Like so: push #5 //instruction that says to create local variable with integer 5 And than this instruction just makes number 5 to be on stack. Please help me, I really want to know why its this way. Thanks.

Upvotes: 1

Views: 441

Answers (6)

5ound
5ound

Reputation: 1199

Variables have storage space and can be modified. It makes no sense to stick them in the code segment, where they cannot be modified.

If you have code with int a=10 or even const int a=10, the compiler cannot convert code which references 'a' to use the constant 10 directly, because it has no way of knowing whether 'a' may be changed behind its back (even const variables can be changed). For example, one way 'a' can be changed without the compiler knowing is, if you have a pointer which points 'a'. Pointers are not fixed at runtime, so the compiler cannot determine at compile time whether there will be a pointer which will point to and modify 'a'.

Upvotes: 0

Why isn´t just a value of 10 coded directly into program like this:

xor eax,eax //just some instruction  
10 //the value iserted to the program  
call end //just some instruction  

That is how global variables are stored. However, instead of being stuck in the middle of executable code (which is messy, and not even possible nowadays), they are stored just after the program code in memory (in Windows and Linux, at least), in what's called the .data section.

When it can, the compiler will move variables to the .data section to optimize performance. However, there are several reasons it might not:

  • Some variables cannot be made global, including instance variables for a class, parameters passed into a function (obviously), and variables used in recursive functions.
  • The variable still exists in memory somewhere, and still must have code to access it. Thus, memory usage will not change. In fact, on the x86 ("Intel"), according to this page the instruction to reference a local variable:

    mov eax, [esp+8]
    

    and the instruction to reference a global variable:

    mov eax, [0xb3a7135]
    

    both take 1 (one!) clock cycle.

    The only advantage, then, is that if every local variable is global, you wouldn't have to make room on the stack for local variables.

  • Adding a variable to the .data segment may actually increase the size of the executable, since the variable is actually contained in the file itself.

  • As caf mentions in the comments, stack-based variables only exist while the function is running - global variables take up memory during the entire execution of the program.

Upvotes: 3

Dummy00001
Dummy00001

Reputation: 17430

So, there is no far jumps, far pointers, memory segment or data segment. All is nice and linear.

Yes and no. Different program segments have different purposes - despite the fact that they reside within flat virtual memory. E.g. data segment is readable and writable, but you can't execute data. Code segment is readable and executable, but you can't write into it.

why does still compilers create variables on the stack, [...] than directly in program code?

Simple.

  1. Code segment isn't writable. For safety reasons first. Second, most CPUs do not like to have code segment being written into as it breaks many existing optimization used to accelerate execution.
  2. State of the function has to be private to the function due to things like recursion and multi-threading.

isn´t just a value of 10 coded directly into program like this

Modern CPUs prefetch instructions to allow things like parallel execution and out-of-order execution. Putting the garbage (to CPU that is the garbage) into the code segment would simply diminish (or flat out cancel) the effect of the techniques. And they are responsible for the lion share of the performance gains CPUs had showed in the past decade.

when there is no need to switch any segment

So if there is no overhead of switching segment, why then put that into the code segment? There are no problems to keep it in data segment.

Especially in case of read-only data segment, it makes sense to put all read-only data of the program into one place - since it can be shared by all instances of the running application, saving physical RAM.

Becouse compiler know the exact position of every instruction, when operating with that variable, it would just use it´s adress.

No, not really. Most of the code is relocatable or position independent. The code is patched with real memory addresses when OS loads it into the memory. Actually special techniques are used to actually avoid patching the code so that the code segment too could be shared by all running application instances.

The ABI is responsible for defining how and what compiler and linker supposed to do for program to be executable by the complying OS. I haven't seen the Windows ABI, but the ABIs used by Linux are easy to find: search for "AMD64 ABI". Even reading the Linux ABI might answer some of your questions.

Upvotes: 4

Consider:

  • local variables may have more than one simultaneous existence if a routine is called recursively (even indirectly in, say, a recursive decent parser) or from more than one thread, and these cases occur in the same memory context
  • marking the program memory non-writable and the stack+heap as non-executable is a small but useful defense against certain classes of attacks (stack smashing...) and is used by some OSs (I don't know if windows does this, however)

Your proposal doesn't allow for either of these cases.

Upvotes: 6

T.E.D.
T.E.D.

Reputation: 44804

What you are talking about is optimization, and that is the compiler's business. If nothing ever changes that value, and the compiler can figure that out, then the compiler is perfectly free to do just what you say (unless a is declared volatile).

Now if you are saying that you are seeing that the compiler isn't doing that, and you think it should, you'd have to talk to your compiler writer. If you are using VisualStudio, their address is One Microsoft Way, Redmond WA. Good luck knocking on doors there. :-)

Upvotes: 3

Keith Nicholas
Keith Nicholas

Reputation: 44306

not quite sure what your confusion is?

int a = 10; means make a spot in memory, and put the value 10 at the memory address

if you want a to be 10

#define a 10

though more typically

#define TEN 10

Upvotes: 0

Related Questions