Index: include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h =================================================================== --- include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h +++ include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h @@ -150,6 +150,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: lib/StaticAnalyzer/Core/MemRegion.cpp =================================================================== --- lib/StaticAnalyzer/Core/MemRegion.cpp +++ lib/StaticAnalyzer/Core/MemRegion.cpp @@ -632,6 +632,50 @@ superRegion->printPrettyAsExpr(os); } +std::string MemRegion::getVariableName() const { + std::string VariableName; + std::string ArrayIndices; + const MemRegion *R = this; + SmallString<50> buf; + llvm::raw_svector_ostream os(buf); + + // Obtain array indices to add them to the variable name. + const ElementRegion *ER = nullptr; + while ((ER = R->getAs())) { + // Index is a ConcreteInt. + if (auto CI = ER->getIndex().getAs()) { + llvm::SmallString<2> intValAsString; + CI->getValue().toString(intValAsString); + ArrayIndices = + (llvm::Twine("[") + intValAsString.str() + "]" + ArrayIndices).str(); + } + // If not a ConcreteInt, try to obtain the variable + // name by calling 'getVariableName()' recursively. + else { + std::string idx = ER->getVariableName(); + if (!idx.empty()) { + // Substring to exclude single quotes surrounding the index var name. + ArrayIndices = (llvm::Twine("[") + idx.substr(1, idx.size() - 2) + "]" + + ArrayIndices) + .str(); + } + } + R = ER->getSuperRegion(); + } + + // Get variable name. + if (R && R->canPrintPretty()) { + R->printPretty(os); + VariableName = os.str(); + // Combine variable name with indices. Place indices before second single + // quote created by printPretty. 'varName' + [..] -> 'varName[..]' + VariableName.insert(VariableName.size() - 1, ArrayIndices); + } + + return VariableName; +} + + //===----------------------------------------------------------------------===// // MemRegionManager methods. //===----------------------------------------------------------------------===//