Index: tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h =================================================================== --- tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h +++ tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h @@ -149,6 +149,14 @@ template const RegionTy* getAs() const; virtual bool isBoundable() const { return false; } + + /// Get variable name for memory region. The name is obtained from + /// the variable/field declaration retrieved from the memory region. + /// Regions that point to an element of an array are returned as: "arr[0]". + /// Regions that point to a struct are returned as: "st.var". + /// + /// \returns variable name for memory region + std::string getVariableName() const; }; /// MemSpaceRegion - A memory region that represents a "memory space"; Index: tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp =================================================================== --- tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp +++ tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp @@ -639,6 +639,55 @@ superRegion->printPrettyAsExpr(os); } +std::string MemRegion::getVariableName() const { + std::string VariableName{""}; + std::string ArrayIndices{""}; + + const clang::ento::MemRegion *R = this; + llvm::SmallString<50> buf; + llvm::raw_svector_ostream os(buf); + + // Obtain array indices to add them to the variable name. + const clang::ento::ElementRegion *ER = nullptr; + while ((ER = R->getAs())) { + + std::string idx{""}; + if (auto CI = ER->getIndex().getAs()) { + llvm::SmallString<2> intValAsString; + CI->getValue().toString(intValAsString); + idx = {intValAsString.begin(), intValAsString.end()}; + } + + else if (auto SV = + ER->getIndex().getAs()) { + llvm::SmallString<8> buf; + llvm::raw_svector_ostream os(buf); + os << SV->getSymbol(); + idx = os.str(); + } + + ArrayIndices += "]" + idx + "["; + R = ER->getSuperRegion(); + } + + std::reverse(ArrayIndices.begin(), ArrayIndices.end()); + + // Get variable name. + if (R && R->canPrintPretty()) { + R->printPretty(os); + VariableName += os.str(); + } + + // Combine variable name with indices. + if (VariableName.size() && VariableName.back() == '\'') { + VariableName.insert(VariableName.size() - 1, ArrayIndices); + } else { + VariableName += ArrayIndices; + } + + return VariableName; +} + //===----------------------------------------------------------------------===// // MemRegionManager methods. //===----------------------------------------------------------------------===//