diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -290,6 +290,11 @@ - Introduced the new function ``clang_CXXMethod_isExplicit``, which identifies whether a constructor or conversion function cursor was marked with the explicit identifier. +- Added check in ``clang_getFieldDeclBitWidth`` for whether a bit field + has an evaluable bit width. Fixes undefined behavior when called on a + bit field whose width depends on a template paramter. +- Added function ``clang_isFieldDeclBitWidthDependent`` to check if a + bit field's width depends on a template parameter. Static Analyzer --------------- diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h --- a/clang/include/clang-c/Index.h +++ b/clang/include/clang-c/Index.h @@ -2887,10 +2887,19 @@ CINDEX_LINKAGE unsigned long long clang_getEnumConstantDeclUnsignedValue(CXCursor C); +/** + * Returns non-zero if a bit field's width depends on template parameters. + * + * If the cursor does not reference a bit field declaration or if the bit + * field's width does not depend on template parameters, 0 is returned. + */ +CINDEX_LINKAGE unsigned clang_isFieldDeclBitWidthDependent(CXCursor C); + /** * Retrieve the bit width of a bit field declaration as an integer. * - * If a cursor that is not a bit field declaration is passed in, -1 is returned. + * If a cursor that is not a bit field declaration is passed in, or if the bit + * field's width expression cannot be evaluated, -1 is returned. */ CINDEX_LINKAGE int clang_getFieldDeclBitWidth(CXCursor C); diff --git a/clang/tools/libclang/CXType.cpp b/clang/tools/libclang/CXType.cpp --- a/clang/tools/libclang/CXType.cpp +++ b/clang/tools/libclang/CXType.cpp @@ -10,11 +10,11 @@ // //===--------------------------------------------------------------------===// +#include "CXType.h" #include "CIndexer.h" #include "CXCursor.h" #include "CXString.h" #include "CXTranslationUnit.h" -#include "CXType.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" @@ -371,6 +371,21 @@ return ULLONG_MAX; } +unsigned clang_isFieldDeclBitWidthDependent(CXCursor C) { + using namespace cxcursor; + + if (clang_isDeclaration(C.kind)) { + const Decl *D = getCursorDecl(C); + + if (const FieldDecl *FD = dyn_cast_or_null(D)) { + if (FD->isBitField() && FD->getBitWidth()->isValueDependent()) + return 1; + } + } + + return 0; +} + int clang_getFieldDeclBitWidth(CXCursor C) { using namespace cxcursor; @@ -378,7 +393,7 @@ const Decl *D = getCursorDecl(C); if (const FieldDecl *FD = dyn_cast_or_null(D)) { - if (FD->isBitField()) + if (FD->isBitField() && !FD->getBitWidth()->isValueDependent()) return FD->getBitWidthValue(getCursorContext(C)); } }