+template <class WeightList>
+uint32_t
+MachineBranchProbabilityInfo::normalizeEdgeWeights(WeightList &Weights) {
+ assert(Weights.size() < UINT32_MAX && "Too many weights in the list!");
+ // First we compute the sum with 64-bits of precision.
+ uint64_t Sum = std::accumulate(Weights.begin(), Weights.end(), uint64_t(0));
+
+ // If the computed sum fits in 32-bits, we're done.
+ if (Sum <= UINT32_MAX)
+ return 1;
+
+ // Otherwise, compute the scale necessary to cause the weights to fit, and
+ // re-sum with that scale applied.
+ assert((Sum / UINT32_MAX) < UINT32_MAX &&
+ "The sum of weights exceeds UINT32_MAX^2!");
+ uint32_t Scale = (Sum / UINT32_MAX) + 1;
+ for (auto &W : Weights)
+ W /= Scale;
+ return Scale;
+}
+