Use only explicit bool conversion operator

The most common (non-buggy) case are where such objects are used as
return expressions in bool-returning functions or as boolean function
arguments. In those cases I've used (& added if necessary) a named
function to provide the equivalent (or sometimes negative, depending on
convenient wording) test.

DiagnosticBuilder kept its implicit conversion operator owing to the
prevalent use of it in return statements.

One bug was found in ExprConstant.cpp involving a comparison of two
PointerUnions (PointerUnion did not previously have an operator==, so
instead both operands were converted to bool & then compared). A test
is included in test/SemaCXX/constant-expression-cxx1y.cpp for the fix
(adding operator== to PointerUnion in LLVM).

llvm-svn: 181869
This commit is contained in:
David Blaikie 2013-05-15 07:37:26 +00:00
parent 041f1aa3e2
commit 7d17010db5
45 changed files with 71 additions and 53 deletions

View File

@ -81,7 +81,7 @@ public:
operator QualType() const { return Stored; }
/// \brief Implicit conversion to bool.
operator bool() const { return !isNull(); }
LLVM_EXPLICIT operator bool() const { return !isNull(); }
bool isNull() const {
return Stored.isNull();

View File

@ -228,7 +228,7 @@ inline CXXRecordDecl::friend_iterator CXXRecordDecl::friend_end() const {
}
inline void CXXRecordDecl::pushFriendDecl(FriendDecl *FD) {
assert(FD->NextFriend == 0 && "friend already has next friend?");
assert(!FD->NextFriend && "friend already has next friend?");
FD->NextFriend = data().FirstFriend;
data().FirstFriend = FD;
}

View File

@ -452,7 +452,7 @@ public:
}
/// \brief Determine whether this method has a body.
virtual bool hasBody() const { return Body; }
virtual bool hasBody() const { return Body.isValid(); }
/// \brief Retrieve the body of this method, if it has one.
virtual Stmt *getBody() const;
@ -463,7 +463,7 @@ public:
void setBody(Stmt *B) { Body = B; }
/// \brief Returns whether this specific method is a definition.
bool isThisDeclarationADefinition() const { return Body; }
bool isThisDeclarationADefinition() const { return hasBody(); }
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }

View File

@ -182,11 +182,16 @@ public:
// operator bool() - Evaluates true when this declaration name is
// non-empty.
operator bool() const {
LLVM_EXPLICIT operator bool() const {
return ((Ptr & PtrMask) != 0) ||
(reinterpret_cast<IdentifierInfo *>(Ptr & ~PtrMask));
}
/// \brief Evaluates true when this declaration name is empty.
bool isEmpty() const {
return !*this;
}
/// Predicate functions for querying what type of name this is.
bool isIdentifier() const { return getStoredNameKind() == StoredIdentifier; }
bool isObjCZeroArgSelector() const {

View File

@ -1935,7 +1935,7 @@ public:
/// \brief Determines whether this member expression actually had
/// a C++ nested-name-specifier prior to the name of the member, e.g.,
/// x->Base::foo.
bool hasQualifier() const { return QualifierLoc; }
bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
/// \brief Retrieves the nested-name-specifier that qualifies the type name,
/// with source-location information.

View File

@ -329,7 +329,12 @@ public:
/// \brief Whether this pointer is non-NULL.
///
/// This operation does not require the AST node to be deserialized.
operator bool() const { return Ptr != 0; }
LLVM_EXPLICIT operator bool() const { return Ptr != 0; }
/// \brief Whether this pointer is non-NULL.
///
/// This operation does not require the AST node to be deserialized.
bool isValid() const { return Ptr != 0; }
/// \brief Whether this pointer is currently stored as an offset.
bool isOffset() const { return Ptr & 0x01; }

View File

@ -231,7 +231,11 @@ public:
/// \brief Evalutes true when this nested-name-specifier location is
/// non-empty.
operator bool() const { return Qualifier; }
LLVM_EXPLICIT operator bool() const { return Qualifier; }
/// \brief Evalutes true when this nested-name-specifier location is
/// empty.
bool hasQualifier() const { return Qualifier; }
/// \brief Retrieve the nested-name-specifier to which this instance
/// refers.

View File

@ -15,6 +15,7 @@
#define LLVM_CLANG_AST_STMT_ITR_H
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Compiler.h"
#include <cassert>
#include <cstddef>
#include <iterator>
@ -156,7 +157,7 @@ struct StmtRange : std::pair<StmtIterator,StmtIterator> {
: std::pair<StmtIterator,StmtIterator>(begin, end) {}
bool empty() const { return first == second; }
operator bool() const { return !empty(); }
LLVM_EXPLICIT operator bool() const { return !empty(); }
Stmt *operator->() const { return first.operator->(); }
Stmt *&operator*() const { return first.operator*(); }
@ -199,7 +200,7 @@ struct ConstStmtRange : std::pair<ConstStmtIterator,ConstStmtIterator> {
: std::pair<ConstStmtIterator,ConstStmtIterator>(begin, end) {}
bool empty() const { return first == second; }
operator bool() const { return !empty(); }
LLVM_EXPLICIT operator bool() const { return !empty(); }
const Stmt *operator->() const { return first.operator->(); }
const Stmt *operator*() const { return first.operator*(); }

View File

@ -441,7 +441,7 @@ public:
bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
operator bool() const { return hasQualifiers(); }
LLVM_EXPLICIT operator bool() const { return hasQualifiers(); }
Qualifiers &operator+=(Qualifiers R) {
addQualifiers(R);

View File

@ -90,7 +90,7 @@ public:
}
bool isNull() const { return !Ty; }
operator bool() const { return Ty; }
LLVM_EXPLICIT operator bool() const { return Ty; }
/// \brief Returns the size of type source info data block for the given type.
static unsigned getFullDataSizeForType(QualType Ty);

View File

@ -49,7 +49,7 @@ public:
const char *toString() const { return representation; }
// Overloaded operators for bool like qualities
operator bool() const { return flag; }
LLVM_EXPLICIT operator bool() const { return flag; }
OptionalFlag& operator=(const bool &rhs) {
flag = rhs;
return *this; // Return a reference to myself.

View File

@ -269,7 +269,7 @@ public:
Stmt &operator*() { return *getStmt(); }
const Stmt &operator*() const { return *getStmt(); }
operator bool() const { return getStmt(); }
LLVM_EXPLICIT operator bool() const { return getStmt(); }
};
/// CFGBlock - Represents a single basic block in a source-level CFG.

View File

@ -1212,7 +1212,7 @@ public:
~StoredDiagnostic();
/// \brief Evaluates true when this object stores a diagnostic.
operator bool() const { return Message.size() > 0; }
LLVM_EXPLICIT operator bool() const { return Message.size() > 0; }
unsigned getID() const { return ID; }
DiagnosticsEngine::Level getLevel() const { return Level; }

View File

@ -456,7 +456,7 @@ public:
void setASTContext(ASTContext *ctx) { Ctx = ctx; }
void setPreprocessor(Preprocessor *pp);
bool hasSema() const { return TheSema; }
bool hasSema() const { return TheSema.isValid(); }
Sema &getSema() const {
assert(TheSema && "ASTUnit does not have a Sema object!");
return *TheSema;

View File

@ -395,7 +395,7 @@ public:
/// @name ASTConsumer
/// {
bool hasASTConsumer() const { return Consumer != 0; }
bool hasASTConsumer() const { return Consumer.isValid(); }
ASTConsumer &getASTConsumer() const {
assert(Consumer && "Compiler instance has no AST consumer!");
@ -413,7 +413,7 @@ public:
/// }
/// @name Semantic analysis
/// {
bool hasSema() const { return TheSema != 0; }
bool hasSema() const { return TheSema.isValid(); }
Sema &getSema() const {
assert(TheSema && "Compiler instance has no Sema object!");
@ -433,7 +433,9 @@ public:
/// @name Code Completion
/// {
bool hasCodeCompletionConsumer() const { return CompletionConsumer != 0; }
bool hasCodeCompletionConsumer() const {
return CompletionConsumer.isValid();
}
CodeCompleteConsumer &getCodeCompletionConsumer() const {
assert(CompletionConsumer &&
@ -455,7 +457,7 @@ public:
/// @name Frontend timer
/// {
bool hasFrontendTimer() const { return FrontendTimer != 0; }
bool hasFrontendTimer() const { return FrontendTimer.isValid(); }
llvm::Timer &getFrontendTimer() const {
assert(FrontendTimer && "Compiler instance has no frontend timer!");

View File

@ -116,7 +116,7 @@ public:
bool isCurrentFileAST() const {
assert(!CurrentInput.isEmpty() && "No current file!");
return CurrentASTUnit != 0;
return CurrentASTUnit.isValid();
}
const FrontendInputFile &getCurrentInput() const {

View File

@ -264,7 +264,7 @@ public:
/// \brief Checks whether the map exists or not.
bool HasIncludeAliasMap() const {
return IncludeAliases;
return IncludeAliases.isValid();
}
/// \brief Map the source include name to the dest include name.

View File

@ -421,7 +421,7 @@ public:
bool isValid() const { return DefDirective != 0; }
bool isInvalid() const { return !isValid(); }
operator bool() const { return isValid(); }
LLVM_EXPLICIT operator bool() const { return isValid(); }
inline DefInfo getPreviousDefinition(bool AllowHidden = false);
const DefInfo getPreviousDefinition(bool AllowHidden = false) const {

View File

@ -80,7 +80,7 @@ class ModuleMap {
// \brief Whether this known header is valid (i.e., it has an
// associated module).
operator bool() const { return Storage.getPointer() != 0; }
LLVM_EXPLICIT operator bool() const { return Storage.getPointer() != 0; }
};
typedef llvm::DenseMap<const FileEntry *, KnownHeader> HeadersMap;

View File

@ -1400,7 +1400,7 @@ private:
bool InCachingLexMode() const {
// If the Lexer pointers are 0 and IncludeMacroStack is empty, it means
// that we are past EOF, not that we are in CachingLex mode.
return CurPPLexer == 0 && CurTokenLexer == 0 && CurPTHLexer == 0 &&
return !CurPPLexer && !CurTokenLexer && !CurPTHLexer &&
!IncludeMacroStack.empty();
}
void EnterCachingLexMode();

View File

@ -841,7 +841,7 @@ public:
void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
/// \brief Determine whether the initialization sequence is valid.
operator bool() const { return !Failed(); }
LLVM_EXPLICIT operator bool() const { return !Failed(); }
/// \brief Determine whether the initialization sequence is invalid.
bool Failed() const { return SequenceKind == FailedSequence; }

View File

@ -65,7 +65,7 @@ namespace clang {
Ptr = Traits::getAsVoidPointer(P);
}
operator bool() const { return Ptr != 0; }
LLVM_EXPLICIT operator bool() const { return Ptr != 0; }
void *getAsOpaquePtr() const { return Ptr; }
static OpaquePtr getFromOpaquePtr(void *P) { return OpaquePtr(P); }

View File

@ -5994,7 +5994,7 @@ public:
/// \brief Determines whether we have exceeded the maximum
/// recursive template instantiations.
operator bool() const { return Invalid; }
LLVM_EXPLICIT operator bool() const { return Invalid; }
private:
Sema &SemaRef;

View File

@ -140,7 +140,7 @@ public:
}
/// \brief Returns whether this TypoCorrection has a non-empty DeclarationName
operator bool() const { return bool(CorrectionName); }
LLVM_EXPLICIT operator bool() const { return bool(CorrectionName); }
/// \brief Mark this TypoCorrection as being a keyword.
/// Since addCorrectionDeclsand setCorrectionDecl don't allow NULL to be

View File

@ -1232,7 +1232,7 @@ public:
void setDeserializationListener(ASTDeserializationListener *Listener);
/// \brief Determine whether this AST reader has a global index.
bool hasGlobalIndex() const { return GlobalIndex; }
bool hasGlobalIndex() const { return GlobalIndex.isValid(); }
/// \brief Attempts to load the global index.
///

View File

@ -504,7 +504,7 @@ public:
}
bool hasCallStackHint() {
return (CallStackHint != 0);
return CallStackHint.isValid();
}
/// Produce the hint for the given node. The node contains

View File

@ -505,7 +505,7 @@ struct ImplicitNullDerefEvent {
struct DefaultBool {
bool val;
DefaultBool() : val(false) {}
operator bool() const { return val; }
LLVM_EXPLICIT operator bool() const { return val; }
DefaultBool &operator=(bool b) { val = b; return *this; }
};

View File

@ -231,7 +231,7 @@ public:
bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
SVal val);
operator bool() { return First && Binding; }
LLVM_EXPLICIT operator bool() { return First && Binding; }
const MemRegion *getRegion() { return Binding; }
};

View File

@ -1329,7 +1329,7 @@ void ASTDumper::dumpStmt(const Stmt *S) {
return;
}
setMoreChildren(S->children());
setMoreChildren(!S->children().empty());
ConstStmtVisitor<ASTDumper>::Visit(S);
setMoreChildren(false);
for (Stmt::const_child_range CI = S->children(); CI; ++CI) {

View File

@ -2878,7 +2878,7 @@ Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
if (Importer.IsStructurallyEquivalent(D->getType(),
FoundField->getType(),
Name)) {
!Name.isEmpty())) {
Importer.Imported(D, FoundField);
return FoundField;
}

View File

@ -2319,7 +2319,7 @@ bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
const FunctionDecl *Prev = this;
bool FoundBody = false;
while ((Prev = Prev->getPreviousDecl())) {
FoundBody |= Prev->Body;
FoundBody |= Prev->Body.isValid();
if (Prev->Body) {
// If it's not the case that both 'inline' and 'extern' are
@ -2347,7 +2347,7 @@ bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
const FunctionDecl *Prev = this;
bool FoundBody = false;
while ((Prev = Prev->getPreviousDecl())) {
FoundBody |= Prev->Body;
FoundBody |= Prev->Body.isValid();
if (RedeclForcesDefC99(Prev))
return false;
}

View File

@ -423,7 +423,7 @@ DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
FoundD = 0;
std::size_t Size = sizeof(DeclRefExpr);
if (QualifierLoc != 0)
if (QualifierLoc)
Size += sizeof(NestedNameSpecifierLoc);
if (FoundD)
Size += sizeof(NamedDecl *);

View File

@ -1809,7 +1809,7 @@ struct CompleteObject {
assert(Value && "missing value for complete object");
}
operator bool() const { return Value; }
LLVM_EXPLICIT operator bool() const { return Value; }
};
/// Find the designated sub-object of an rvalue.

View File

@ -155,7 +155,7 @@ public:
return !(*this == rhs);
}
operator bool() const {
LLVM_EXPLICIT operator bool() const {
return *this != const_iterator();
}

View File

@ -2422,7 +2422,7 @@ public:
return ConstantEmission(C, false);
}
operator bool() const { return ValueAndIsReference.getOpaqueValue() != 0; }
LLVM_EXPLICIT operator bool() const { return ValueAndIsReference.getOpaqueValue() != 0; }
bool isReference() const { return ValueAndIsReference.getInt(); }
LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {

View File

@ -82,7 +82,7 @@ const HeaderMap *HeaderMap::Create(const FileEntry *FE, FileManager &FM) {
if (FileSize <= sizeof(HMapHeader)) return 0;
OwningPtr<const llvm::MemoryBuffer> FileBuffer(FM.getBufferForFile(FE));
if (FileBuffer == 0) return 0; // Unreadable file?
if (!FileBuffer) return 0; // Unreadable file?
const char *FileStart = FileBuffer->getBufferStart();
// We know the file is at least as big as the header, check it now.

View File

@ -241,7 +241,7 @@ void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
bool FoundElse,
SourceLocation ElseLoc) {
++NumSkipped;
assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
FoundNonSkipPortion, FoundElse);

View File

@ -70,7 +70,7 @@ PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
/// start lexing tokens from it instead of the current buffer.
void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
SourceLocation Loc) {
assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
++NumEnteredSourceFiles;
if (MaxIncludeStackDepth < IncludeMacroStack.size())

View File

@ -2524,7 +2524,7 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
// erroneous: We already checked about that it has no type specifier, and
// C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
// typename.
if (TypeRep == 0) {
if (!TypeRep) {
ConsumeToken(); // Eat the scope spec so the identifier is current.
ParsedAttributesWithRange Attrs(AttrFactory);
if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {

View File

@ -463,7 +463,7 @@ public:
}
}
bool ok() { return FileStream; }
bool ok() { return FileStream.isValid(); }
raw_ostream &getStream() { return *FileStream; }
private:

View File

@ -9307,7 +9307,7 @@ void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
QualType OtherRefType = Other->getType()->
getAs<RValueReferenceType>()->getPointeeType();
assert(OtherRefType.getQualifiers() == 0 &&
assert(!OtherRefType.getQualifiers() &&
"Bad argument type of defaulted move assignment");
// Our location for everything implicitly-generated.

View File

@ -2945,7 +2945,7 @@ Decl *Sema::ActOnMethodDeclaration(
QualType ArgType;
TypeSourceInfo *DI;
if (ArgInfo[i].Type == 0) {
if (!ArgInfo[i].Type) {
ArgType = Context.getObjCIdType();
DI = 0;
} else {

View File

@ -4468,7 +4468,7 @@ Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
ExprResult
Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
SourceLocation RParenLoc, Expr *InitExpr) {
assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
assert(Ty && "ActOnCompoundLiteral(): missing type");
// FIXME: put back this assert when initializers are worked out.
//assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");

View File

@ -250,11 +250,12 @@ namespace lifetime {
}
namespace const_modify {
constexpr int modify(int &n) { return n = 1; } // expected-note {{modification of object of const-qualified type 'const int'}}
constexpr int modify(int &n) { return n = 1; } // expected-note 2 {{modification of object of const-qualified type 'const int'}}
constexpr int test1() { int k = 0; return modify(k); }
constexpr int test2() { const int k = 0; return modify(const_cast<int&>(k)); } // expected-note {{in call}}
constexpr int test2() { const int k = 0; return modify(const_cast<int&>(k)); } // expected-note 2 {{in call}}
static_assert(test1() == 1, "");
static_assert(test2() == 1, ""); // expected-error {{constant expression}} expected-note {{in call}}
constexpr int i = test2(); // expected-error {{constant expression}} expected-note {{in call}}
}
namespace null {

View File

@ -453,7 +453,7 @@ TEST(ParseFixedCompilationDatabase, ReturnsArgumentsAfterDoubleDash) {
const char *Argv[] = { "1", "2", "--\0no-constant-folding", "3", "4" };
OwningPtr<FixedCompilationDatabase> Database(
FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
ASSERT_TRUE(Database);
ASSERT_TRUE(Database.isValid());
std::vector<CompileCommand> Result =
Database->getCompileCommands("source");
ASSERT_EQ(1ul, Result.size());
@ -472,7 +472,7 @@ TEST(ParseFixedCompilationDatabase, ReturnsEmptyCommandLine) {
const char *Argv[] = { "1", "2", "--\0no-constant-folding" };
OwningPtr<FixedCompilationDatabase> Database(
FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
ASSERT_TRUE(Database);
ASSERT_TRUE(Database.isValid());
std::vector<CompileCommand> Result =
Database->getCompileCommands("source");
ASSERT_EQ(1ul, Result.size());