Index: lib/Transforms/Instrumentation/InstrProfiling.cpp =================================================================== --- lib/Transforms/Instrumentation/InstrProfiling.cpp +++ lib/Transforms/Instrumentation/InstrProfiling.cpp @@ -137,12 +137,34 @@ // We did not know how many value sites there would be inside // the instrumented function. This is counting the number of instrumented // target value sites to enter it as field in the profile data variable. - for (Function &F : M) + // + // Also create the profile data variable -- do it here because there is no + // guarantee that a counter increment will be ahead of value profile + // instrumentation in IR level instrumentation where the profile data + // variable are needed in the lowering. We only need to see the first + // counter increment instruction to create the variable. This needs + // to be done after counting the number of value sites in this function. + for (Function &F : M) { for (BasicBlock &BB : F) for (auto I = BB.begin(), E = BB.end(); I != E;) if (auto *Ind = dyn_cast(I++)) computeNumValueSiteCounts(Ind); + // Create the profile data variable. + bool CounterVarSet = false; + for (BasicBlock &BB : F) { + if (CounterVarSet) break; + for (auto I = BB.begin(), E = BB.end(); I != E;) + if (!CounterVarSet) { + if (auto *Inc = dyn_cast(I++)) { + getOrCreateRegionCounters(Inc); + CounterVarSet = true; + break; + } + } + } + } + for (Function &F : M) for (BasicBlock &BB : F) for (auto I = BB.begin(), E = BB.end(); I != E;) {