base: Fix squares of stats
[gem5.git] / src / base / statistics.hh
index bf2139caabd6e492b751096a0f6600f948f7c739..fd16c3a36b0a6564d68331eff67fc81bc10454ed 100644 (file)
@@ -1,5 +1,18 @@
 /*
+ * Copyright (c) 2019 Arm Limited
+ * All rights reserved.
+ *
+ * The license below extends only to copyright in the software and shall
+ * not be construed as granting a license to any other intellectual
+ * property including but not limited to intellectual property relating
+ * to a hardware implementation of the functionality of the software
+ * licensed hereunder.  You may use the software subject to the license
+ * terms below provided that you ensure that this notice is replicated
+ * unmodified and in its entirety in all distributions of the software,
+ * modified or unmodified, in source code or in binary form.
+ *
  * Copyright (c) 2003-2005 The Regents of The University of Michigan
+ * Copyright (c) 2017, Centre National de la Recherche Scientifique
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,6 +39,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  * Authors: Nathan Binkert
+ *          Pierre-Yves Peneau
  */
 
 /** @file
 #include <algorithm>
 #include <cassert>
 #ifdef __SUNPRO_CC
-#include <cmath>
+#include <math.h>
 #endif
 #include <cmath>
 #include <functional>
 #include <iosfwd>
 #include <list>
+#include <map>
+#include <memory>
 #include <string>
 #include <vector>
 
+#include "base/stats/group.hh"
 #include "base/stats/info.hh"
+#include "base/stats/output.hh"
 #include "base/stats/types.hh"
-#include "base/stats/visit.hh"
 #include "base/cast.hh"
 #include "base/cprintf.hh"
 #include "base/intmath.hh"
-#include "base/refcnt.hh"
 #include "base/str.hh"
 #include "base/types.hh"
 
@@ -90,7 +106,7 @@ class InfoProxy : public Base
     void prepare() { s.prepare(); }
     void reset() { s.reset(); }
     void
-    visit(Visit &visitor)
+    visit(Output &visitor)
     {
         visitor.visit(*static_cast<Base *>(this));
     }
@@ -158,6 +174,8 @@ class Vector2dInfoProxy : public InfoProxy<Stat, Vector2dInfo>
 {
   public:
     Vector2dInfoProxy(Stat &stat) : InfoProxy<Stat, Vector2dInfo>(stat) {}
+
+    Result total() const { return this->s.total(); }
 };
 
 struct StorageParams
@@ -167,9 +185,12 @@ struct StorageParams
 
 class InfoAccess
 {
+  private:
+    Info *_info;
+
   protected:
     /** Set up an info class for this statistic */
-    void setInfo(Info *info);
+    void setInfo(Group *parent, Info *info);
     /** Save Storage class parameters if any */
     void setParams(const StorageParams *params);
     /** Save Storage class parameters if any */
@@ -181,6 +202,9 @@ class InfoAccess
     const Info *info() const;
 
   public:
+    InfoAccess()
+        : _info(nullptr) {};
+
     /**
      * Reset the stat to the default state.
      */
@@ -223,21 +247,27 @@ class DataWrap : public InfoAccess
         return safe_cast<const Info *>(InfoAccess::info());
     }
 
-  protected:
-    /**
-     * Copy constructor, copies are not allowed.
-     */
-    DataWrap(const DataWrap &stat);
+  public:
+    DataWrap() = delete;
+    DataWrap(const DataWrap &) = delete;
+    DataWrap &operator=(const DataWrap &) = delete;
 
-    /**
-     * Can't copy stats.
-     */
-    void operator=(const DataWrap &);
 
-  public:
-    DataWrap()
+    DataWrap(Group *parent, const char *name, const char *desc)
     {
-        this->setInfo(new Info(self()));
+        auto info = new Info(self());
+        this->setInfo(parent, info);
+
+        if (parent)
+            parent->addStat(info);
+
+        if (name) {
+            info->setName(parent, name);
+            info->flags.set(display);
+        }
+
+        if (desc)
+            info->desc = desc;
     }
 
     /**
@@ -255,6 +285,23 @@ class DataWrap : public InfoAccess
     }
     const std::string &name() const { return this->info()->name; }
 
+    /**
+     * Set the character(s) used between the name and vector number
+     * on vectors, dist, etc.
+     * @param _sep The new separator string
+     * @return A reference to this stat.
+     */
+    Derived &
+    setSeparator(const std::string &_sep)
+    {
+      this->info()->setSeparator(_sep);
+      return this->self();
+    }
+    const std::string &setSeparator() const
+    {
+      return this->info()->separatorString;
+    }
+
     /**
      * Set the description and marks this stat to print at the end of
      * simulation.
@@ -313,6 +360,11 @@ class DataWrapVec : public DataWrap<Derived, InfoProxyType>
   public:
     typedef InfoProxyType<Derived> Info;
 
+    DataWrapVec(Group *parent = nullptr, const char *name = nullptr,
+                const char *desc = nullptr)
+        : DataWrap<Derived, InfoProxyType>(parent, name, desc)
+    {}
+
     // The following functions are specific to vectors.  If you use them
     // in a non vector context, you will get a nice compiler error!
 
@@ -389,6 +441,11 @@ class DataWrapVec2d : public DataWrapVec<Derived, InfoProxyType>
   public:
     typedef InfoProxyType<Derived> Info;
 
+    DataWrapVec2d(Group *parent, const char *name, const char *desc)
+        : DataWrapVec<Derived, InfoProxyType>(parent, name, desc)
+    {
+    }
+
     /**
      * @warning This makes the assumption that if you're gonna subnames a 2d
      * vector, you're subnaming across all y
@@ -646,7 +703,9 @@ class ScalarBase : public DataWrap<Derived, ScalarInfoProxy>
     Counter value() const { return data()->value(); }
 
   public:
-    ScalarBase()
+    ScalarBase(Group *parent = nullptr, const char *name = nullptr,
+               const char *desc = nullptr)
+        : DataWrap<Derived, ScalarInfoProxy>(parent, name, desc)
     {
         this->doInit();
     }
@@ -714,14 +773,14 @@ class ScalarBase : public DataWrap<Derived, ScalarInfoProxy>
 class ProxyInfo : public ScalarInfo
 {
   public:
-    std::string str() const { return to_string(value()); }
+    std::string str() const { return std::to_string(value()); }
     size_type size() const { return 1; }
     bool check() const { return true; }
     void prepare() { }
     void reset() { }
     bool zero() const { return value() == 0; }
 
-    void visit(Visit &visitor) { visitor.visit(*this); }
+    void visit(Output &visitor) { visitor.visit(*this); }
 };
 
 template <class T>
@@ -750,6 +809,25 @@ class FunctorProxy : public ProxyInfo
     Result total() const { return (*functor)(); }
 };
 
+/**
+ * A proxy similar to the FunctorProxy, but allows calling a method of a bound
+ * object, instead of a global free-standing function.
+ */
+template <class T, class V>
+class MethodProxy : public ProxyInfo
+{
+  private:
+    T *object;
+    typedef V (T::*MethodPointer) () const;
+    MethodPointer method;
+
+  public:
+    MethodProxy(T *obj, MethodPointer meth) : object(obj), method(meth) {}
+    Counter value() const { return (object->*method)(); }
+    Result result() const { return (object->*method)(); }
+    Result total() const { return (object->*method)(); }
+};
+
 template <class Derived>
 class ValueBase : public DataWrap<Derived, ScalarInfoProxy>
 {
@@ -757,7 +835,12 @@ class ValueBase : public DataWrap<Derived, ScalarInfoProxy>
     ProxyInfo *proxy;
 
   public:
-    ValueBase() : proxy(NULL) { }
+    ValueBase(Group *parent, const char *name, const char *desc)
+        : DataWrap<Derived, ScalarInfoProxy>(parent, name, desc),
+          proxy(NULL)
+    {
+    }
+
     ~ValueBase() { if (proxy) delete proxy; }
 
     template <class T>
@@ -778,6 +861,22 @@ class ValueBase : public DataWrap<Derived, ScalarInfoProxy>
         return this->self();
     }
 
+    /**
+     * Extended functor that calls the specified method of the provided object.
+     *
+     * @param obj Pointer to the object whose method should be called.
+     * @param method Pointer of the function / method of the object.
+     * @return Updated stats item.
+     */
+    template <class T, class V>
+    Derived &
+    method(T *obj,  V (T::*method)() const)
+    {
+        proxy = new MethodProxy<T,V>(obj, method);
+        this->setInit();
+        return this->self();
+    }
+
     Counter value() { return proxy->value(); }
     Result result() const { return proxy->result(); }
     Result total() const { return proxy->total(); };
@@ -1029,8 +1128,9 @@ class VectorBase : public DataWrapVec<Derived, VectorInfoProxy>
     }
 
   public:
-    VectorBase()
-        : storage(NULL)
+    VectorBase(Group *parent, const char *name, const char *desc)
+        : DataWrapVec<Derived, VectorInfoProxy>(parent, name, desc),
+          storage(nullptr), _size(0)
     {}
 
     ~VectorBase()
@@ -1169,8 +1269,9 @@ class Vector2dBase : public DataWrapVec2d<Derived, Vector2dInfoProxy>
     const Storage *data(off_type index) const { return &storage[index]; }
 
   public:
-    Vector2dBase()
-        : storage(NULL)
+    Vector2dBase(Group *parent, const char *name, const char *desc)
+        : DataWrapVec2d<Derived, Vector2dInfoProxy>(parent, name, desc),
+          x(0), y(0), _size(0), storage(nullptr)
     {}
 
     ~Vector2dBase()
@@ -1213,7 +1314,7 @@ class Vector2dBase : public DataWrapVec2d<Derived, Vector2dInfoProxy>
     operator[](off_type index)
     {
         off_type offset = index * y;
-        assert (index >= 0 && offset + index < size());
+        assert (index >= 0 && offset + y <= size());
         return Proxy(this->self(), offset, y);
     }
 
@@ -1228,12 +1329,19 @@ class Vector2dBase : public DataWrapVec2d<Derived, Vector2dInfoProxy>
     zero() const
     {
         return data(0)->zero();
-#if 0
+    }
+
+    /**
+     * Return a total of all entries in this vector.
+     * @return The total of all vector entries.
+     */
+    Result
+    total() const
+    {
+        Result total = 0.0;
         for (off_type i = 0; i < size(); ++i)
-            if (!data(i)->zero())
-                return false;
-        return true;
-#endif
+            total += data(i)->result();
+        return total;
     }
 
     void
@@ -1282,7 +1390,7 @@ struct DistParams : public StorageParams
 };
 
 /**
- * Templatized storage and interface for a distrbution stat.
+ * Templatized storage and interface for a distribution stat.
  */
 class DistStor
 {
@@ -1299,7 +1407,8 @@ class DistStor
         /** The number of buckets. Equal to (max-min)/bucket_size. */
         size_type buckets;
 
-        Params() : DistParams(Dist) {}
+        Params() : DistParams(Dist), min(0), max(0), bucket_size(0),
+                   buckets(0) {}
     };
 
   private:
@@ -1309,8 +1418,6 @@ class DistStor
     Counter max_track;
     /** The number of entries in each bucket. */
     Counter bucket_size;
-    /** The number of buckets. Equal to (max-min)/bucket_size. */
-    size_type buckets;
 
     /** The smallest value sampled. */
     Counter min_val;
@@ -1398,9 +1505,8 @@ class DistStor
         data.underflow = underflow;
         data.overflow = overflow;
 
-        size_type buckets = params->buckets;
-        data.cvec.resize(buckets);
-        for (off_type i = 0; i < buckets; ++i)
+        data.cvec.resize(params->buckets);
+        for (off_type i = 0; i < params->buckets; ++i)
             data.cvec[i] = cvec[i];
 
         data.sum = sum;
@@ -1446,7 +1552,7 @@ class HistStor
         /** The number of buckets.. */
         size_type buckets;
 
-        Params() : DistParams(Hist) {}
+        Params() : DistParams(Hist), buckets(0) {}
     };
 
   private:
@@ -1459,6 +1565,8 @@ class HistStor
 
     /** The current sum. */
     Counter sum;
+    /** The sum of logarithm of each sample, used to compute geometric mean. */
+    Counter logs;
     /** The sum of squares. */
     Counter squares;
     /** The number of samples. */
@@ -1476,6 +1584,7 @@ class HistStor
     void grow_up();
     void grow_out();
     void grow_convert();
+    void add(HistStor *);
 
     /**
      * Add a value to the distribution for the given number of times.
@@ -1505,11 +1614,12 @@ class HistStor
         size_type index =
             (int64_t)std::floor((val - min_bucket) / bucket_size);
 
-        assert(index >= 0 && index < size());
+        assert(index < size());
         cvec[index] += number;
 
         sum += val * number;
         squares += val * val * number;
+        logs += log(val) * number;
         samples += number;
     }
 
@@ -1549,6 +1659,7 @@ class HistStor
             data.cvec[i] = cvec[i];
 
         data.sum = sum;
+        data.logs = logs;
         data.squares = squares;
         data.samples = samples;
     }
@@ -1571,6 +1682,7 @@ class HistStor
         sum = Counter();
         squares = Counter();
         samples = Counter();
+        logs = Counter();
     }
 };
 
@@ -1612,9 +1724,8 @@ class SampleStor
     void
     sample(Counter val, int number)
     {
-        Counter value = val * number;
-        sum += value;
-        squares += value * value;
+        sum += val * number;
+        squares += val * val * number;
         samples += number;
     }
 
@@ -1689,9 +1800,8 @@ class AvgSampleStor
     void
     sample(Counter val, int number)
     {
-        Counter value = val * number;
-        sum += value;
-        squares += value * value;
+        sum += val * number;
+        squares += val * val * number;
     }
 
     /**
@@ -1774,7 +1884,10 @@ class DistBase : public DataWrap<Derived, DistInfoProxy>
     }
 
   public:
-    DistBase() { }
+    DistBase(Group *parent, const char *name, const char *desc)
+        : DataWrap<Derived, DistInfoProxy>(parent, name, desc)
+    {
+    }
 
     /**
      * Add a value to the distribtion n times. Calls sample on the storage
@@ -1811,6 +1924,12 @@ class DistBase : public DataWrap<Derived, DistInfoProxy>
     {
         data()->reset(this->info());
     }
+
+    /**
+     *  Add the argument distribution to the this distribution.
+     */
+    void add(DistBase &d) { data()->add(d.data()); }
+
 };
 
 template <class Stat>
@@ -1862,8 +1981,9 @@ class VectorDistBase : public DataWrapVec<Derived, VectorDistInfoProxy>
     }
 
   public:
-    VectorDistBase()
-        : storage(NULL)
+    VectorDistBase(Group *parent, const char *name, const char *desc)
+        : DataWrapVec<Derived, VectorDistInfoProxy>(parent, name, desc),
+          storage(NULL)
     {}
 
     ~VectorDistBase()
@@ -1978,7 +2098,7 @@ class DistProxy
  * Base class for formula statistic node. These nodes are used to build a tree
  * that represents the formula.
  */
-class Node : public RefCounted
+class Node
 {
   public:
     /**
@@ -2001,10 +2121,12 @@ class Node : public RefCounted
      *
      */
     virtual std::string str() const = 0;
+
+    virtual ~Node() {};
 };
 
-/** Reference counting pointer to a function Node. */
-typedef RefCountingPtr<Node> NodePtr;
+/** Shared pointer to a function Node. */
+typedef std::shared_ptr<Node> NodePtr;
 
 class ScalarStatNode : public Node
 {
@@ -2099,7 +2221,7 @@ class ConstNode : public Node
     const VResult &result() const { return vresult; }
     Result total() const { return vresult[0]; };
     size_type size() const { return 1; }
-    std::string str() const { return to_string(vresult[0]); }
+    std::string str() const { return std::to_string(vresult[0]); }
 };
 
 template <class T>
@@ -2129,7 +2251,7 @@ class ConstVectorNode : public Node
         size_type size = this->size();
         std::string tmp = "(";
         for (off_type i = 0; i < size; i++)
-            tmp += csprintf("%s ",to_string(vresult[i]));
+            tmp += csprintf("%s ", std::to_string(vresult[i]));
         tmp += ")";
         return tmp;
     }
@@ -2231,7 +2353,7 @@ class BinaryNode : public Node
     BinaryNode(NodePtr &a, NodePtr &b) : l(a), r(b) {}
 
     const VResult &
-    result() const
+    result() const override
     {
         Op op;
         const VResult &lvec = l->result();
@@ -2263,17 +2385,39 @@ class BinaryNode : public Node
     }
 
     Result
-    total() const
+    total() const override
     {
         const VResult &vec = this->result();
+        const VResult &lvec = l->result();
+        const VResult &rvec = r->result();
         Result total = 0.0;
-        for (off_type i = 0; i < size(); i++)
+        Result lsum = 0.0;
+        Result rsum = 0.0;
+        Op op;
+
+        assert(lvec.size() > 0 && rvec.size() > 0);
+        assert(lvec.size() == rvec.size() ||
+               lvec.size() == 1 || rvec.size() == 1);
+
+        /** If vectors are the same divide their sums (x0+x1)/(y0+y1) */
+        if (lvec.size() == rvec.size() && lvec.size() > 1) {
+            for (off_type i = 0; i < size(); ++i) {
+                lsum += lvec[i];
+                rsum += rvec[i];
+            }
+            return op(lsum, rsum);
+        }
+
+        /** Otherwise divide each item by the divisor */
+        for (off_type i = 0; i < size(); ++i) {
             total += vec[i];
+        }
+
         return total;
     }
 
     size_type
-    size() const
+    size() const override
     {
         size_type ls = l->size();
         size_type rs = r->size();
@@ -2288,7 +2432,7 @@ class BinaryNode : public Node
     }
 
     std::string
-    str() const
+    str() const override
     {
         return csprintf("(%s %s %s)", l->str(), OpString<Op>::str(), r->str());
     }
@@ -2327,13 +2471,13 @@ class SumNode : public Node
         size_type size = lvec.size();
         assert(size > 0);
 
-        Result vresult = 0.0;
+        Result result = 0.0;
 
         Op op;
         for (off_type i = 0; i < size; ++i)
-            vresult = op(vresult, lvec[i]);
+            result = op(result, lvec[i]);
 
-        return vresult;
+        return result;
     }
 
     size_type size() const { return 1; }
@@ -2365,6 +2509,12 @@ class Scalar : public ScalarBase<Scalar, StatStor>
 {
   public:
     using ScalarBase<Scalar, StatStor>::operator=;
+
+    Scalar(Group *parent = nullptr, const char *name = nullptr,
+           const char *desc = nullptr)
+        : ScalarBase<Scalar, StatStor>(parent, name, desc)
+    {
+    }
 };
 
 /**
@@ -2375,10 +2525,22 @@ class Average : public ScalarBase<Average, AvgStor>
 {
   public:
     using ScalarBase<Average, AvgStor>::operator=;
+
+    Average(Group *parent = nullptr, const char *name = nullptr,
+            const char *desc = nullptr)
+        : ScalarBase<Average, AvgStor>(parent, name, desc)
+    {
+    }
 };
 
 class Value : public ValueBase<Value>
 {
+  public:
+    Value(Group *parent = nullptr, const char *name = nullptr,
+          const char *desc = nullptr)
+        : ValueBase<Value>(parent, name, desc)
+    {
+    }
 };
 
 /**
@@ -2387,6 +2549,12 @@ class Value : public ValueBase<Value>
  */
 class Vector : public VectorBase<Vector, StatStor>
 {
+  public:
+    Vector(Group *parent = nullptr, const char *name = nullptr,
+           const char *desc = nullptr)
+        : VectorBase<Vector, StatStor>(parent, name, desc)
+    {
+    }
 };
 
 /**
@@ -2395,6 +2563,12 @@ class Vector : public VectorBase<Vector, StatStor>
  */
 class AverageVector : public VectorBase<AverageVector, AvgStor>
 {
+  public:
+    AverageVector(Group *parent = nullptr, const char *name = nullptr,
+                  const char *desc = nullptr)
+        : VectorBase<AverageVector, AvgStor>(parent, name, desc)
+    {
+    }
 };
 
 /**
@@ -2403,6 +2577,12 @@ class AverageVector : public VectorBase<AverageVector, AvgStor>
  */
 class Vector2d : public Vector2dBase<Vector2d, StatStor>
 {
+  public:
+    Vector2d(Group *parent = nullptr, const char *name = nullptr,
+             const char *desc = nullptr)
+        : Vector2dBase<Vector2d, StatStor>(parent, name, desc)
+    {
+    }
 };
 
 /**
@@ -2412,6 +2592,12 @@ class Vector2d : public Vector2dBase<Vector2d, StatStor>
 class Distribution : public DistBase<Distribution, DistStor>
 {
   public:
+    Distribution(Group *parent = nullptr, const char *name = nullptr,
+                 const char *desc = nullptr)
+        : DistBase<Distribution, DistStor>(parent, name, desc)
+    {
+    }
+
     /**
      * Set the parameters of this distribution. @sa DistStor::Params
      * @param min The minimum value of the distribution.
@@ -2426,6 +2612,9 @@ class Distribution : public DistBase<Distribution, DistStor>
         params->min = min;
         params->max = max;
         params->bucket_size = bkt;
+        // Division by zero is especially serious in an Aarch64 host,
+        // where it gets rounded to allocate 32GiB RAM.
+        assert(bkt > 0);
         params->buckets = (size_type)ceil((max - min + 1.0) / bkt);
         this->setParams(params);
         this->doInit();
@@ -2440,6 +2629,12 @@ class Distribution : public DistBase<Distribution, DistStor>
 class Histogram : public DistBase<Histogram, HistStor>
 {
   public:
+    Histogram(Group *parent = nullptr, const char *name = nullptr,
+              const char *desc = nullptr)
+        : DistBase<Histogram, HistStor>(parent, name, desc)
+    {
+    }
+
     /**
      * Set the parameters of this histogram. @sa HistStor::Params
      * @param size The number of buckets in the histogram
@@ -2466,7 +2661,9 @@ class StandardDeviation : public DistBase<StandardDeviation, SampleStor>
     /**
      * Construct and initialize this distribution.
      */
-    StandardDeviation()
+    StandardDeviation(Group *parent = nullptr, const char *name = nullptr,
+                      const char *desc = nullptr)
+        : DistBase<StandardDeviation, SampleStor>(parent, name, desc)
     {
         SampleStor::Params *params = new SampleStor::Params;
         this->doInit();
@@ -2484,7 +2681,9 @@ class AverageDeviation : public DistBase<AverageDeviation, AvgSampleStor>
     /**
      * Construct and initialize this distribution.
      */
-    AverageDeviation()
+    AverageDeviation(Group *parent = nullptr, const char *name = nullptr,
+                     const char *desc = nullptr)
+        : DistBase<AverageDeviation, AvgSampleStor>(parent, name, desc)
     {
         AvgSampleStor::Params *params = new AvgSampleStor::Params;
         this->doInit();
@@ -2499,6 +2698,12 @@ class AverageDeviation : public DistBase<AverageDeviation, AvgSampleStor>
 class VectorDistribution : public VectorDistBase<VectorDistribution, DistStor>
 {
   public:
+    VectorDistribution(Group *parent = nullptr, const char *name = nullptr,
+                       const char *desc = nullptr)
+        : VectorDistBase<VectorDistribution, DistStor>(parent, name, desc)
+    {
+    }
+
     /**
      * Initialize storage and parameters for this distribution.
      * @param size The size of the vector (the number of distributions).
@@ -2529,6 +2734,13 @@ class VectorStandardDeviation
     : public VectorDistBase<VectorStandardDeviation, SampleStor>
 {
   public:
+    VectorStandardDeviation(Group *parent = nullptr, const char *name = nullptr,
+                            const char *desc = nullptr)
+        : VectorDistBase<VectorStandardDeviation, SampleStor>(parent, name,
+                                                              desc)
+    {
+    }
+
     /**
      * Initialize storage for this distribution.
      * @param size The size of the vector.
@@ -2552,6 +2764,13 @@ class VectorAverageDeviation
     : public VectorDistBase<VectorAverageDeviation, AvgSampleStor>
 {
   public:
+    VectorAverageDeviation(Group *parent = nullptr, const char *name = nullptr,
+                           const char *desc = nullptr)
+        : VectorDistBase<VectorAverageDeviation, AvgSampleStor>(parent, name,
+                                                                desc)
+    {
+    }
+
     /**
      * Initialize storage for this distribution.
      * @param size The size of the vector.
@@ -2591,6 +2810,199 @@ class FormulaInfoProxy : public InfoProxy<Stat, FormulaInfo>
     std::string str() const { return this->s.str(); }
 };
 
+template <class Stat>
+class SparseHistInfoProxy : public InfoProxy<Stat, SparseHistInfo>
+{
+  public:
+    SparseHistInfoProxy(Stat &stat) : InfoProxy<Stat, SparseHistInfo>(stat) {}
+};
+
+/**
+ * Implementation of a sparse histogram stat. The storage class is
+ * determined by the Storage template.
+ */
+template <class Derived, class Stor>
+class SparseHistBase : public DataWrap<Derived, SparseHistInfoProxy>
+{
+  public:
+    typedef SparseHistInfoProxy<Derived> Info;
+    typedef Stor Storage;
+    typedef typename Stor::Params Params;
+
+  protected:
+    /** The storage for this stat. */
+    char storage[sizeof(Storage)];
+
+  protected:
+    /**
+     * Retrieve the storage.
+     * @return The storage object for this stat.
+     */
+    Storage *
+    data()
+    {
+        return reinterpret_cast<Storage *>(storage);
+    }
+
+    /**
+     * Retrieve a const pointer to the storage.
+     * @return A const pointer to the storage object for this stat.
+     */
+    const Storage *
+    data() const
+    {
+        return reinterpret_cast<const Storage *>(storage);
+    }
+
+    void
+    doInit()
+    {
+        new (storage) Storage(this->info());
+        this->setInit();
+    }
+
+  public:
+    SparseHistBase(Group *parent, const char *name, const char *desc)
+        : DataWrap<Derived, SparseHistInfoProxy>(parent, name, desc)
+    {
+    }
+
+    /**
+     * Add a value to the distribtion n times. Calls sample on the storage
+     * class.
+     * @param v The value to add.
+     * @param n The number of times to add it, defaults to 1.
+     */
+    template <typename U>
+    void sample(const U &v, int n = 1) { data()->sample(v, n); }
+
+    /**
+     * Return the number of entries in this stat.
+     * @return The number of entries.
+     */
+    size_type size() const { return data()->size(); }
+    /**
+     * Return true if no samples have been added.
+     * @return True if there haven't been any samples.
+     */
+    bool zero() const { return data()->zero(); }
+
+    void
+    prepare()
+    {
+        Info *info = this->info();
+        data()->prepare(info, info->data);
+    }
+
+    /**
+     * Reset stat value to default
+     */
+    void
+    reset()
+    {
+        data()->reset(this->info());
+    }
+};
+
+/**
+ * Templatized storage and interface for a sparse histogram stat.
+ */
+class SparseHistStor
+{
+  public:
+    /** The parameters for a sparse histogram stat. */
+    struct Params : public DistParams
+    {
+        Params() : DistParams(Hist) {}
+    };
+
+  private:
+    /** Counter for number of samples */
+    Counter samples;
+    /** Counter for each bucket. */
+    MCounter cmap;
+
+  public:
+    SparseHistStor(Info *info)
+    {
+        reset(info);
+    }
+
+    /**
+     * Add a value to the distribution for the given number of times.
+     * @param val The value to add.
+     * @param number The number of times to add the value.
+     */
+    void
+    sample(Counter val, int number)
+    {
+        cmap[val] += number;
+        samples += number;
+    }
+
+    /**
+     * Return the number of buckets in this distribution.
+     * @return the number of buckets.
+     */
+    size_type size() const { return cmap.size(); }
+
+    /**
+     * Returns true if any calls to sample have been made.
+     * @return True if any values have been sampled.
+     */
+    bool
+    zero() const
+    {
+        return samples == Counter();
+    }
+
+    void
+    prepare(Info *info, SparseHistData &data)
+    {
+        MCounter::iterator it;
+        data.cmap.clear();
+        for (it = cmap.begin(); it != cmap.end(); it++) {
+            data.cmap[(*it).first] = (*it).second;
+        }
+
+        data.samples = samples;
+    }
+
+    /**
+     * Reset stat value to default
+     */
+    void
+    reset(Info *info)
+    {
+        cmap.clear();
+        samples = 0;
+    }
+};
+
+class SparseHistogram : public SparseHistBase<SparseHistogram, SparseHistStor>
+{
+  public:
+    SparseHistogram(Group *parent = nullptr, const char *name = nullptr,
+                    const char *desc = nullptr)
+        : SparseHistBase<SparseHistogram, SparseHistStor>(parent, name, desc)
+    {
+    }
+
+    /**
+     * Set the parameters of this histogram. @sa HistStor::Params
+     * @param size The number of buckets in the histogram
+     * @return A reference to this histogram.
+     */
+    SparseHistogram &
+    init(size_type size)
+    {
+        SparseHistStor::Params *params = new SparseHistStor::Params;
+        this->setParams(params);
+        this->doInit();
+        return this->self();
+    }
+};
+
 class Temp;
 /**
  * A formula for statistics that is calculated when printed. A formula is
@@ -2608,21 +3020,25 @@ class Formula : public DataWrapVec<Formula, FormulaInfoProxy>
     /**
      * Create and initialize thie formula, and register it with the database.
      */
-    Formula();
+    Formula(Group *parent = nullptr, const char *name = nullptr,
+            const char *desc = nullptr);
 
-    /**
-     * Create a formula with the given root node, register it with the
-     * database.
-     * @param r The root of the expression tree.
-     */
-    Formula(Temp r);
+    Formula(Group *parent, const char *name, const char *desc,
+            const Temp &r);
 
     /**
      * Set an unitialized Formula to the given root.
      * @param r The root of the expression tree.
      * @return a reference to this formula.
      */
-    const Formula &operator=(Temp r);
+    const Formula &operator=(const Temp &r);
+
+    template<typename T>
+    const Formula &operator=(const T &v)
+    {
+        *this = Temp(v);
+        return *this;
+    }
 
     /**
      * Add the given tree to the existing one.
@@ -2630,6 +3046,14 @@ class Formula : public DataWrapVec<Formula, FormulaInfoProxy>
      * @return a reference to this formula.
      */
     const Formula &operator+=(Temp r);
+
+    /**
+     * Divide the existing tree by the given one.
+     * @param r The root of the expression tree.
+     * @return a reference to this formula.
+     */
+    const Formula &operator/=(Temp r);
+
     /**
      * Return the result of the Fomula in a vector.  If there were no Vector
      * components to the Formula, then the vector is size 1.  If there were,
@@ -2703,7 +3127,9 @@ class Temp
      * Copy the given pointer to this class.
      * @param n A pointer to a Node object to copy.
      */
-    Temp(NodePtr n) : node(n) { }
+    Temp(const NodePtr &n) : node(n) { }
+
+    Temp(NodePtr &&n) : node(std::move(n)) { }
 
     /**
      * Return the node pointer.
@@ -2711,6 +3137,11 @@ class Temp
      */
     operator NodePtr&() { return node; }
 
+    /**
+     * Makde gcc < 4.6.3 happy and explicitly get the underlying node.
+     */
+    NodePtr getNodePtr() const { return node; }
+
   public:
     /**
      * Create a new ScalarStatNode.
@@ -2869,83 +3300,102 @@ class Temp
 inline Temp
 operator+(Temp l, Temp r)
 {
-    return NodePtr(new BinaryNode<std::plus<Result> >(l, r));
+    return Temp(std::make_shared<BinaryNode<std::plus<Result> > >(l, r));
 }
 
 inline Temp
 operator-(Temp l, Temp r)
 {
-    return NodePtr(new BinaryNode<std::minus<Result> >(l, r));
+    return Temp(std::make_shared<BinaryNode<std::minus<Result> > >(l, r));
 }
 
 inline Temp
 operator*(Temp l, Temp r)
 {
-    return NodePtr(new BinaryNode<std::multiplies<Result> >(l, r));
+    return Temp(std::make_shared<BinaryNode<std::multiplies<Result> > >(l, r));
 }
 
 inline Temp
 operator/(Temp l, Temp r)
 {
-    return NodePtr(new BinaryNode<std::divides<Result> >(l, r));
+    return Temp(std::make_shared<BinaryNode<std::divides<Result> > >(l, r));
 }
 
 inline Temp
 operator-(Temp l)
 {
-    return NodePtr(new UnaryNode<std::negate<Result> >(l));
+    return Temp(std::make_shared<UnaryNode<std::negate<Result> > >(l));
 }
 
 template <typename T>
 inline Temp
 constant(T val)
 {
-    return NodePtr(new ConstNode<T>(val));
+    return Temp(std::make_shared<ConstNode<T> >(val));
 }
 
 template <typename T>
 inline Temp
 constantVector(T val)
 {
-    return NodePtr(new ConstVectorNode<T>(val));
+    return Temp(std::make_shared<ConstVectorNode<T> >(val));
 }
 
 inline Temp
 sum(Temp val)
 {
-    return NodePtr(new SumNode<std::plus<Result> >(val));
+    return Temp(std::make_shared<SumNode<std::plus<Result> > >(val));
 }
 
+/** Dump all statistics data to the registered outputs */
+void dump();
+void reset();
+void enable();
+bool enabled();
+
 /**
- * Enable the statistics package.  Before the statistics package is
- * enabled, all statistics must be created and initialized and once
- * the package is enabled, no more statistics can be created.
+ * Register reset and dump handlers.  These are the functions which
+ * will actually perform the whole statistics reset/dump actions
+ * including processing the reset/dump callbacks
  */
-void enable();
+typedef void (*Handler)();
+
+void registerHandlers(Handler reset_handler, Handler dump_handler);
 
 /**
- * Prepare all stats for data access.  This must be done before
- * dumping and serialization.
+ * Register a callback that should be called whenever statistics are
+ * reset
  */
-void prepare();
+void registerResetCallback(Callback *cb);
 
 /**
- * Dump all statistics data to the registered outputs
+ * Register a callback that should be called whenever statistics are
+ * about to be dumped
  */
-void dump();
+void registerDumpCallback(Callback *cb);
 
 /**
- * Reset all statistics to the base state
+ * Process all the callbacks in the reset callbacks queue
  */
-void reset();
+void processResetQueue();
+
 /**
- * Register a callback that should be called whenever statistics are
- * reset
+ * Process all the callbacks in the dump callbacks queue
  */
-void registerResetCallback(Callback *cb);
+void processDumpQueue();
 
 std::list<Info *> &statsList();
 
+typedef std::map<const void *, Info *> MapType;
+MapType &statsMap();
+
+typedef std::map<std::string, Info *> NameMapType;
+NameMapType &nameMap();
+
+bool validateStatName(const std::string &name);
+
 } // namespace Stats
 
+void debugDumpStats();
+
 #endif // __BASE_STATISTICS_HH__