[PATCH] D126341: Order implicitly instantiated global variable's initializer by the reverse instantiation order

Yuanfang Chen via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Wed May 25 16:07:17 PDT 2022


ychen added a comment.

In D126341#3537947 <https://reviews.llvm.org/D126341#3537947>, @rnk wrote:

> I'm somewhat supportive of the goal here, but I think there are still some underlying issues.
>
> First, why should these guarantees be limited to instantiations and not inline variables? Such as:
>
>   int f();
>   inline int gv1 = f();
>   inline int gv2 = gv1 + 1; // rely on previous

I think this is because (as discussed in cwg362, https://eel.is/c++draft/lex.phases#1.8) instantiations happen in instantiation units where no order is specified. inline variables live in TU, where the order is specified.

> Second, LLVM doesn't guarantee that global_ctors at the same priority execute in order. See the langref: https://llvm.org/docs/LangRef.html#the-llvm-global-ctors-global-variable So, without a guarantee from LLVM, Clang can't rely on this behavior. LLVM relies on this lack of an ordering guarantee to power globalopt.

Yeah, I noticed that too. In practice, it looks like we do rely on the order in llvm.global_ctors to implement the static init order (for the above inline variable case, https://clang.godbolt.org/z/G3YoY5bc9). If globalopt decides to reorder the two init functions, the result would be wrong.

> Last, what happens when the same global is implicitly instantiated in some other TU? Won't that disrupt the ordering?
>
> + at alexander-shaposhnikov, who is working on global opt changes.

Hmm, that's a great point. My thoughts are it would not unless the linker is weird/inconsistent about which COMDAT to pick. Since for each TU, one globalvar has all its dependency globalvars initialized in the correct order in init array. Say two TUs, both have T<8>, no matter which T<8> the linker picks, it would pick all the T<8>'s dependencies according to the same criteria. Hence the init order is kept. I wouldn't say I'm 100% sure. At least it appears to me so at the moment. I'll do some experiments locally.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D126341/new/

https://reviews.llvm.org/D126341



More information about the cfe-commits mailing list