Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Assume the following program fragement without any control flow branches (straig

ID: 674395 • Letter: A

Question

Assume the following program fragement without any control flow branches (straight line code). Your job is it to implement a compiler optimization called “constant folding” for straight line code. This optimization identifies program variables with values that are known at compile time. Expressions that consist of only such variables can be evaluated at compile time.

Would it always be safe for the compiler optimization of constant folding to replace the assignment “c = a + b” by “c = 12” ? Note that there are no assignments to variables a or b between “b = 7” and “c = a + b”. The control flow is linear, so there are no branches. If you believe that constant propagation may not be safe, give an example where constant propagation would be indeed unsafe (incorrect), without violating any of the above assumptions about the code fragment. Note: You can add declarations of other variables and other statements that do not mention a or b.

Having a hard time figuring this out.

Thank you in advance!

Explanation / Answer

begin
   /*Compiler folding :without using the variable declarations , and compiler will know
the value of the a and b at run time.*/

/*constant folding.
5 and 7 are constants will replace by 12 at run time. No need
of other declarations and assignments and addition operations*/
c=5+7;
end

It would be not safe if set c=12 since if c address known then programmer can change
the value at address of c.
Constant folding is useful where possible cause of run time errors
For example, division by zero will cause runtime exception.
Such cases can be avoided with division by known values to avoid
program terminations.

Constant propagation is replacing the values of the variables at
the time of usage of variables.
Constant propagation cannot guarantee that when using the variables
at the time of usage do not throws an run time error.

/*example*/
int x=1;
int y=0;
int division(int x, int y)
{
   return x/y;
}

In constange propagation , the values of x and y is replaced
by 1 and 0. Since 1 is divided by 0, then compiler throws
an division by zero error in this case.
So constant propagation is not always safe for the variable substiution.
To avoid this kind of issues, programmers use exception handling

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote