[Flang] Default initialize module variables to zero [527.cam4_r failure]
The cam4 spec2017 benchmark is failing since module variables are initialized as undef. This can cause not well-defined behaviour to happen if the module variable is used in an if statement. Use the zeroinitializer to fix the issue.
A simple reproducer is:
module simple
logical :: async_interf
contains
subroutine one
print *, "one = ", async_interf
if (async_interf) then
print *, "Inside async"
end if
end subroutine
end module
program mn
use simple
call one()
end program
The code above will print the following result with Flang when compiled with LTO and O2.
one = F
Inside async
The LLVM IR generated marks the module variable async_interf as undefined.
@_QMsimpleEasync_interf = local_unnamed_addr global i32 undef
The variable being marked as undef makes the if comparison pointless and optimisation either remove the if check or hoists the code outside the if.
@llvm/issue-subscribers-flang-ir
For simple types, this is trivial to fix - 3-4 lines of code-change and a few tests that needs changing. I haven't fixed tests yet, but I've got the basic simple types working.
Aggregate types shouldn't be too hard, but need some changes in CodeGen.cpp, the ZeroOpConversion currently doesn't support aggregate types.
Does standard Fortran support initializing module variables?
For the record, I support statically allocating module variables with zeros and not marking them as undef, which I consider to be the expected default behavior for Fortran.
At least Flang should warn about the uninitialised variable. GCC supports for security reasons: -ftrivial-auto-var-init=choice
https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-ftrivial-auto-var-init
Story: My plan was to initialise async_interf with true, I forgot, and Flang secretly initialises the variable with 0 ?!?
Does standard Fortran support initializing module variables?
I don't think the standard prescribes anything here. This is processor dependent. But gfortan and Classic Flang initializes these variables to zero.
For the record, I support statically allocating module variables with zeros and not marking them as undef, which I consider to be the expected default behavior for Fortran.
OK. We discussed this a bit in the last technical call on April 17th. @jeanPerier was also recommending zero-initialization but also suggested we could do something (like poison in llvm) to trigger some runtime debug for uninitialized values.
At least Flang should warn about the uninitialised variable. GCC supports for security reasons:
-ftrivial-auto-var-init=choicehttps://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-ftrivial-auto-var-init
There is also -Wuninitialized. Not sure whether the auto here refers to stack-allocated variables which might not apply to the case of module variables.
Story: My plan was to initialise
async_interfwith true, I forgot, and Flang secretly initialises the variable with0?!?
If you print it out, you are likely to get false. But the internal LLVM IR representation is undef which can cause some transformations to apply.
I am inclined to follow the C/C++ standards. Never initialise uninitialised variables. It can cause surprising behaviour. Why zero, you could use patterns or random values.
Warn about all uninitialised variables.
The lifetime of the module variables ends when the modules ends. It is like a local variable (auto).
I think the LTO is doing a legal thing for the example in the description: if this module is the only one that the LTO sees, then it is obvious that the variable has undefined value and it can be optimized in any way.
I wonder what is the code closure (list of modules) in cam that causes the problem.
I am inclined to follow the C/C++ standards. Never initialise uninitialised variables. It can cause surprising behaviour. Why zero, you could use patterns or random values.
Warn about all uninitialised variables.
The lifetime of the module variables ends when the modules ends. It is like a local variable (auto).
From Fortran 2008 onwards, module globals have an implicit SAVE attribute, which makes them similar to static variables in C or C++.
See 8.5.16.4 on page 106 in this: https://j3-fortran.org/doc/year/18/18-007r1.pdf
Based on that, and the fact that flang is aiming to be a F2018 compatible compiler, I'd say zero initializing is fair and as expected for a C or C++ programmer. And from other code that I've seen, that's what programmers expect - assuming they expect anything.
Agreed, pre-2008, the behaviour of module globals [and various other things also covered by the 4 section in the above paragrapph] were not guaranteed to remain from one use [1] of a module to the next - I believe the motivation for that behaviour was the ability to have overlays in some compilers, mainly those for 16-bit computers - like the PDP-11 I used at school and early PCs and similar machines.
So, zero-initialization is reasonable here. It is also the default in a few other compilers, so there is a precedent. For example in gfortran [without extra flags]:
__simple_MOD_async_interf:
.zero 4
I think the LTO is doing a legal thing for the example in the description: if this module is the only one that the LTO sees, then it is obvious that the variable has undefined value and it can be optimized in any way.
I wonder what is the code closure (list of modules) in cam that causes the problem.
I think the real problem is that we have some code that is along the lines of:
module A
logical a_variable
...
subroutine sub
if (a_variable) then
...
end if
end sub
''''
Somwehere else there's another module:
module b
use a, only a_variable
...
subroutine do_stuff(logical x)
...
x = .false.
if (something) then
x = .true.
end if
....
end subroutine do_stuff
subroutine do_work
...
do_stuff(a_variable)
...
end do_work
[This is actually quite simplified still - it's inside a struct and there's also an array of them, I think].
So whilst the variable is indeed initalized, the linker/optimizer isn't quite "following the flow", so it doesn't understand that the variable does indeed get initialized.
So, I agree that the linker is not doing anything wrong. I'm not convinced there's any other way than "initialize the variable" to fix it.
The C and C++ standard forbids to initialize uninitialized variables! Maybe Fortran is different.
But it would be an amazing user experience, if you could give a detailed warning.
a_variableis uninitializedif(a_variable)reads an uninitialized variable (a_variable). With line and column numbers and code.
The C and C++ standard forbids to initialize uninitialized variables! Maybe Fortran is different.
But it would be an amazing user experience, if you could give a detailed warning.
a_variableis uninitializedif(a_variable)reads an uninitialized variable (a_variable). With line and column numbers and code.
And in my example, the variable IS initialized, just not in module a - it is done by module b [we assume that do_work does gets called at some point].
As I've already written: from Fortran 2008 onwards: there is an implied SAVE on the module-wide variable, which means that in C terms, it's a static or global variable, a static is a global variable that doesn't have it's name available to other translation units. It is, in C and C++, initialized to zero on all standards compliant implementations of C, and has been like that for a VERY long time. Fortran doesn't specify that these values should or shouldn't be initialized, that's an implementation detail. It makes sense to followi the standard of C global variables, which ARE initialized to zero according to the C standard (and C++ just copy-pasted that part).
For variables local to a function, it would definitely be possible to determine that a variable is not initialized (or "May not be initialized" in cases where branches are involved).
When it's a global variable, you can't know at compilation time - it MAY be possible to determine for some cases with LTO, but there's lots of problems trying to achieve this - it would be valid to not initialize some variable if it never gets used - for example some optional functionality.
I do not believe anyone is arguing that the code in Spec-2017 is actually not initializing this variable - although the simple example here is minimized to show the problem.
I am misunderstanding something. C and C++ mandate to not initialize uninitialized variables. It is is forbidden, see https://reviews.llvm.org/D54604?id=174471 and https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-ftrivial-auto-var-init. There were long discussion to add flags to Clang to initialize variables to zero. It is used for security reasons in the Linux kernel and Apple uses it in production.
The example in the initial post read an uninitialized variable. Flang should give a great warning experience to the user.
Yes, you are missing that these are to all intents and purposes global variables. The variables we are changing are not auto storage. They are, in C terms, static storage, which according to the C standard are always initialized to zero [if not explicitly initializes of course]. See above about "implicit SAVE", I even linked the standards document - that means the variable has the same lifetime as the whole program. Whilst that was not guaranteed in earlier Fortran specifications - up to 2003, it is now. It was then "implementation defined" how it worked, so you can't rely on any specific behaviour across different compilers.
Yes, the simple example is showing the effect of reading a global value that is uninitialized. The REAL code is complex, and the LTO-linker just doesn't understand that the code in another module actually DOES set the value, and then compiles the code in the original module as if it was never set, even though it has been set (to false). If you have access to SPEC-2017 source code, feel free to analyze the cam4 behavioru on ios%async_interface - it is being read in lots of places, and it is set in two places. Which happens before the calls to the code that reads it. Just, because the code is complicated, LTO-linker doesn't understand what happens and says "Uh, this is undefined, I'll just remove this if-statement and execute the code inside always". There is possibly soemthing we could do to fix LTO, but it seems like an awkward solution.
Also note that the code I'm editing to fix this is in flang/lib/Lower/ConvertVariable.cpp, in the function defineGlobal - it is a global variable in this compiler. I would not take this approach if the code was reading an uninitialized local variable.
That was a surprise. From the C++ standard:
[Note 1: Objects with static or thread storage duration are zero-initialized, see 6.9.3.2. —end note]
I think the real problem is that we have some code that is along the lines of:
module A logical a_variable ... subroutine sub if (a_variable) then ... end if end sub '''' Somwehere else there's another module:module b use a, only a_variable ... subroutine do_stuff(logical x) ... x = .false. if (something) then x = .true. end if .... end subroutine do_stuff subroutine do_work ... do_stuff(a_variable) ... end do_work[This is actually quite simplified still - it's inside a struct and there's also an array of them, I think].
So whilst the variable is indeed initalized, the linker/optimizer isn't quite "following the flow", so it doesn't understand that the variable does indeed get initialized.
So, I agree that the linker is not doing anything wrong. I'm not convinced there's any other way than "initialize the variable" to fix it.
It looks like LTO issue to me. The a_variable in module A has 'external' linkage (definition in https://llvm.org/docs/LangRef.html#linkage-types), so it is visible externally (relative to module A) and can be read/modified in other modules. If LTO is given both module A and module B, then it should be obvious that a pointer to a_variable is passed to do_stuff (unless it is passed by value) and it is modified inside do_stuff. So if do_stuff might be called before sub, then the undef initialization of a_variable in module A might not reach the check inside sub and it is incorrect to assume that a_variable has undefined value at this point.
So I think we jumped to the conclusion about the need to initialize the module variables too quickly. We have to try to solve the real issue instead of hiding it with the zero-initialization.
Please also note that Fortran SAVE attribute does not equal to C/C++ static. C/C++ static is mapped by Clang to LLVM IR internal linkage, whereas Fortran SAVE attribute is mapped by Flang to external linkage.
Due to the uncertainty by the external linkage, you could still warn that:
if (async_interf) then
may read an uninitialized value.
Thanks for all the thoughts, I think we need to discuss this some more. I wrote a long reply, but I think I need to discuss with my team before actually replying.
I have to apologise. The problem is really just that "we don't initialize globlas to zero, so LTO does it's job and says undefined - removes the if as it is completely entitled to do".
I misunderstood my colleague's notes on what was actually going wrong, and looked at a different part of the code.
The ACTUAL problem is that we have:
module a
logical a_variable
subroutine sub_one
...
logical a_variable ! Yes, shadowing the global.
a_variable = .false.
...
if (something) then
a_variable = .true.
end if
...
end subroutine
subroutine sub_two
...
if (a_variable) then
call do_stuff_that_will_not_work
end if
....
end subroutine
end module
So, the variable is never set. Nothing to do with flang-new or the compiler - it's a bug in Spec-2017. Unfortunately, there's no way to fix this, since modifying Spec is not allowed. It HAPPENS to work in other compilers, because other compilers, apparently, don't treat unset global variables as true.
If I comment out the shadowing variable, everything works correctly.
I'm not sure what we can do here. It's clearly not a flang bug. But we want this benchmark to run on flang, but modifyiung the source of the benchmark, as far as I know is a BIG NO! So, we'll have to live with "this benchmark doesn't work, becasue we set global variables to undef". And yes, I agree, we should not change the compiler to fix this. At the same time, we want the benchmark to work. Impossible to solve.
Thank you for your detailed analysis:
#include <stdio.h>
extern bool a_variable;
void important() {
bool a_variable; // shadows global a_variable
a_variable = false;
if (a_variable)
printf("");
a_variable = true;
}
void evenMoreImportant() {
if (a_variable) // <-- reads uninitialized a_variable
printf("");
}
In this example, Clang gives no warnings.
I have some interest in which warnings should Flang give in the benchmark to help users and what methods Flang provides to find issues.