Page MenuHomePhabricator

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp
===================================================================
--- cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp (revision 209799)
+++ cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp (revision 209800)
@@ -1,2814 +1,2814 @@
//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang attribute processing code
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/StringMatcher.h"
#include "llvm/TableGen/TableGenBackend.h"
#include <algorithm>
#include <cctype>
#include <memory>
#include <set>
#include <sstream>
using namespace llvm;
class FlattenedSpelling {
std::string V, N, NS;
bool K;
public:
FlattenedSpelling(const std::string &Variety, const std::string &Name,
const std::string &Namespace, bool KnownToGCC) :
V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
explicit FlattenedSpelling(const Record &Spelling) :
V(Spelling.getValueAsString("Variety")),
N(Spelling.getValueAsString("Name")) {
assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
"flattened!");
if (V == "CXX11")
NS = Spelling.getValueAsString("Namespace");
bool Unset;
K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
}
const std::string &variety() const { return V; }
const std::string &name() const { return N; }
const std::string &nameSpace() const { return NS; }
bool knownToGCC() const { return K; }
};
std::vector<FlattenedSpelling> GetFlattenedSpellings(const Record &Attr) {
std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
std::vector<FlattenedSpelling> Ret;
for (const auto &Spelling : Spellings) {
if (Spelling->getValueAsString("Variety") == "GCC") {
// Gin up two new spelling objects to add into the list.
Ret.push_back(FlattenedSpelling("GNU", Spelling->getValueAsString("Name"),
"", true));
Ret.push_back(FlattenedSpelling(
"CXX11", Spelling->getValueAsString("Name"), "gnu", true));
} else
Ret.push_back(FlattenedSpelling(*Spelling));
}
return Ret;
}
static std::string ReadPCHRecord(StringRef type) {
return StringSwitch<std::string>(type)
.EndsWith("Decl *", "GetLocalDeclAs<"
+ std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
.Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
.Case("Expr *", "ReadExpr(F)")
.Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
.Default("Record[Idx++]");
}
// Assumes that the way to get the value is SA->getname()
static std::string WritePCHRecord(StringRef type, StringRef name) {
return StringSwitch<std::string>(type)
.EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
", Record);\n")
.Case("TypeSourceInfo *",
"AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
.Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
.Case("IdentifierInfo *",
"AddIdentifierRef(" + std::string(name) + ", Record);\n")
.Default("Record.push_back(" + std::string(name) + ");\n");
}
// Normalize attribute name by removing leading and trailing
// underscores. For example, __foo, foo__, __foo__ would
// become foo.
static StringRef NormalizeAttrName(StringRef AttrName) {
if (AttrName.startswith("__"))
AttrName = AttrName.substr(2, AttrName.size());
if (AttrName.endswith("__"))
AttrName = AttrName.substr(0, AttrName.size() - 2);
return AttrName;
}
// Normalize the name by removing any and all leading and trailing underscores.
// This is different from NormalizeAttrName in that it also handles names like
// _pascal and __pascal.
static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
while (Name.startswith("_"))
Name = Name.substr(1, Name.size());
while (Name.endswith("_"))
Name = Name.substr(0, Name.size() - 1);
return Name;
}
// Normalize attribute spelling only if the spelling has both leading
// and trailing underscores. For example, __ms_struct__ will be
// normalized to "ms_struct"; __cdecl will remain intact.
static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
}
return AttrSpelling;
}
typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
ParsedAttrMap *Dupes = nullptr) {
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
std::set<std::string> Seen;
ParsedAttrMap R;
for (const auto *Attr : Attrs) {
if (Attr->getValueAsBit("SemaHandler")) {
std::string AN;
if (Attr->isSubClassOf("TargetSpecificAttr") &&
!Attr->isValueUnset("ParseKind")) {
AN = Attr->getValueAsString("ParseKind");
// If this attribute has already been handled, it does not need to be
// handled again.
if (Seen.find(AN) != Seen.end()) {
if (Dupes)
Dupes->push_back(std::make_pair(AN, Attr));
continue;
}
Seen.insert(AN);
} else
AN = NormalizeAttrName(Attr->getName()).str();
R.push_back(std::make_pair(AN, Attr));
}
}
return R;
}
namespace {
class Argument {
std::string lowerName, upperName;
StringRef attrName;
bool isOpt;
public:
Argument(const Record &Arg, StringRef Attr)
: lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
attrName(Attr), isOpt(false) {
if (!lowerName.empty()) {
lowerName[0] = std::tolower(lowerName[0]);
upperName[0] = std::toupper(upperName[0]);
}
}
virtual ~Argument() {}
StringRef getLowerName() const { return lowerName; }
StringRef getUpperName() const { return upperName; }
StringRef getAttrName() const { return attrName; }
bool isOptional() const { return isOpt; }
void setOptional(bool set) { isOpt = set; }
// These functions print the argument contents formatted in different ways.
virtual void writeAccessors(raw_ostream &OS) const = 0;
virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
virtual void writeCloneArgs(raw_ostream &OS) const = 0;
virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
virtual void writeCtorBody(raw_ostream &OS) const {}
virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
virtual void writeCtorParameters(raw_ostream &OS) const = 0;
virtual void writeDeclarations(raw_ostream &OS) const = 0;
virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
virtual void writePCHWrite(raw_ostream &OS) const = 0;
virtual void writeValue(raw_ostream &OS) const = 0;
virtual void writeDump(raw_ostream &OS) const = 0;
virtual void writeDumpChildren(raw_ostream &OS) const {}
virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
virtual bool isEnumArg() const { return false; }
virtual bool isVariadicEnumArg() const { return false; }
virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
OS << getUpperName();
}
};
class SimpleArgument : public Argument {
std::string type;
public:
SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
: Argument(Arg, Attr), type(T)
{}
std::string getType() const { return type; }
void writeAccessors(raw_ostream &OS) const override {
OS << " " << type << " get" << getUpperName() << "() const {\n";
OS << " return " << getLowerName() << ";\n";
OS << " }";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "()";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "(" << getUpperName() << ")";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "()";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << type << " " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
OS << type << " " << getLowerName() << ";";
}
void writePCHReadDecls(raw_ostream &OS) const override {
std::string read = ReadPCHRecord(type);
OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " " << WritePCHRecord(type, "SA->get" +
std::string(getUpperName()) + "()");
}
void writeValue(raw_ostream &OS) const override {
if (type == "FunctionDecl *") {
OS << "\" << get" << getUpperName()
<< "()->getNameInfo().getAsString() << \"";
} else if (type == "IdentifierInfo *") {
OS << "\" << get" << getUpperName() << "()->getName() << \"";
} else if (type == "TypeSourceInfo *") {
OS << "\" << get" << getUpperName() << "().getAsString() << \"";
} else {
OS << "\" << get" << getUpperName() << "() << \"";
}
}
void writeDump(raw_ostream &OS) const override {
if (type == "FunctionDecl *") {
OS << " OS << \" \";\n";
OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
} else if (type == "IdentifierInfo *") {
OS << " OS << \" \" << SA->get" << getUpperName()
<< "()->getName();\n";
} else if (type == "TypeSourceInfo *") {
OS << " OS << \" \" << SA->get" << getUpperName()
<< "().getAsString();\n";
} else if (type == "bool") {
OS << " if (SA->get" << getUpperName() << "()) OS << \" "
<< getUpperName() << "\";\n";
} else if (type == "int" || type == "unsigned") {
OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
} else {
llvm_unreachable("Unknown SimpleArgument type!");
}
}
};
class DefaultSimpleArgument : public SimpleArgument {
int64_t Default;
public:
DefaultSimpleArgument(const Record &Arg, StringRef Attr,
std::string T, int64_t Default)
: SimpleArgument(Arg, Attr, T), Default(Default) {}
void writeAccessors(raw_ostream &OS) const override {
SimpleArgument::writeAccessors(OS);
OS << "\n\n static const " << getType() << " Default" << getUpperName()
<< " = " << Default << ";";
}
};
class StringArgument : public Argument {
public:
StringArgument(const Record &Arg, StringRef Attr)
: Argument(Arg, Attr)
{}
void writeAccessors(raw_ostream &OS) const override {
OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
OS << " return llvm::StringRef(" << getLowerName() << ", "
<< getLowerName() << "Length);\n";
OS << " }\n";
OS << " unsigned get" << getUpperName() << "Length() const {\n";
OS << " return " << getLowerName() << "Length;\n";
OS << " }\n";
OS << " void set" << getUpperName()
<< "(ASTContext &C, llvm::StringRef S) {\n";
OS << " " << getLowerName() << "Length = S.size();\n";
OS << " this->" << getLowerName() << " = new (C, 1) char ["
<< getLowerName() << "Length];\n";
OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
<< getLowerName() << "Length);\n";
OS << " }";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << "get" << getUpperName() << "()";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "()";
}
void writeCtorBody(raw_ostream &OS) const override {
OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
<< ".data(), " << getLowerName() << "Length);";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
<< getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
<< "Length])";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "Length(0)," << getLowerName() << "(0)";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << "llvm::StringRef " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
OS << "unsigned " << getLowerName() << "Length;\n";
OS << "char *" << getLowerName() << ";";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " std::string " << getLowerName()
<< "= ReadString(Record, Idx);\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " AddString(SA->get" << getUpperName() << "(), Record);\n";
}
void writeValue(raw_ostream &OS) const override {
OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
}
void writeDump(raw_ostream &OS) const override {
OS << " OS << \" \\\"\" << SA->get" << getUpperName()
<< "() << \"\\\"\";\n";
}
};
class AlignedArgument : public Argument {
public:
AlignedArgument(const Record &Arg, StringRef Attr)
: Argument(Arg, Attr)
{}
void writeAccessors(raw_ostream &OS) const override {
OS << " bool is" << getUpperName() << "Dependent() const;\n";
OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
OS << " bool is" << getUpperName() << "Expr() const {\n";
OS << " return is" << getLowerName() << "Expr;\n";
OS << " }\n";
OS << " Expr *get" << getUpperName() << "Expr() const {\n";
OS << " assert(is" << getLowerName() << "Expr);\n";
OS << " return " << getLowerName() << "Expr;\n";
OS << " }\n";
OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
OS << " assert(!is" << getLowerName() << "Expr);\n";
OS << " return " << getLowerName() << "Type;\n";
OS << " }";
}
void writeAccessorDefinitions(raw_ostream &OS) const override {
OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
<< "Dependent() const {\n";
OS << " if (is" << getLowerName() << "Expr)\n";
OS << " return " << getLowerName() << "Expr && (" << getLowerName()
<< "Expr->isValueDependent() || " << getLowerName()
<< "Expr->isTypeDependent());\n";
OS << " else\n";
OS << " return " << getLowerName()
<< "Type->getType()->isDependentType();\n";
OS << "}\n";
// FIXME: Do not do the calculation here
// FIXME: Handle types correctly
// A null pointer means maximum alignment
// FIXME: Load the platform-specific maximum alignment, rather than
// 16, the x86 max.
OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
<< "(ASTContext &Ctx) const {\n";
OS << " assert(!is" << getUpperName() << "Dependent());\n";
OS << " if (is" << getLowerName() << "Expr)\n";
OS << " return (" << getLowerName() << "Expr ? " << getLowerName()
<< "Expr->EvaluateKnownConstInt(Ctx).getZExtValue() : 16)"
<< "* Ctx.getCharWidth();\n";
OS << " else\n";
OS << " return 0; // FIXME\n";
OS << "}\n";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << "is" << getLowerName() << "Expr, is" << getLowerName()
<< "Expr ? static_cast<void*>(" << getLowerName()
<< "Expr) : " << getLowerName()
<< "Type";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
// FIXME: move the definition in Sema::InstantiateAttrs to here.
// In the meantime, aligned attributes are cloned.
}
void writeCtorBody(raw_ostream &OS) const override {
OS << " if (is" << getLowerName() << "Expr)\n";
OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
<< getUpperName() << ");\n";
OS << " else\n";
OS << " " << getLowerName()
<< "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
<< ");";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << "is" << getLowerName() << "Expr(false)";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
}
void writeImplicitCtorArgs(raw_ostream &OS) const override {
OS << "Is" << getUpperName() << "Expr, " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
OS << "bool is" << getLowerName() << "Expr;\n";
OS << "union {\n";
OS << "Expr *" << getLowerName() << "Expr;\n";
OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
OS << "};";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " bool is" << getLowerName() << "Expr = Record[Idx++];\n";
OS << " void *" << getLowerName() << "Ptr;\n";
OS << " if (is" << getLowerName() << "Expr)\n";
OS << " " << getLowerName() << "Ptr = ReadExpr(F);\n";
OS << " else\n";
OS << " " << getLowerName()
<< "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
OS << " if (SA->is" << getUpperName() << "Expr())\n";
OS << " AddStmt(SA->get" << getUpperName() << "Expr());\n";
OS << " else\n";
OS << " AddTypeSourceInfo(SA->get" << getUpperName()
<< "Type(), Record);\n";
}
void writeValue(raw_ostream &OS) const override {
OS << "\";\n"
<< " " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n"
<< " OS << \"";
}
void writeDump(raw_ostream &OS) const override {
}
void writeDumpChildren(raw_ostream &OS) const override {
OS << " if (SA->is" << getUpperName() << "Expr()) {\n";
OS << " lastChild();\n";
OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
OS << " } else\n";
OS << " dumpType(SA->get" << getUpperName()
<< "Type()->getType());\n";
}
void writeHasChildren(raw_ostream &OS) const override {
OS << "SA->is" << getUpperName() << "Expr()";
}
};
class VariadicArgument : public Argument {
std::string Type, ArgName, ArgSizeName, RangeName;
public:
VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
: Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}
std::string getType() const { return Type; }
void writeAccessors(raw_ostream &OS) const override {
std::string IteratorType = getLowerName().str() + "_iterator";
std::string BeginFn = getLowerName().str() + "_begin()";
std::string EndFn = getLowerName().str() + "_end()";
OS << " typedef " << Type << "* " << IteratorType << ";\n";
OS << " " << IteratorType << " " << BeginFn << " const {"
<< " return " << ArgName << "; }\n";
OS << " " << IteratorType << " " << EndFn << " const {"
<< " return " << ArgName << " + " << ArgSizeName << "; }\n";
OS << " unsigned " << getLowerName() << "_size() const {"
<< " return " << ArgSizeName << "; }\n";
OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
<< "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
<< "); }\n";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << ArgName << ", " << ArgSizeName;
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
// This isn't elegant, but we have to go through public methods...
OS << "A->" << getLowerName() << "_begin(), "
<< "A->" << getLowerName() << "_size()";
}
void writeCtorBody(raw_ostream &OS) const override {
OS << " std::copy(" << getUpperName() << ", " << getUpperName()
<< " + " << ArgSizeName << ", " << ArgName << ");";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << ArgSizeName << "(" << getUpperName() << "Size), "
<< ArgName << "(new (Ctx, 16) " << getType() << "["
<< ArgSizeName << "])";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << getType() << " *" << getUpperName() << ", unsigned "
<< getUpperName() << "Size";
}
void writeImplicitCtorArgs(raw_ostream &OS) const override {
OS << getUpperName() << ", " << getUpperName() << "Size";
}
void writeDeclarations(raw_ostream &OS) const override {
OS << " unsigned " << ArgSizeName << ";\n";
OS << " " << getType() << " *" << ArgName << ";";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
OS << " SmallVector<" << Type << ", 4> " << getLowerName()
<< ";\n";
OS << " " << getLowerName() << ".reserve(" << getLowerName()
<< "Size);\n";
OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
std::string read = ReadPCHRecord(Type);
OS << " " << getLowerName() << ".push_back(" << read << ");\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName() << ".data(), " << getLowerName() << "Size";
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
OS << " for (auto &Val : SA->" << RangeName << "())\n";
OS << " " << WritePCHRecord(Type, "Val");
}
void writeValue(raw_ostream &OS) const override {
OS << "\";\n";
OS << " bool isFirst = true;\n"
<< " for (const auto &Val : " << RangeName << "()) {\n"
<< " if (isFirst) isFirst = false;\n"
<< " else OS << \", \";\n"
<< " OS << Val;\n"
<< " }\n";
OS << " OS << \"";
}
void writeDump(raw_ostream &OS) const override {
OS << " for (const auto &Val : SA->" << RangeName << "())\n";
OS << " OS << \" \" << Val;\n";
}
};
// Unique the enums, but maintain the original declaration ordering.
std::vector<std::string>
uniqueEnumsInOrder(const std::vector<std::string> &enums) {
std::vector<std::string> uniques;
std::set<std::string> unique_set(enums.begin(), enums.end());
for (const auto &i : enums) {
std::set<std::string>::iterator set_i = unique_set.find(i);
if (set_i != unique_set.end()) {
uniques.push_back(i);
unique_set.erase(set_i);
}
}
return uniques;
}
class EnumArgument : public Argument {
std::string type;
std::vector<std::string> values, enums, uniques;
public:
EnumArgument(const Record &Arg, StringRef Attr)
: Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
values(Arg.getValueAsListOfStrings("Values")),
enums(Arg.getValueAsListOfStrings("Enums")),
uniques(uniqueEnumsInOrder(enums))
{
// FIXME: Emit a proper error
assert(!uniques.empty());
}
bool isEnumArg() const override { return true; }
void writeAccessors(raw_ostream &OS) const override {
OS << " " << type << " get" << getUpperName() << "() const {\n";
OS << " return " << getLowerName() << ";\n";
OS << " }";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "()";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "(" << getUpperName() << ")";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "(" << type << "(0))";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << type << " " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
std::vector<std::string>::const_iterator i = uniques.begin(),
e = uniques.end();
// The last one needs to not have a comma.
--e;
OS << "public:\n";
OS << " enum " << type << " {\n";
for (; i != e; ++i)
OS << " " << *i << ",\n";
OS << " " << *e << "\n";
OS << " };\n";
OS << "private:\n";
OS << " " << type << " " << getLowerName() << ";";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
<< "(static_cast<" << getAttrName() << "Attr::" << type
<< ">(Record[Idx++]));\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writePCHWrite(raw_ostream &OS) const override {
OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
}
void writeValue(raw_ostream &OS) const override {
OS << "\" << get" << getUpperName() << "() << \"";
}
void writeDump(raw_ostream &OS) const override {
OS << " switch(SA->get" << getUpperName() << "()) {\n";
for (const auto &I : uniques) {
OS << " case " << getAttrName() << "Attr::" << I << ":\n";
OS << " OS << \" " << I << "\";\n";
OS << " break;\n";
}
OS << " }\n";
}
void writeConversion(raw_ostream &OS) const {
OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
OS << type << " &Out) {\n";
OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
OS << type << ">>(Val)\n";
for (size_t I = 0; I < enums.size(); ++I) {
OS << " .Case(\"" << values[I] << "\", ";
OS << getAttrName() << "Attr::" << enums[I] << ")\n";
}
OS << " .Default(Optional<" << type << ">());\n";
OS << " if (R) {\n";
OS << " Out = *R;\n return true;\n }\n";
OS << " return false;\n";
OS << " }\n";
}
};
class VariadicEnumArgument: public VariadicArgument {
std::string type, QualifiedTypeName;
std::vector<std::string> values, enums, uniques;
public:
VariadicEnumArgument(const Record &Arg, StringRef Attr)
: VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
type(Arg.getValueAsString("Type")),
values(Arg.getValueAsListOfStrings("Values")),
enums(Arg.getValueAsListOfStrings("Enums")),
uniques(uniqueEnumsInOrder(enums))
{
QualifiedTypeName = getAttrName().str() + "Attr::" + type;
// FIXME: Emit a proper error
assert(!uniques.empty());
}
bool isVariadicEnumArg() const override { return true; }
void writeDeclarations(raw_ostream &OS) const override {
std::vector<std::string>::const_iterator i = uniques.begin(),
e = uniques.end();
// The last one needs to not have a comma.
--e;
OS << "public:\n";
OS << " enum " << type << " {\n";
for (; i != e; ++i)
OS << " " << *i << ",\n";
OS << " " << *e << "\n";
OS << " };\n";
OS << "private:\n";
VariadicArgument::writeDeclarations(OS);
}
void writeDump(raw_ostream &OS) const override {
OS << " for (" << getAttrName() << "Attr::" << getLowerName()
<< "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
<< getLowerName() << "_end(); I != E; ++I) {\n";
OS << " switch(*I) {\n";
for (const auto &UI : uniques) {
OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
OS << " OS << \" " << UI << "\";\n";
OS << " break;\n";
}
OS << " }\n";
OS << " }\n";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
<< ";\n";
OS << " " << getLowerName() << ".reserve(" << getLowerName()
<< "Size);\n";
OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
OS << " " << getLowerName() << ".push_back(" << "static_cast<"
<< QualifiedTypeName << ">(Record[Idx++]));\n";
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
OS << " for (" << getAttrName() << "Attr::" << getLowerName()
<< "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
<< getLowerName() << "_end(); i != e; ++i)\n";
OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
}
void writeConversion(raw_ostream &OS) const {
OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
OS << type << " &Out) {\n";
OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
OS << type << ">>(Val)\n";
for (size_t I = 0; I < enums.size(); ++I) {
OS << " .Case(\"" << values[I] << "\", ";
OS << getAttrName() << "Attr::" << enums[I] << ")\n";
}
OS << " .Default(Optional<" << type << ">());\n";
OS << " if (R) {\n";
OS << " Out = *R;\n return true;\n }\n";
OS << " return false;\n";
OS << " }\n";
}
};
class VersionArgument : public Argument {
public:
VersionArgument(const Record &Arg, StringRef Attr)
: Argument(Arg, Attr)
{}
void writeAccessors(raw_ostream &OS) const override {
OS << " VersionTuple get" << getUpperName() << "() const {\n";
OS << " return " << getLowerName() << ";\n";
OS << " }\n";
OS << " void set" << getUpperName()
<< "(ASTContext &C, VersionTuple V) {\n";
OS << " " << getLowerName() << " = V;\n";
OS << " }";
}
void writeCloneArgs(raw_ostream &OS) const override {
OS << "get" << getUpperName() << "()";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "()";
}
void writeCtorInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "(" << getUpperName() << ")";
}
void writeCtorDefaultInitializers(raw_ostream &OS) const override {
OS << getLowerName() << "()";
}
void writeCtorParameters(raw_ostream &OS) const override {
OS << "VersionTuple " << getUpperName();
}
void writeDeclarations(raw_ostream &OS) const override {
OS << "VersionTuple " << getLowerName() << ";\n";
}
void writePCHReadDecls(raw_ostream &OS) const override {
OS << " VersionTuple " << getLowerName()
<< "= ReadVersionTuple(Record, Idx);\n";
}
void writePCHReadArgs(raw_ostream &OS) const override {
OS << getLowerName();
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
}
void writeValue(raw_ostream &OS) const override {
OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
}
void writeDump(raw_ostream &OS) const override {
OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
}
};
class ExprArgument : public SimpleArgument {
public:
ExprArgument(const Record &Arg, StringRef Attr)
: SimpleArgument(Arg, Attr, "Expr *")
{}
void writeASTVisitorTraversal(raw_ostream &OS) const override {
OS << " if (!"
<< "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
OS << " return false;\n";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "tempInst" << getUpperName();
}
void writeTemplateInstantiation(raw_ostream &OS) const override {
OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
OS << " {\n";
OS << " EnterExpressionEvaluationContext "
<< "Unevaluated(S, Sema::Unevaluated);\n";
OS << " ExprResult " << "Result = S.SubstExpr("
<< "A->get" << getUpperName() << "(), TemplateArgs);\n";
OS << " tempInst" << getUpperName() << " = "
- << "Result.takeAs<Expr>();\n";
+ << "Result.getAs<Expr>();\n";
OS << " }\n";
}
void writeDump(raw_ostream &OS) const override {}
void writeDumpChildren(raw_ostream &OS) const override {
OS << " lastChild();\n";
OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
}
void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
};
class VariadicExprArgument : public VariadicArgument {
public:
VariadicExprArgument(const Record &Arg, StringRef Attr)
: VariadicArgument(Arg, Attr, "Expr *")
{}
void writeASTVisitorTraversal(raw_ostream &OS) const override {
OS << " {\n";
OS << " " << getType() << " *I = A->" << getLowerName()
<< "_begin();\n";
OS << " " << getType() << " *E = A->" << getLowerName()
<< "_end();\n";
OS << " for (; I != E; ++I) {\n";
OS << " if (!getDerived().TraverseStmt(*I))\n";
OS << " return false;\n";
OS << " }\n";
OS << " }\n";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "tempInst" << getUpperName() << ", "
<< "A->" << getLowerName() << "_size()";
}
void writeTemplateInstantiation(raw_ostream &OS) const override {
OS << " " << getType() << " *tempInst" << getUpperName()
<< " = new (C, 16) " << getType()
<< "[A->" << getLowerName() << "_size()];\n";
OS << " {\n";
OS << " EnterExpressionEvaluationContext "
<< "Unevaluated(S, Sema::Unevaluated);\n";
OS << " " << getType() << " *TI = tempInst" << getUpperName()
<< ";\n";
OS << " " << getType() << " *I = A->" << getLowerName()
<< "_begin();\n";
OS << " " << getType() << " *E = A->" << getLowerName()
<< "_end();\n";
OS << " for (; I != E; ++I, ++TI) {\n";
OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
- OS << " *TI = Result.takeAs<Expr>();\n";
+ OS << " *TI = Result.getAs<Expr>();\n";
OS << " }\n";
OS << " }\n";
}
void writeDump(raw_ostream &OS) const override {}
void writeDumpChildren(raw_ostream &OS) const override {
OS << " for (" << getAttrName() << "Attr::" << getLowerName()
<< "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
<< getLowerName() << "_end(); I != E; ++I) {\n";
OS << " if (I + 1 == E)\n";
OS << " lastChild();\n";
OS << " dumpStmt(*I);\n";
OS << " }\n";
}
void writeHasChildren(raw_ostream &OS) const override {
OS << "SA->" << getLowerName() << "_begin() != "
<< "SA->" << getLowerName() << "_end()";
}
};
class TypeArgument : public SimpleArgument {
public:
TypeArgument(const Record &Arg, StringRef Attr)
: SimpleArgument(Arg, Attr, "TypeSourceInfo *")
{}
void writeAccessors(raw_ostream &OS) const override {
OS << " QualType get" << getUpperName() << "() const {\n";
OS << " return " << getLowerName() << "->getType();\n";
OS << " }";
OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
OS << " return " << getLowerName() << ";\n";
OS << " }";
}
void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
OS << "A->get" << getUpperName() << "Loc()";
}
void writePCHWrite(raw_ostream &OS) const override {
OS << " " << WritePCHRecord(
getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
}
};
}
static std::unique_ptr<Argument>
createArgument(const Record &Arg, StringRef Attr,
const Record *Search = nullptr) {
if (!Search)
Search = &Arg;
Argument *Ptr = nullptr;
llvm::StringRef ArgName = Search->getName();
if (ArgName == "AlignedArgument") Ptr = new AlignedArgument(Arg, Attr);
else if (ArgName == "EnumArgument") Ptr = new EnumArgument(Arg, Attr);
else if (ArgName == "ExprArgument") Ptr = new ExprArgument(Arg, Attr);
else if (ArgName == "FunctionArgument")
Ptr = new SimpleArgument(Arg, Attr, "FunctionDecl *");
else if (ArgName == "IdentifierArgument")
Ptr = new SimpleArgument(Arg, Attr, "IdentifierInfo *");
else if (ArgName == "DefaultBoolArgument")
Ptr = new DefaultSimpleArgument(Arg, Attr, "bool",
Arg.getValueAsBit("Default"));
else if (ArgName == "BoolArgument") Ptr = new SimpleArgument(Arg, Attr,
"bool");
else if (ArgName == "DefaultIntArgument")
Ptr = new DefaultSimpleArgument(Arg, Attr, "int",
Arg.getValueAsInt("Default"));
else if (ArgName == "IntArgument") Ptr = new SimpleArgument(Arg, Attr, "int");
else if (ArgName == "StringArgument") Ptr = new StringArgument(Arg, Attr);
else if (ArgName == "TypeArgument") Ptr = new TypeArgument(Arg, Attr);
else if (ArgName == "UnsignedArgument")
Ptr = new SimpleArgument(Arg, Attr, "unsigned");
else if (ArgName == "VariadicUnsignedArgument")
Ptr = new VariadicArgument(Arg, Attr, "unsigned");
else if (ArgName == "VariadicEnumArgument")
Ptr = new VariadicEnumArgument(Arg, Attr);
else if (ArgName == "VariadicExprArgument")
Ptr = new VariadicExprArgument(Arg, Attr);
else if (ArgName == "VersionArgument")
Ptr = new VersionArgument(Arg, Attr);
if (!Ptr) {
// Search in reverse order so that the most-derived type is handled first.
std::vector<Record*> Bases = Search->getSuperClasses();
for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
Ptr = createArgument(Arg, Attr, Base).release();
if (Ptr)
break;
}
}
if (Ptr && Arg.getValueAsBit("Optional"))
Ptr->setOptional(true);
return std::unique_ptr<Argument>(Ptr);
}
static void writeAvailabilityValue(raw_ostream &OS) {
OS << "\" << getPlatform()->getName();\n"
<< " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
<< " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
<< " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
<< " if (getUnavailable()) OS << \", unavailable\";\n"
<< " OS << \"";
}
static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
if (Spellings.empty()) {
OS << " return \"(No spelling)\";\n}\n\n";
return;
}
OS << " switch (SpellingListIndex) {\n"
" default:\n"
" llvm_unreachable(\"Unknown attribute spelling!\");\n"
" return \"(No spelling)\";\n";
for (unsigned I = 0; I < Spellings.size(); ++I)
OS << " case " << I << ":\n"
" return \"" << Spellings[I].name() << "\";\n";
// End of the switch statement.
OS << " }\n";
// End of the getSpelling function.
OS << "}\n\n";
}
static void
writePrettyPrintFunction(Record &R,
const std::vector<std::unique_ptr<Argument>> &Args,
raw_ostream &OS) {
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
OS << "void " << R.getName() << "Attr::printPretty("
<< "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
if (Spellings.size() == 0) {
OS << "}\n\n";
return;
}
OS <<
" switch (SpellingListIndex) {\n"
" default:\n"
" llvm_unreachable(\"Unknown attribute spelling!\");\n"
" break;\n";
for (unsigned I = 0; I < Spellings.size(); ++ I) {
llvm::SmallString<16> Prefix;
llvm::SmallString<8> Suffix;
// The actual spelling of the name and namespace (if applicable)
// of an attribute without considering prefix and suffix.
llvm::SmallString<64> Spelling;
std::string Name = Spellings[I].name();
std::string Variety = Spellings[I].variety();
if (Variety == "GNU") {
Prefix = " __attribute__((";
Suffix = "))";
} else if (Variety == "CXX11") {
Prefix = " [[";
Suffix = "]]";
std::string Namespace = Spellings[I].nameSpace();
if (Namespace != "") {
Spelling += Namespace;
Spelling += "::";
}
} else if (Variety == "Declspec") {
Prefix = " __declspec(";
Suffix = ")";
} else if (Variety == "Keyword") {
Prefix = " ";
Suffix = "";
} else {
llvm_unreachable("Unknown attribute syntax variety!");
}
Spelling += Name;
OS <<
" case " << I << " : {\n"
" OS << \"" + Prefix.str() + Spelling.str();
if (!Args.empty())
OS << "(";
if (Spelling == "availability") {
writeAvailabilityValue(OS);
} else {
for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
if (I != Args.begin()) OS << ", ";
(*I)->writeValue(OS);
}
}
if (!Args.empty())
OS << ")";
OS << Suffix.str() + "\";\n";
OS <<
" break;\n"
" }\n";
}
// End of the switch statement.
OS << "}\n";
// End of the print function.
OS << "}\n\n";
}
/// \brief Return the index of a spelling in a spelling list.
static unsigned
getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
const FlattenedSpelling &Spelling) {
assert(SpellingList.size() && "Spelling list is empty!");
for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
const FlattenedSpelling &S = SpellingList[Index];
if (S.variety() != Spelling.variety())
continue;
if (S.nameSpace() != Spelling.nameSpace())
continue;
if (S.name() != Spelling.name())
continue;
return Index;
}
llvm_unreachable("Unknown spelling!");
}
static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
for (const auto *Accessor : Accessors) {
std::string Name = Accessor->getValueAsString("Name");
std::vector<FlattenedSpelling> Spellings =
GetFlattenedSpellings(*Accessor);
std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
assert(SpellingList.size() &&
"Attribute with empty spelling list can't have accessors!");
OS << " bool " << Name << "() const { return SpellingListIndex == ";
for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
OS << getSpellingListIndex(SpellingList, Spellings[Index]);
if (Index != Spellings.size() -1)
OS << " ||\n SpellingListIndex == ";
else
OS << "; }\n";
}
}
}
static bool
SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
assert(!Spellings.empty() && "An empty list of spellings was provided");
std::string FirstName = NormalizeNameForSpellingComparison(
Spellings.front().name());
for (const auto &Spelling :
llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
if (Name != FirstName)
return false;
}
return true;
}
typedef std::map<unsigned, std::string> SemanticSpellingMap;
static std::string
CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
SemanticSpellingMap &Map) {
// The enumerants are automatically generated based on the variety,
// namespace (if present) and name for each attribute spelling. However,
// care is taken to avoid trampling on the reserved namespace due to
// underscores.
std::string Ret(" enum Spelling {\n");
std::set<std::string> Uniques;
unsigned Idx = 0;
for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
const FlattenedSpelling &S = *I;
std::string Variety = S.variety();
std::string Spelling = S.name();
std::string Namespace = S.nameSpace();
std::string EnumName = "";
EnumName += (Variety + "_");
if (!Namespace.empty())
EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
"_");
EnumName += NormalizeNameForSpellingComparison(Spelling);
// Even if the name is not unique, this spelling index corresponds to a
// particular enumerant name that we've calculated.
Map[Idx] = EnumName;
// Since we have been stripping underscores to avoid trampling on the
// reserved namespace, we may have inadvertently created duplicate
// enumerant names. These duplicates are not considered part of the
// semantic spelling, and can be elided.
if (Uniques.find(EnumName) != Uniques.end())
continue;
Uniques.insert(EnumName);
if (I != Spellings.begin())
Ret += ",\n";
Ret += " " + EnumName;
}
Ret += "\n };\n\n";
return Ret;
}
void WriteSemanticSpellingSwitch(const std::string &VarName,
const SemanticSpellingMap &Map,
raw_ostream &OS) {
OS << " switch (" << VarName << ") {\n default: "
<< "llvm_unreachable(\"Unknown spelling list index\");\n";
for (const auto &I : Map)
OS << " case " << I.first << ": return " << I.second << ";\n";
OS << " }\n";
}
// Emits the LateParsed property for attributes.
static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
for (const auto *Attr : Attrs) {
bool LateParsed = Attr->getValueAsBit("LateParsed");
if (LateParsed) {
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
// FIXME: Handle non-GNU attributes
for (const auto &I : Spellings) {
if (I.variety() != "GNU")
continue;
OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
}
}
}
OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
}
/// \brief Emits the first-argument-is-type property for attributes.
static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
for (const auto *Attr : Attrs) {
// Determine whether the first argument is a type.
std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
if (Args.empty())
continue;
if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
continue;
// All these spellings take a single type argument.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
std::set<std::string> Emitted;
for (const auto &S : Spellings) {
if (Emitted.insert(S.name()).second)
OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
}
}
OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
}
/// \brief Emits the parse-arguments-in-unevaluated-context property for
/// attributes.
static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
ParsedAttrMap Attrs = getParsedAttrList(Records);
for (const auto &I : Attrs) {
const Record &Attr = *I.second;
if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
continue;
// All these spellings take are parsed unevaluated.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
std::set<std::string> Emitted;
for (const auto &S : Spellings) {
if (Emitted.insert(S.name()).second)
OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
}
}
OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
}
static bool isIdentifierArgument(Record *Arg) {
return !Arg->getSuperClasses().empty() &&
llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
.Case("IdentifierArgument", true)
.Case("EnumArgument", true)
.Default(false);
}
// Emits the first-argument-is-identifier property for attributes.
static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
for (const auto *Attr : Attrs) {
// Determine whether the first argument is an identifier.
std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
if (Args.empty() || !isIdentifierArgument(Args[0]))
continue;
// All these spellings take an identifier argument.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
std::set<std::string> Emitted;
for (const auto &S : Spellings) {
if (Emitted.insert(S.name()).second)
OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
}
}
OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
}
namespace clang {
// Emits the class definitions for attributes.
void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute classes' definitions", OS);
OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
// FIXME: Currently, documentation is generated as-needed due to the fact
// that there is no way to allow a generated project "reach into" the docs
// directory (for instance, it may be an out-of-tree build). However, we want
// to ensure that every attribute has a Documentation field, and produce an
// error if it has been neglected. Otherwise, the on-demand generation which
// happens server-side will fail. This code is ensuring that functionality,
// even though this Emitter doesn't technically need the documentation.
// When attribute documentation can be generated as part of the build
// itself, this code can be removed.
(void)R.getValueAsListOfDefs("Documentation");
if (!R.getValueAsBit("ASTNode"))
continue;
const std::vector<Record *> Supers = R.getSuperClasses();
assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
std::string SuperName;
for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
const Record &R = *Super;
if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
SuperName = R.getName();
}
OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
std::vector<std::unique_ptr<Argument>> Args;
Args.reserve(ArgRecords.size());
for (const auto *ArgRecord : ArgRecords) {
Args.emplace_back(createArgument(*ArgRecord, R.getName()));
Args.back()->writeDeclarations(OS);
OS << "\n\n";
}
OS << "\npublic:\n";
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
// If there are zero or one spellings, all spelling-related functionality
// can be elided. If all of the spellings share the same name, the spelling
// functionality can also be elided.
bool ElideSpelling = (Spellings.size() <= 1) ||
SpellingNamesAreCommon(Spellings);
// This maps spelling index values to semantic Spelling enumerants.
SemanticSpellingMap SemanticToSyntacticMap;
if (!ElideSpelling)
OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
OS << " static " << R.getName() << "Attr *CreateImplicit(";
OS << "ASTContext &Ctx";
if (!ElideSpelling)
OS << ", Spelling S";
for (auto const &ai : Args) {
OS << ", ";
ai->writeCtorParameters(OS);
}
OS << ", SourceRange Loc = SourceRange()";
OS << ") {\n";
OS << " " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
OS << "Attr(Loc, Ctx, ";
for (auto const &ai : Args) {
ai->writeImplicitCtorArgs(OS);
OS << ", ";
}
OS << (ElideSpelling ? "0" : "S") << ");\n";
OS << " A->setImplicit(true);\n";
OS << " return A;\n }\n\n";
OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
bool HasOpt = false;
for (auto const &ai : Args) {
OS << " , ";
ai->writeCtorParameters(OS);
OS << "\n";
if (ai->isOptional())
HasOpt = true;
}
OS << " , ";
OS << "unsigned SI\n";
OS << " )\n";
OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";
for (auto const &ai : Args) {
OS << " , ";
ai->writeCtorInitializers(OS);
OS << "\n";
}
OS << " {\n";
for (auto const &ai : Args) {
ai->writeCtorBody(OS);
OS << "\n";
}
OS << " }\n\n";
// If there are optional arguments, write out a constructor that elides the
// optional arguments as well.
if (HasOpt) {
OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
for (auto const &ai : Args) {
if (!ai->isOptional()) {
OS << " , ";
ai->writeCtorParameters(OS);
OS << "\n";
}
}
OS << " , ";
OS << "unsigned SI\n";
OS << " )\n";
OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";
for (auto const &ai : Args) {
OS << " , ";
ai->writeCtorDefaultInitializers(OS);
OS << "\n";
}
OS << " {\n";
for (auto const &ai : Args) {
if (!ai->isOptional()) {
ai->writeCtorBody(OS);
OS << "\n";
}
}
OS << " }\n\n";
}
OS << " " << R.getName() << "Attr *clone(ASTContext &C) const override;\n";
OS << " void printPretty(raw_ostream &OS,\n"
<< " const PrintingPolicy &Policy) const override;\n";
OS << " const char *getSpelling() const override;\n";
if (!ElideSpelling) {
assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
OS << " Spelling getSemanticSpelling() const {\n";
WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
OS);
OS << " }\n";
}
writeAttrAccessorDefinition(R, OS);
for (auto const &ai : Args) {
ai->writeAccessors(OS);
OS << "\n\n";
if (ai->isEnumArg())
static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
else if (ai->isVariadicEnumArg())
static_cast<const VariadicEnumArgument *>(ai.get())
->writeConversion(OS);
}
OS << R.getValueAsString("AdditionalMembers");
OS << "\n\n";
OS << " static bool classof(const Attr *A) { return A->getKind() == "
<< "attr::" << R.getName() << "; }\n";
bool LateParsed = R.getValueAsBit("LateParsed");
OS << " bool isLateParsed() const override { return "
<< LateParsed << "; }\n";
if (R.getValueAsBit("DuplicatesAllowedWhileMerging"))
OS << " bool duplicatesAllowed() const override { return true; }\n\n";
OS << "};\n\n";
}
OS << "#endif\n";
}
// Emits the class method definitions for attributes.
void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute classes' member function definitions", OS);
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
for (auto *Attr : Attrs) {
Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
std::vector<std::unique_ptr<Argument>> Args;
for (const auto *Arg : ArgRecords)
Args.emplace_back(createArgument(*Arg, R.getName()));
for (auto const &ai : Args)
ai->writeAccessorDefinitions(OS);
OS << R.getName() << "Attr *" << R.getName()
<< "Attr::clone(ASTContext &C) const {\n";
OS << " return new (C) " << R.getName() << "Attr(getLocation(), C";
for (auto const &ai : Args) {
OS << ", ";
ai->writeCloneArgs(OS);
}
OS << ", getSpellingListIndex());\n}\n\n";
writePrettyPrintFunction(R, Args, OS);
writeGetSpellingFunction(R, OS);
}
}
} // end namespace clang
static void EmitAttrList(raw_ostream &OS, StringRef Class,
const std::vector<Record*> &AttrList) {
std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end();
if (i != e) {
// Move the end iterator back to emit the last attribute.
for(--e; i != e; ++i) {
if (!(*i)->getValueAsBit("ASTNode"))
continue;
OS << Class << "(" << (*i)->getName() << ")\n";
}
OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
}
}
namespace clang {
// Emits the enumeration list for attributes.
void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
OS << "#ifndef LAST_ATTR\n";
OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef INHERITABLE_ATTR\n";
OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef LAST_INHERITABLE_ATTR\n";
OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
OS << "#endif\n\n";
OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
" INHERITABLE_PARAM_ATTR(NAME)\n";
OS << "#endif\n\n";
Record *InhClass = Records.getClass("InheritableAttr");
Record *InhParamClass = Records.getClass("InheritableParamAttr");
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
NonInhAttrs, InhAttrs, InhParamAttrs;
for (auto *Attr : Attrs) {
if (!Attr->getValueAsBit("ASTNode"))
continue;
if (Attr->isSubClassOf(InhParamClass))
InhParamAttrs.push_back(Attr);
else if (Attr->isSubClassOf(InhClass))
InhAttrs.push_back(Attr);
else
NonInhAttrs.push_back(Attr);
}
EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
EmitAttrList(OS, "ATTR", NonInhAttrs);
OS << "#undef LAST_ATTR\n";
OS << "#undef INHERITABLE_ATTR\n";
OS << "#undef LAST_INHERITABLE_ATTR\n";
OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
OS << "#undef ATTR\n";
}
// Emits the code to read an attribute from a precompiled header.
void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute deserialization code", OS);
Record *InhClass = Records.getClass("InheritableAttr");
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
ArgRecords;
std::vector<std::unique_ptr<Argument>> Args;
OS << " switch (Kind) {\n";
OS << " default:\n";
OS << " assert(0 && \"Unknown attribute!\");\n";
OS << " break;\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ": {\n";
if (R.isSubClassOf(InhClass))
OS << " bool isInherited = Record[Idx++];\n";
OS << " bool isImplicit = Record[Idx++];\n";
OS << " unsigned Spelling = Record[Idx++];\n";
ArgRecords = R.getValueAsListOfDefs("Args");
Args.clear();
for (const auto *Arg : ArgRecords) {
Args.emplace_back(createArgument(*Arg, R.getName()));
Args.back()->writePCHReadDecls(OS);
}
OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
for (auto const &ri : Args) {
OS << ", ";
ri->writePCHReadArgs(OS);
}
OS << ", Spelling);\n";
if (R.isSubClassOf(InhClass))
OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
OS << " New->setImplicit(isImplicit);\n";
OS << " break;\n";
OS << " }\n";
}
OS << " }\n";
}
// Emits the code to write an attribute to a precompiled header.
void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute serialization code", OS);
Record *InhClass = Records.getClass("InheritableAttr");
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
OS << " switch (A->getKind()) {\n";
OS << " default:\n";
OS << " llvm_unreachable(\"Unknown attribute kind!\");\n";
OS << " break;\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ": {\n";
Args = R.getValueAsListOfDefs("Args");
if (R.isSubClassOf(InhClass) || !Args.empty())
OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName()
<< "Attr>(A);\n";
if (R.isSubClassOf(InhClass))
OS << " Record.push_back(SA->isInherited());\n";
OS << " Record.push_back(A->isImplicit());\n";
OS << " Record.push_back(A->getSpellingListIndex());\n";
for (const auto *Arg : Args)
createArgument(*Arg, R.getName())->writePCHWrite(OS);
OS << " break;\n";
OS << " }\n";
}
OS << " }\n";
}
static void GenerateHasAttrSpellingStringSwitch(
const std::vector<Record *> &Attrs, raw_ostream &OS,
const std::string &Variety = "", const std::string &Scope = "") {
for (const auto *Attr : Attrs) {
// It is assumed that there will be an llvm::Triple object named T within
// scope that can be used to determine whether the attribute exists in
// a given target.
std::string Test;
if (Attr->isSubClassOf("TargetSpecificAttr")) {
const Record *R = Attr->getValueAsDef("Target");
std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
Test += "(";
for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) {
std::string Part = *AI;
Test += "T.getArch() == llvm::Triple::" + Part;
if (AI + 1 != AE)
Test += " || ";
}
Test += ")";
std::vector<std::string> OSes;
if (!R->isValueUnset("OSes")) {
Test += " && (";
std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) {
std::string Part = *AI;
Test += "T.getOS() == llvm::Triple::" + Part;
if (AI + 1 != AE)
Test += " || ";
}
Test += ")";
}
// If this is the C++11 variety, also add in the LangOpts test.
if (Variety == "CXX11")
Test += " && LangOpts.CPlusPlus11";
} else if (Variety == "CXX11")
// C++11 mode should be checked against LangOpts, which is presumed to be
// present in the caller.
Test = "LangOpts.CPlusPlus11";
else
Test = "true";
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
for (const auto &S : Spellings)
if (Variety.empty() || (Variety == S.variety() &&
(Scope.empty() || Scope == S.nameSpace())))
OS << " .Case(\"" << S.name() << "\", " << Test << ")\n";
}
OS << " .Default(false);\n";
}
// Emits the list of spellings for attributes.
void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
// Separate all of the attributes out into four group: generic, C++11, GNU,
// and declspecs. Then generate a big switch statement for each of them.
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
std::vector<Record *> Declspec, GNU;
std::map<std::string, std::vector<Record *>> CXX;
// Walk over the list of all attributes, and split them out based on the
// spelling variety.
for (auto *R : Attrs) {
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
for (const auto &SI : Spellings) {
std::string Variety = SI.variety();
if (Variety == "GNU")
GNU.push_back(R);
else if (Variety == "Declspec")
Declspec.push_back(R);
else if (Variety == "CXX11") {
CXX[SI.nameSpace()].push_back(R);
}
}
}
OS << "switch (Syntax) {\n";
OS << "case AttrSyntax::Generic:\n";
OS << " return llvm::StringSwitch<bool>(Name)\n";
GenerateHasAttrSpellingStringSwitch(Attrs, OS);
OS << "case AttrSyntax::GNU:\n";
OS << " return llvm::StringSwitch<bool>(Name)\n";
GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
OS << "case AttrSyntax::Declspec:\n";
OS << " return llvm::StringSwitch<bool>(Name)\n";
GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
OS << "case AttrSyntax::CXX: {\n";
// C++11-style attributes are further split out based on the Scope.
for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(),
E = CXX.end();
I != E; ++I) {
if (I != CXX.begin())
OS << " else ";
if (I->first.empty())
OS << "if (!Scope || Scope->getName() == \"\") {\n";
else
OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
OS << " return llvm::StringSwitch<bool>(Name)\n";
GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
OS << "}";
}
OS << "\n}\n";
OS << "}\n";
}
void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Code to translate different attribute spellings "
"into internal identifiers", OS);
OS <<
" switch (AttrKind) {\n"
" default:\n"
" llvm_unreachable(\"Unknown attribute kind!\");\n"
" break;\n";
ParsedAttrMap Attrs = getParsedAttrList(Records);
for (const auto &I : Attrs) {
const Record &R = *I.second;
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
OS << " case AT_" << I.first << ": {\n";
for (unsigned I = 0; I < Spellings.size(); ++ I) {
OS << " if (Name == \""
<< Spellings[I].name() << "\" && "
<< "SyntaxUsed == "
<< StringSwitch<unsigned>(Spellings[I].variety())
.Case("GNU", 0)
.Case("CXX11", 1)
.Case("Declspec", 2)
.Case("Keyword", 3)
.Default(0)
<< " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
<< " return " << I << ";\n";
}
OS << " break;\n";
OS << " }\n";
}
OS << " }\n";
OS << " return 0;\n";
}
// Emits code used by RecursiveASTVisitor to visit attributes
void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
// Write method declarations for Traverse* methods.
// We emit this here because we only generate methods for attributes that
// are declared as ASTNodes.
OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " bool Traverse"
<< R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
OS << " bool Visit"
<< R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
<< " return true; \n"
<< " };\n";
}
OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
// Write individual Traverse* methods for each attribute class.
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << "template <typename Derived>\n"
<< "bool VISITORCLASS<Derived>::Traverse"
<< R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
<< " if (!getDerived().VisitAttr(A))\n"
<< " return false;\n"
<< " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
<< " return false;\n";
std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
for (const auto *Arg : ArgRecords)
createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
OS << " return true;\n";
OS << "}\n\n";
}
// Write generic Traverse routine
OS << "template <typename Derived>\n"
<< "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
<< " if (!A)\n"
<< " return true;\n"
<< "\n"
<< " switch (A->getKind()) {\n"
<< " default:\n"
<< " return true;\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ":\n"
<< " return getDerived().Traverse" << R.getName() << "Attr("
<< "cast<" << R.getName() << "Attr>(A));\n";
}
OS << " }\n"; // end case
OS << "}\n"; // end function
OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
}
// Emits code to instantiate dependent attributes on templates.
void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Template instantiation code for attributes", OS);
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
OS << "namespace clang {\n"
<< "namespace sema {\n\n"
<< "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
<< "Sema &S,\n"
<< " const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
<< " switch (At->getKind()) {\n"
<< " default:\n"
<< " break;\n";
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ": {\n";
bool ShouldClone = R.getValueAsBit("Clone");
if (!ShouldClone) {
OS << " return NULL;\n";
OS << " }\n";
continue;
}
OS << " const " << R.getName() << "Attr *A = cast<"
<< R.getName() << "Attr>(At);\n";
bool TDependent = R.getValueAsBit("TemplateDependent");
if (!TDependent) {
OS << " return A->clone(C);\n";
OS << " }\n";
continue;
}
std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
std::vector<std::unique_ptr<Argument>> Args;
Args.reserve(ArgRecords.size());
for (const auto *ArgRecord : ArgRecords)
Args.emplace_back(createArgument(*ArgRecord, R.getName()));
for (auto const &ai : Args)
ai->writeTemplateInstantiation(OS);
OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
for (auto const &ai : Args) {
OS << ", ";
ai->writeTemplateInstantiationArgs(OS);
}
OS << ", A->getSpellingListIndex());\n }\n";
}
OS << " } // end switch\n"
<< " llvm_unreachable(\"Unknown attribute!\");\n"
<< " return 0;\n"
<< "}\n\n"
<< "} // end namespace sema\n"
<< "} // end namespace clang\n";
}
// Emits the list of parsed attributes.
void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
OS << "#ifndef PARSED_ATTR\n";
OS << "#define PARSED_ATTR(NAME) NAME\n";
OS << "#endif\n\n";
ParsedAttrMap Names = getParsedAttrList(Records);
for (const auto &I : Names) {
OS << "PARSED_ATTR(" << I.first << ")\n";
}
}
static void emitArgInfo(const Record &R, std::stringstream &OS) {
// This function will count the number of arguments specified for the
// attribute and emit the number of required arguments followed by the
// number of optional arguments.
std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
unsigned ArgCount = 0, OptCount = 0;
for (const auto *Arg : Args) {
Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
}
OS << ArgCount << ", " << OptCount;
}
static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
OS << "const Decl *) {\n";
OS << " return true;\n";
OS << "}\n\n";
}
static std::string CalculateDiagnostic(const Record &S) {
// If the SubjectList object has a custom diagnostic associated with it,
// return that directly.
std::string CustomDiag = S.getValueAsString("CustomDiag");
if (!CustomDiag.empty())
return CustomDiag;
// Given the list of subjects, determine what diagnostic best fits.
enum {
Func = 1U << 0,
Var = 1U << 1,
ObjCMethod = 1U << 2,
Param = 1U << 3,
Class = 1U << 4,
GenericRecord = 1U << 5,
Type = 1U << 6,
ObjCIVar = 1U << 7,
ObjCProp = 1U << 8,
ObjCInterface = 1U << 9,
Block = 1U << 10,
Namespace = 1U << 11,
Field = 1U << 12,
CXXMethod = 1U << 13,
ObjCProtocol = 1U << 14
};
uint32_t SubMask = 0;
std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
for (const auto *Subject : Subjects) {
const Record &R = *Subject;
std::string Name;
if (R.isSubClassOf("SubsetSubject")) {
PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
// As a fallback, look through the SubsetSubject to see what its base
// type is, and use that. This needs to be updated if SubsetSubjects
// are allowed within other SubsetSubjects.
Name = R.getValueAsDef("Base")->getName();
} else
Name = R.getName();
uint32_t V = StringSwitch<uint32_t>(Name)
.Case("Function", Func)
.Case("Var", Var)
.Case("ObjCMethod", ObjCMethod)
.Case("ParmVar", Param)
.Case("TypedefName", Type)
.Case("ObjCIvar", ObjCIVar)
.Case("ObjCProperty", ObjCProp)
.Case("Record", GenericRecord)
.Case("ObjCInterface", ObjCInterface)
.Case("ObjCProtocol", ObjCProtocol)
.Case("Block", Block)
.Case("CXXRecord", Class)
.Case("Namespace", Namespace)
.Case("Field", Field)
.Case("CXXMethod", CXXMethod)
.Default(0);
if (!V) {
// Something wasn't in our mapping, so be helpful and let the developer
// know about it.
PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
return "";
}
SubMask |= V;
}
switch (SubMask) {
// For the simple cases where there's only a single entry in the mask, we
// don't have to resort to bit fiddling.
case Func: return "ExpectedFunction";
case Var: return "ExpectedVariable";
case Param: return "ExpectedParameter";
case Class: return "ExpectedClass";
case CXXMethod:
// FIXME: Currently, this maps to ExpectedMethod based on existing code,
// but should map to something a bit more accurate at some point.
case ObjCMethod: return "ExpectedMethod";
case Type: return "ExpectedType";
case ObjCInterface: return "ExpectedObjectiveCInterface";
case ObjCProtocol: return "ExpectedObjectiveCProtocol";
// "GenericRecord" means struct, union or class; check the language options
// and if not compiling for C++, strip off the class part. Note that this
// relies on the fact that the context for this declares "Sema &S".
case GenericRecord:
return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
"ExpectedStructOrUnion)";
case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
case Func | Param:
case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
case Func | Var: return "ExpectedVariableOrFunction";
// If not compiling for C++, the class portion does not apply.
case Func | Var | Class:
return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
"ExpectedVariableOrFunction)";
case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
case Field | Var: return "ExpectedFieldOrGlobalVar";
}
PrintFatalError(S.getLoc(),
"Could not deduce diagnostic argument for Attr subjects");
return "";
}
static std::string GetSubjectWithSuffix(const Record *R) {
std::string B = R->getName();
if (B == "DeclBase")
return "Decl";
return B + "Decl";
}
static std::string GenerateCustomAppertainsTo(const Record &Subject,
raw_ostream &OS) {
std::string FnName = "is" + Subject.getName();
// If this code has already been generated, simply return the previous
// instance of it.
static std::set<std::string> CustomSubjectSet;
std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
if (I != CustomSubjectSet.end())
return *I;
Record *Base = Subject.getValueAsDef("Base");
// Not currently support custom subjects within custom subjects.
if (Base->isSubClassOf("SubsetSubject")) {
PrintFatalError(Subject.getLoc(),
"SubsetSubjects within SubsetSubjects is not supported");
return "";
}
OS << "static bool " << FnName << "(const Decl *D) {\n";
OS << " if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
OS << GetSubjectWithSuffix(Base);
OS << ">(D))\n";
OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
OS << " return false;\n";
OS << "}\n\n";
CustomSubjectSet.insert(FnName);
return FnName;
}
static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
// If the attribute does not contain a Subjects definition, then use the
// default appertainsTo logic.
if (Attr.isValueUnset("Subjects"))
return "defaultAppertainsTo";
const Record *SubjectObj = Attr.getValueAsDef("Subjects");
std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
// If the list of subjects is empty, it is assumed that the attribute
// appertains to everything.
if (Subjects.empty())
return "defaultAppertainsTo";
bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
// Otherwise, generate an appertainsTo check specific to this attribute which
// checks all of the given subjects against the Decl passed in. Return the
// name of that check to the caller.
std::string FnName = "check" + Attr.getName() + "AppertainsTo";
std::stringstream SS;
SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
SS << "const Decl *D) {\n";
SS << " if (";
for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
// If the subject has custom code associated with it, generate a function
// for it. The function cannot be inlined into this check (yet) because it
// requires the subject to be of a specific type, and were that information
// inlined here, it would not support an attribute with multiple custom
// subjects.
if ((*I)->isSubClassOf("SubsetSubject")) {
SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
} else {
SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
}
if (I + 1 != E)
SS << " && ";
}
SS << ") {\n";
SS << " S.Diag(Attr.getLoc(), diag::";
SS << (Warn ? "warn_attribute_wrong_decl_type" :
"err_attribute_wrong_decl_type");
SS << ")\n";
SS << " << Attr.getName() << ";
SS << CalculateDiagnostic(*SubjectObj) << ";\n";
SS << " return false;\n";
SS << " }\n";
SS << " return true;\n";
SS << "}\n\n";
OS << SS.str();
return FnName;
}
static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
OS << "const AttributeList &) {\n";
OS << " return true;\n";
OS << "}\n\n";
}
static std::string GenerateLangOptRequirements(const Record &R,
raw_ostream &OS) {
// If the attribute has an empty or unset list of language requirements,
// return the default handler.
std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
if (LangOpts.empty())
return "defaultDiagnoseLangOpts";
// Generate the test condition, as well as a unique function name for the
// diagnostic test. The list of options should usually be short (one or two
// options), and the uniqueness isn't strictly necessary (it is just for
// codegen efficiency).
std::string FnName = "check", Test;
for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
std::string Part = (*I)->getValueAsString("Name");
Test += "S.LangOpts." + Part;
if (I + 1 != E)
Test += " || ";
FnName += Part;
}
FnName += "LangOpts";
// If this code has already been generated, simply return the previous
// instance of it.
static std::set<std::string> CustomLangOptsSet;
std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
if (I != CustomLangOptsSet.end())
return *I;
OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
OS << " if (" << Test << ")\n";
OS << " return true;\n\n";
OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
OS << "<< Attr.getName();\n";
OS << " return false;\n";
OS << "}\n\n";
CustomLangOptsSet.insert(FnName);
return FnName;
}
static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n";
OS << " return true;\n";
OS << "}\n\n";
}
static std::string GenerateTargetRequirements(const Record &Attr,
const ParsedAttrMap &Dupes,
raw_ostream &OS) {
// If the attribute is not a target specific attribute, return the default
// target handler.
if (!Attr.isSubClassOf("TargetSpecificAttr"))
return "defaultTargetRequirements";
// Get the list of architectures to be tested for.
const Record *R = Attr.getValueAsDef("Target");
std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
if (Arches.empty()) {
PrintError(Attr.getLoc(), "Empty list of target architectures for a "
"target-specific attr");
return "defaultTargetRequirements";
}
// If there are other attributes which share the same parsed attribute kind,
// such as target-specific attributes with a shared spelling, collapse the
// duplicate architectures. This is required because a shared target-specific
// attribute has only one AttributeList::Kind enumeration value, but it
// applies to multiple target architectures. In order for the attribute to be
// considered valid, all of its architectures need to be included.
if (!Attr.isValueUnset("ParseKind")) {
std::string APK = Attr.getValueAsString("ParseKind");
for (const auto &I : Dupes) {
if (I.first == APK) {
std::vector<std::string> DA = I.second->getValueAsDef("Target")
->getValueAsListOfStrings("Arches");
std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
}
}
}
std::string FnName = "isTarget", Test = "(";
for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
std::string Part = *I;
Test += "Arch == llvm::Triple::" + Part;
if (I + 1 != E)
Test += " || ";
FnName += Part;
}
Test += ")";
// If the target also requires OS testing, generate those tests as well.
bool UsesOS = false;
if (!R->isValueUnset("OSes")) {
UsesOS = true;
// We know that there was at least one arch test, so we need to and in the
// OS tests.
Test += " && (";
std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
std::string Part = *I;
Test += "OS == llvm::Triple::" + Part;
if (I + 1 != E)
Test += " || ";
FnName += Part;
}
Test += ")";
}
// If this code has already been generated, simply return the previous
// instance of it.
static std::set<std::string> CustomTargetSet;
std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
if (I != CustomTargetSet.end())
return *I;
OS << "static bool " << FnName << "(const llvm::Triple &T) {\n";
OS << " llvm::Triple::ArchType Arch = T.getArch();\n";
if (UsesOS)
OS << " llvm::Triple::OSType OS = T.getOS();\n";
OS << " return " << Test << ";\n";
OS << "}\n\n";
CustomTargetSet.insert(FnName);
return FnName;
}
static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
<< "const AttributeList &Attr) {\n";
OS << " return UINT_MAX;\n";
OS << "}\n\n";
}
static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
raw_ostream &OS) {
// If the attribute does not have a semantic form, we can bail out early.
if (!Attr.getValueAsBit("ASTNode"))
return "defaultSpellingIndexToSemanticSpelling";
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
// If there are zero or one spellings, or all of the spellings share the same
// name, we can also bail out early.
if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
return "defaultSpellingIndexToSemanticSpelling";
// Generate the enumeration we will use for the mapping.
SemanticSpellingMap SemanticToSyntacticMap;
std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
std::string Name = Attr.getName() + "AttrSpellingMap";
OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
OS << Enum;
OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
OS << "}\n\n";
return Name;
}
static bool IsKnownToGCC(const Record &Attr) {
// Look at the spellings for this subject; if there are any spellings which
// claim to be known to GCC, the attribute is known to GCC.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
for (const auto &I : Spellings) {
if (I.knownToGCC())
return true;
}
return false;
}
/// Emits the parsed attribute helpers
void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Parsed attribute helpers", OS);
// Get the list of parsed attributes, and accept the optional list of
// duplicates due to the ParseKind.
ParsedAttrMap Dupes;
ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
// Generate the default appertainsTo, target and language option diagnostic,
// and spelling list index mapping methods.
GenerateDefaultAppertainsTo(OS);
GenerateDefaultLangOptRequirements(OS);
GenerateDefaultTargetRequirements(OS);
GenerateDefaultSpellingIndexToSemanticSpelling(OS);
// Generate the appertainsTo diagnostic methods and write their names into
// another mapping. At the same time, generate the AttrInfoMap object
// contents. Due to the reliance on generated code, use separate streams so
// that code will not be interleaved.
std::stringstream SS;
for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
// TODO: If the attribute's kind appears in the list of duplicates, that is
// because it is a target-specific attribute that appears multiple times.
// It would be beneficial to test whether the duplicates are "similar
// enough" to each other to not cause problems. For instance, check that
// the spellings are identical, and custom parsing rules match, etc.
// We need to generate struct instances based off ParsedAttrInfo from
// AttributeList.cpp.
SS << " { ";
emitArgInfo(*I->second, SS);
SS << ", " << I->second->getValueAsBit("HasCustomParsing");
SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
SS << ", " << I->second->isSubClassOf("TypeAttr");
SS << ", " << IsKnownToGCC(*I->second);
SS << ", " << GenerateAppertainsTo(*I->second, OS);
SS << ", " << GenerateLangOptRequirements(*I->second, OS);
SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
SS << " }";
if (I + 1 != E)
SS << ",";
SS << " // AT_" << I->first << "\n";
}
OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
OS << SS.str();
OS << "};\n\n";
}
// Emits the kind list of parsed attributes
void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute name matcher", OS);
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords;
std::set<std::string> Seen;
for (const auto *A : Attrs) {
const Record &Attr = *A;
bool SemaHandler = Attr.getValueAsBit("SemaHandler");
bool Ignored = Attr.getValueAsBit("Ignored");
if (SemaHandler || Ignored) {
// Attribute spellings can be shared between target-specific attributes,
// and can be shared between syntaxes for the same attribute. For
// instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
// specific attribute, or MSP430-specific attribute. Additionally, an
// attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
// for the same semantic attribute. Ultimately, we need to map each of
// these to a single AttributeList::Kind value, but the StringMatcher
// class cannot handle duplicate match strings. So we generate a list of
// string to match based on the syntax, and emit multiple string matchers
// depending on the syntax used.
std::string AttrName;
if (Attr.isSubClassOf("TargetSpecificAttr") &&
!Attr.isValueUnset("ParseKind")) {
AttrName = Attr.getValueAsString("ParseKind");
if (Seen.find(AttrName) != Seen.end())
continue;
Seen.insert(AttrName);
} else
AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
for (const auto &S : Spellings) {
std::string RawSpelling = S.name();
std::vector<StringMatcher::StringPair> *Matches = nullptr;
std::string Spelling, Variety = S.variety();
if (Variety == "CXX11") {
Matches = &CXX11;
Spelling += S.nameSpace();
Spelling += "::";
} else if (Variety == "GNU")
Matches = &GNU;
else if (Variety == "Declspec")
Matches = &Declspec;
else if (Variety == "Keyword")
Matches = &Keywords;
assert(Matches && "Unsupported spelling variety found");
Spelling += NormalizeAttrSpelling(RawSpelling);
if (SemaHandler)
Matches->push_back(StringMatcher::StringPair(Spelling,
"return AttributeList::AT_" + AttrName + ";"));
else
Matches->push_back(StringMatcher::StringPair(Spelling,
"return AttributeList::IgnoredAttribute;"));
}
}
}
OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
OS << "AttributeList::Syntax Syntax) {\n";
OS << " if (AttributeList::AS_GNU == Syntax) {\n";
StringMatcher("Name", GNU, OS).Emit();
OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n";
StringMatcher("Name", Declspec, OS).Emit();
OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n";
StringMatcher("Name", CXX11, OS).Emit();
OS << " } else if (AttributeList::AS_Keyword == Syntax) {\n";
StringMatcher("Name", Keywords, OS).Emit();
OS << " }\n";
OS << " return AttributeList::UnknownAttribute;\n"
<< "}\n";
}
// Emits the code to dump an attribute.
void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
emitSourceFileHeader("Attribute dumper", OS);
OS <<
" switch (A->getKind()) {\n"
" default:\n"
" llvm_unreachable(\"Unknown attribute kind!\");\n"
" break;\n";
std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
for (const auto *Attr : Attrs) {
const Record &R = *Attr;
if (!R.getValueAsBit("ASTNode"))
continue;
OS << " case attr::" << R.getName() << ": {\n";
// If the attribute has a semantically-meaningful name (which is determined
// by whether there is a Spelling enumeration for it), then write out the
// spelling used for the attribute.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
OS << " OS << \" \" << A->getSpelling();\n";
Args = R.getValueAsListOfDefs("Args");
if (!Args.empty()) {
OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName()
<< "Attr>(A);\n";
for (const auto *Arg : Args)
createArgument(*Arg, R.getName())->writeDump(OS);
// Code for detecting the last child.
OS << " bool OldMoreChildren = hasMoreChildren();\n";
OS << " bool MoreChildren;\n";
for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI) {
// More code for detecting the last child.
OS << " MoreChildren = OldMoreChildren";
for (auto Next = AI + 1; Next != AE; ++Next) {
OS << " || ";
createArgument(**Next, R.getName())->writeHasChildren(OS);
}
OS << ";\n";
OS << " setMoreChildren(MoreChildren);\n";
createArgument(**AI, R.getName())->writeDumpChildren(OS);
}
// Reset the last child.
OS << " setMoreChildren(OldMoreChildren);\n";
}
OS <<
" break;\n"
" }\n";
}
OS << " }\n";
}
void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
raw_ostream &OS) {
emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
emitClangAttrArgContextList(Records, OS);
emitClangAttrIdentifierArgList(Records, OS);
emitClangAttrTypeArgList(Records, OS);
emitClangAttrLateParsedList(Records, OS);
}
class DocumentationData {
public:
const Record *Documentation;
const Record *Attribute;
DocumentationData(const Record &Documentation, const Record &Attribute)
: Documentation(&Documentation), Attribute(&Attribute) {}
};
static void WriteCategoryHeader(const Record *DocCategory,
raw_ostream &OS) {
const std::string &Name = DocCategory->getValueAsString("Name");
OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
// If there is content, print that as well.
std::string ContentStr = DocCategory->getValueAsString("Content");
if (!ContentStr.empty()) {
// Trim leading and trailing newlines and spaces.
StringRef Content(ContentStr);
while (Content.startswith("\r") || Content.startswith("\n") ||
Content.startswith(" ") || Content.startswith("\t"))
Content = Content.substr(1);
while (Content.endswith("\r") || Content.endswith("\n") ||
Content.endswith(" ") || Content.endswith("\t"))
Content = Content.substr(0, Content.size() - 1);
OS << Content;
}
OS << "\n\n";
}
enum SpellingKind {
GNU = 1 << 0,
CXX11 = 1 << 1,
Declspec = 1 << 2,
Keyword = 1 << 3
};
static void WriteDocumentation(const DocumentationData &Doc,
raw_ostream &OS) {
// FIXME: there is no way to have a per-spelling category for the attribute
// documentation. This may not be a limiting factor since the spellings
// should generally be consistently applied across the category.
std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
// Determine the heading to be used for this attribute.
std::string Heading = Doc.Documentation->getValueAsString("Heading");
bool CustomHeading = !Heading.empty();
if (Heading.empty()) {
// If there's only one spelling, we can simply use that.
if (Spellings.size() == 1)
Heading = Spellings.begin()->name();
else {
std::set<std::string> Uniques;
for (auto I = Spellings.begin(), E = Spellings.end();
I != E && Uniques.size() <= 1; ++I) {
std::string Spelling = NormalizeNameForSpellingComparison(I->name());
Uniques.insert(Spelling);
}
// If the semantic map has only one spelling, that is sufficient for our
// needs.
if (Uniques.size() == 1)
Heading = *Uniques.begin();
}
}
// If the heading is still empty, it is an error.
if (Heading.empty())
PrintFatalError(Doc.Attribute->getLoc(),
"This attribute requires a heading to be specified");
// Gather a list of unique spellings; this is not the same as the semantic
// spelling for the attribute. Variations in underscores and other non-
// semantic characters are still acceptable.
std::vector<std::string> Names;
unsigned SupportedSpellings = 0;
for (const auto &I : Spellings) {
SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
.Case("GNU", GNU)
.Case("CXX11", CXX11)
.Case("Declspec", Declspec)
.Case("Keyword", Keyword);
// Mask in the supported spelling.
SupportedSpellings |= Kind;
std::string Name;
if (Kind == CXX11 && !I.nameSpace().empty())
Name = I.nameSpace() + "::";
Name += I.name();
// If this name is the same as the heading, do not add it.
if (Name != Heading)
Names.push_back(Name);
}
// Print out the heading for the attribute. If there are alternate spellings,
// then display those after the heading.
if (!CustomHeading && !Names.empty()) {
Heading += " (";
for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
if (I != Names.begin())
Heading += ", ";
Heading += *I;
}
Heading += ")";
}
OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
if (!SupportedSpellings)
PrintFatalError(Doc.Attribute->getLoc(),
"Attribute has no supported spellings; cannot be "
"documented");
// List what spelling syntaxes the attribute supports.
OS << ".. csv-table:: Supported Syntaxes\n";
OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\"\n\n";
OS << " \"";
if (SupportedSpellings & GNU) OS << "X";
OS << "\",\"";
if (SupportedSpellings & CXX11) OS << "X";
OS << "\",\"";
if (SupportedSpellings & Declspec) OS << "X";
OS << "\",\"";
if (SupportedSpellings & Keyword) OS << "X";
OS << "\"\n\n";
// If the attribute is deprecated, print a message about it, and possibly
// provide a replacement attribute.
if (!Doc.Documentation->isValueUnset("Deprecated")) {
OS << "This attribute has been deprecated, and may be removed in a future "
<< "version of Clang.";
const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
std::string Replacement = Deprecated.getValueAsString("Replacement");
if (!Replacement.empty())
OS << " This attribute has been superseded by ``"
<< Replacement << "``.";
OS << "\n\n";
}
std::string ContentStr = Doc.Documentation->getValueAsString("Content");
// Trim leading and trailing newlines and spaces.
StringRef Content(ContentStr);
while (Content.startswith("\r") || Content.startswith("\n") ||
Content.startswith(" ") || Content.startswith("\t"))
Content = Content.substr(1);
while (Content.endswith("\r") || Content.endswith("\n") ||
Content.endswith(" ") || Content.endswith("\t"))
Content = Content.substr(0, Content.size() - 1);
OS << Content;
OS << "\n\n\n";
}
void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
// Get the documentation introduction paragraph.
const Record *Documentation = Records.getDef("GlobalDocumentation");
if (!Documentation) {
PrintFatalError("The Documentation top-level definition is missing, "
"no documentation will be generated.");
return;
}
OS << Documentation->getValueAsString("Intro") << "\n";
// Gather the Documentation lists from each of the attributes, based on the
// category provided.
std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
for (const auto *A : Attrs) {
const Record &Attr = *A;
std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
for (const auto *D : Docs) {
const Record &Doc = *D;
const Record *Category = Doc.getValueAsDef("Category");
// If the category is "undocumented", then there cannot be any other
// documentation categories (otherwise, the attribute would become
// documented).
std::string Cat = Category->getValueAsString("Name");
bool Undocumented = Cat == "Undocumented";
if (Undocumented && Docs.size() > 1)
PrintFatalError(Doc.getLoc(),
"Attribute is \"Undocumented\", but has multiple "
"documentation categories");
if (!Undocumented)
SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
}
}
// Having split the attributes out based on what documentation goes where,
// we can begin to generate sections of documentation.
for (const auto &I : SplitDocs) {
WriteCategoryHeader(I.first, OS);
// Walk over each of the attributes in the category and write out their
// documentation.
for (const auto &Doc : I.second)
WriteDocumentation(Doc, OS);
}
}
} // end namespace clang
Index: cfe/trunk/lib/Sema/SemaCast.cpp
===================================================================
--- cfe/trunk/lib/Sema/SemaCast.cpp (revision 209799)
+++ cfe/trunk/lib/Sema/SemaCast.cpp (revision 209800)
@@ -1,2413 +1,2413 @@
//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for cast expressions, including
// 1) C-style casts like '(int) x'
// 2) C++ functional casts like 'int(x)'
// 3) C++ named casts like 'static_cast<int>(x)'
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Sema/Initialization.h"
#include "llvm/ADT/SmallVector.h"
#include <set>
using namespace clang;
enum TryCastResult {
TC_NotApplicable, ///< The cast method is not applicable.
TC_Success, ///< The cast method is appropriate and successful.
TC_Failed ///< The cast method is appropriate, but failed. A
///< diagnostic has been emitted.
};
enum CastType {
CT_Const, ///< const_cast
CT_Static, ///< static_cast
CT_Reinterpret, ///< reinterpret_cast
CT_Dynamic, ///< dynamic_cast
CT_CStyle, ///< (Type)expr
CT_Functional ///< Type(expr)
};
namespace {
struct CastOperation {
CastOperation(Sema &S, QualType destType, ExprResult src)
: Self(S), SrcExpr(src), DestType(destType),
ResultType(destType.getNonLValueExprType(S.Context)),
ValueKind(Expr::getValueKindForType(destType)),
Kind(CK_Dependent), IsARCUnbridgedCast(false) {
if (const BuiltinType *placeholder =
src.get()->getType()->getAsPlaceholderType()) {
PlaceholderKind = placeholder->getKind();
} else {
PlaceholderKind = (BuiltinType::Kind) 0;
}
}
Sema &Self;
ExprResult SrcExpr;
QualType DestType;
QualType ResultType;
ExprValueKind ValueKind;
CastKind Kind;
BuiltinType::Kind PlaceholderKind;
CXXCastPath BasePath;
bool IsARCUnbridgedCast;
SourceRange OpRange;
SourceRange DestRange;
// Top-level semantics-checking routines.
void CheckConstCast();
void CheckReinterpretCast();
void CheckStaticCast();
void CheckDynamicCast();
void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
void CheckCStyleCast();
/// Complete an apparently-successful cast operation that yields
/// the given expression.
ExprResult complete(CastExpr *castExpr) {
// If this is an unbridged cast, wrap the result in an implicit
// cast that yields the unbridged-cast placeholder type.
if (IsARCUnbridgedCast) {
castExpr = ImplicitCastExpr::Create(Self.Context,
Self.Context.ARCUnbridgedCastTy,
CK_Dependent, castExpr, nullptr,
castExpr->getValueKind());
}
return Self.Owned(castExpr);
}
// Internal convenience methods.
/// Try to handle the given placeholder expression kind. Return
/// true if the source expression has the appropriate placeholder
/// kind. A placeholder can only be claimed once.
bool claimPlaceholder(BuiltinType::Kind K) {
if (PlaceholderKind != K) return false;
PlaceholderKind = (BuiltinType::Kind) 0;
return true;
}
bool isPlaceholder() const {
return PlaceholderKind != 0;
}
bool isPlaceholder(BuiltinType::Kind K) const {
return PlaceholderKind == K;
}
void checkCastAlign() {
Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
}
void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
assert(Self.getLangOpts().ObjCAutoRefCount);
Expr *src = SrcExpr.get();
if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
Sema::ACR_unbridged)
IsARCUnbridgedCast = true;
SrcExpr = src;
}
/// Check for and handle non-overload placeholder expressions.
void checkNonOverloadPlaceholders() {
if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
return;
- SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
+ SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
if (SrcExpr.isInvalid())
return;
PlaceholderKind = (BuiltinType::Kind) 0;
}
};
}
static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
bool CheckCVR, bool CheckObjCLifetime);
// The Try functions attempt a specific way of casting. If they succeed, they
// return TC_Success. If their way of casting is not appropriate for the given
// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
// to emit if no other way succeeds. If their way of casting is appropriate but
// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
// they emit a specialized diagnostic.
// All diagnostics returned by these functions must expect the same three
// arguments:
// %0: Cast Type (a value from the CastType enumeration)
// %1: Source Type
// %2: Destination Type
static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
QualType DestType, bool CStyle,
CastKind &Kind,
CXXCastPath &BasePath,
unsigned &msg);
static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
CanQualType DestType, bool CStyle,
const SourceRange &OpRange,
QualType OrigSrcType,
QualType OrigDestType, unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
QualType SrcType,
QualType DestType,bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType,
Sema::CheckedConversionKind CCK,
const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
bool ListInitialization);
static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType,
Sema::CheckedConversionKind CCK,
const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
CXXCastPath &BasePath,
bool ListInitialization);
static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType, bool CStyle,
unsigned &msg);
static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind);
/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
ExprResult
Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
SourceLocation LAngleBracketLoc, Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc, Expr *E,
SourceLocation RParenLoc) {
assert(!D.isInvalidType());
TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
if (D.isInvalidType())
return ExprError();
if (getLangOpts().CPlusPlus) {
// Check that there are no default arguments (C++ only).
CheckExtraCXXDefaultArguments(D);
}
return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
SourceRange(LAngleBracketLoc, RAngleBracketLoc),
SourceRange(LParenLoc, RParenLoc));
}
ExprResult
Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
TypeSourceInfo *DestTInfo, Expr *E,
SourceRange AngleBrackets, SourceRange Parens) {
ExprResult Ex = Owned(E);
QualType DestType = DestTInfo->getType();
// If the type is dependent, we won't do the semantic analysis now.
// FIXME: should we check this in a more fine-grained manner?
bool TypeDependent = DestType->isDependentType() ||
Ex.get()->isTypeDependent() ||
Ex.get()->isValueDependent();
CastOperation Op(*this, DestType, E);
Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
Op.DestRange = AngleBrackets;
switch (Kind) {
default: llvm_unreachable("Unknown C++ cast!");
case tok::kw_const_cast:
if (!TypeDependent) {
Op.CheckConstCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
}
return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
- Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
+ Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
OpLoc, Parens.getEnd(),
AngleBrackets));
case tok::kw_dynamic_cast: {
if (!TypeDependent) {
Op.CheckDynamicCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
}
return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
- Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
+ Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
&Op.BasePath, DestTInfo,
OpLoc, Parens.getEnd(),
AngleBrackets));
}
case tok::kw_reinterpret_cast: {
if (!TypeDependent) {
Op.CheckReinterpretCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
}
return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
- Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
+ Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
nullptr, DestTInfo, OpLoc,
Parens.getEnd(),
AngleBrackets));
}
case tok::kw_static_cast: {
if (!TypeDependent) {
Op.CheckStaticCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
}
return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
- Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
+ Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
&Op.BasePath, DestTInfo,
OpLoc, Parens.getEnd(),
AngleBrackets));
}
}
}
/// Try to diagnose a failed overloaded cast. Returns true if
/// diagnostics were emitted.
static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
SourceRange range, Expr *src,
QualType destType,
bool listInitialization) {
switch (CT) {
// These cast kinds don't consider user-defined conversions.
case CT_Const:
case CT_Reinterpret:
case CT_Dynamic:
return false;
// These do.
case CT_Static:
case CT_CStyle:
case CT_Functional:
break;
}
QualType srcType = src->getType();
if (!destType->isRecordType() && !srcType->isRecordType())
return false;
InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
InitializationKind initKind
= (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
range, listInitialization)
: (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
listInitialization)
: InitializationKind::CreateCast(/*type range?*/ range);
InitializationSequence sequence(S, entity, initKind, src);
assert(sequence.Failed() && "initialization succeeded on second try?");
switch (sequence.getFailureKind()) {
default: return false;
case InitializationSequence::FK_ConstructorOverloadFailed:
case InitializationSequence::FK_UserConversionOverloadFailed:
break;
}
OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
unsigned msg = 0;
OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
switch (sequence.getFailedOverloadResult()) {
case OR_Success: llvm_unreachable("successful failed overload");
case OR_No_Viable_Function:
if (candidates.empty())
msg = diag::err_ovl_no_conversion_in_cast;
else
msg = diag::err_ovl_no_viable_conversion_in_cast;
howManyCandidates = OCD_AllCandidates;
break;
case OR_Ambiguous:
msg = diag::err_ovl_ambiguous_conversion_in_cast;
howManyCandidates = OCD_ViableCandidates;
break;
case OR_Deleted:
msg = diag::err_ovl_deleted_conversion_in_cast;
howManyCandidates = OCD_ViableCandidates;
break;
}
S.Diag(range.getBegin(), msg)
<< CT << srcType << destType
<< range << src->getSourceRange();
candidates.NoteCandidates(S, howManyCandidates, src);
return true;
}
/// Diagnose a failed cast.
static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
SourceRange opRange, Expr *src, QualType destType,
bool listInitialization) {
if (msg == diag::err_bad_cxx_cast_generic &&
tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
listInitialization))
return;
S.Diag(opRange.getBegin(), msg) << castType
<< src->getType() << destType << opRange << src->getSourceRange();
}
/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
/// this removes one level of indirection from both types, provided that they're
/// the same kind of pointer (plain or to-member). Unlike the Sema function,
/// this one doesn't care if the two pointers-to-member don't point into the
/// same class. This is because CastsAwayConstness doesn't care.
static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
const PointerType *T1PtrType = T1->getAs<PointerType>(),
*T2PtrType = T2->getAs<PointerType>();
if (T1PtrType && T2PtrType) {
T1 = T1PtrType->getPointeeType();
T2 = T2PtrType->getPointeeType();
return true;
}
const ObjCObjectPointerType *T1ObjCPtrType =
T1->getAs<ObjCObjectPointerType>(),
*T2ObjCPtrType =
T2->getAs<ObjCObjectPointerType>();
if (T1ObjCPtrType) {
if (T2ObjCPtrType) {
T1 = T1ObjCPtrType->getPointeeType();
T2 = T2ObjCPtrType->getPointeeType();
return true;
}
else if (T2PtrType) {
T1 = T1ObjCPtrType->getPointeeType();
T2 = T2PtrType->getPointeeType();
return true;
}
}
else if (T2ObjCPtrType) {
if (T1PtrType) {
T2 = T2ObjCPtrType->getPointeeType();
T1 = T1PtrType->getPointeeType();
return true;
}
}
const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
*T2MPType = T2->getAs<MemberPointerType>();
if (T1MPType && T2MPType) {
T1 = T1MPType->getPointeeType();
T2 = T2MPType->getPointeeType();
return true;
}
const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
*T2BPType = T2->getAs<BlockPointerType>();
if (T1BPType && T2BPType) {
T1 = T1BPType->getPointeeType();
T2 = T2BPType->getPointeeType();
return true;
}
return false;
}
/// CastsAwayConstness - Check if the pointer conversion from SrcType to
/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
/// the cast checkers. Both arguments must denote pointer (possibly to member)
/// types.
///
/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
///
/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
static bool
CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
bool CheckCVR, bool CheckObjCLifetime) {
// If the only checking we care about is for Objective-C lifetime qualifiers,
// and we're not in ARC mode, there's nothing to check.
if (!CheckCVR && CheckObjCLifetime &&
!Self.Context.getLangOpts().ObjCAutoRefCount)
return false;
// Casting away constness is defined in C++ 5.2.11p8 with reference to
// C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
// the rules are non-trivial. So first we construct Tcv *...cv* as described
// in C++ 5.2.11p8.
assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
SrcType->isBlockPointerType()) &&
"Source type is not pointer or pointer to member.");
assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
DestType->isBlockPointerType()) &&
"Destination type is not pointer or pointer to member.");
QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
UnwrappedDestType = Self.Context.getCanonicalType(DestType);
SmallVector<Qualifiers, 8> cv1, cv2;
// Find the qualifiers. We only care about cvr-qualifiers for the
// purpose of this check, because other qualifiers (address spaces,
// Objective-C GC, etc.) are part of the type's identity.
while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
// Determine the relevant qualifiers at this level.
Qualifiers SrcQuals, DestQuals;
Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Qualifiers RetainedSrcQuals, RetainedDestQuals;
if (CheckCVR) {
RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
}
if (CheckObjCLifetime &&
!DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
return true;
cv1.push_back(RetainedSrcQuals);
cv2.push_back(RetainedDestQuals);
}
if (cv1.empty())
return false;
// Construct void pointers with those qualifiers (in reverse order of
// unwrapping, of course).
QualType SrcConstruct = Self.Context.VoidTy;
QualType DestConstruct = Self.Context.VoidTy;
ASTContext &Context = Self.Context;
for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
i2 = cv2.rbegin();
i1 != cv1.rend(); ++i1, ++i2) {
SrcConstruct
= Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
DestConstruct
= Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
}
// Test if they're compatible.
bool ObjCLifetimeConversion;
return SrcConstruct != DestConstruct &&
!Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
ObjCLifetimeConversion);
}
/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
/// checked downcasts in class hierarchies.
void CastOperation::CheckDynamicCast() {
if (ValueKind == VK_RValue)
- SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
+ SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
else if (isPlaceholder())
- SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
+ SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
return;
QualType OrigSrcType = SrcExpr.get()->getType();
QualType DestType = Self.Context.getCanonicalType(this->DestType);
// C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
// or "pointer to cv void".
QualType DestPointee;
const PointerType *DestPointer = DestType->getAs<PointerType>();
const ReferenceType *DestReference = nullptr;
if (DestPointer) {
DestPointee = DestPointer->getPointeeType();
} else if ((DestReference = DestType->getAs<ReferenceType>())) {
DestPointee = DestReference->getPointeeType();
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
<< this->DestType << DestRange;
SrcExpr = ExprError();
return;
}
const RecordType *DestRecord = DestPointee->getAs<RecordType>();
if (DestPointee->isVoidType()) {
assert(DestPointer && "Reference to void is not possible");
} else if (DestRecord) {
if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
diag::err_bad_dynamic_cast_incomplete,
DestRange)) {
SrcExpr = ExprError();
return;
}
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
<< DestPointee.getUnqualifiedType() << DestRange;
SrcExpr = ExprError();
return;
}
// C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
// complete class type, [...]. If T is an lvalue reference type, v shall be
// an lvalue of a complete class type, [...]. If T is an rvalue reference
// type, v shall be an expression having a complete class type, [...]
QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
QualType SrcPointee;
if (DestPointer) {
if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
SrcPointee = SrcPointer->getPointeeType();
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
<< OrigSrcType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
} else if (DestReference->isLValueReferenceType()) {
if (!SrcExpr.get()->isLValue()) {
Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
<< CT_Dynamic << OrigSrcType << this->DestType << OpRange;
}
SrcPointee = SrcType;
} else {
SrcPointee = SrcType;
}
const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
if (SrcRecord) {
if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
diag::err_bad_dynamic_cast_incomplete,
SrcExpr.get())) {
SrcExpr = ExprError();
return;
}
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
<< SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
assert((DestPointer || DestReference) &&
"Bad destination non-ptr/ref slipped through.");
assert((DestRecord || DestPointee->isVoidType()) &&
"Bad destination pointee slipped through.");
assert(SrcRecord && "Bad source pointee slipped through.");
// C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
<< CT_Dynamic << OrigSrcType << this->DestType << OpRange;
SrcExpr = ExprError();
return;
}
// C++ 5.2.7p3: If the type of v is the same as the required result type,
// [except for cv].
if (DestRecord == SrcRecord) {
Kind = CK_NoOp;
return;
}
// C++ 5.2.7p5
// Upcasts are resolved statically.
if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
OpRange.getBegin(), OpRange,
&BasePath)) {
SrcExpr = ExprError();
return;
}
Kind = CK_DerivedToBase;
// If we are casting to or through a virtual base class, we need a
// vtable.
if (Self.BasePathInvolvesVirtualBase(BasePath))
Self.MarkVTableUsed(OpRange.getBegin(),
cast<CXXRecordDecl>(SrcRecord->getDecl()));
return;
}
// C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
assert(SrcDecl && "Definition missing");
if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
<< SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
}
Self.MarkVTableUsed(OpRange.getBegin(),
cast<CXXRecordDecl>(SrcRecord->getDecl()));
// dynamic_cast is not available with -fno-rtti.
// As an exception, dynamic_cast to void* is available because it doesn't
// use RTTI.
if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
SrcExpr = ExprError();
return;
}
// Done. Everything else is run-time checks.
Kind = CK_Dynamic;
}
/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
/// like this:
/// const char *str = "literal";
/// legacy_function(const_cast\<char*\>(str));
void CastOperation::CheckConstCast() {
if (ValueKind == VK_RValue)
- SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
+ SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
else if (isPlaceholder())
- SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
+ SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
return;
unsigned msg = diag::err_bad_cxx_cast_generic;
if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
&& msg != 0) {
Self.Diag(OpRange.getBegin(), msg) << CT_Const
<< SrcExpr.get()->getType() << DestType << OpRange;
SrcExpr = ExprError();
}
}
/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
/// or downcast between respective pointers or references.
static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
QualType DestType,
SourceRange OpRange) {
QualType SrcType = SrcExpr->getType();
// When casting from pointer or reference, get pointee type; use original
// type otherwise.
const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
const CXXRecordDecl *SrcRD =
SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
// Examining subobjects for records is only possible if the complete and
// valid definition is available. Also, template instantiation is not
// allowed here.
if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
return;
const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
return;
enum {
ReinterpretUpcast,
ReinterpretDowncast
} ReinterpretKind;
CXXBasePaths BasePaths;
if (SrcRD->isDerivedFrom(DestRD, BasePaths))
ReinterpretKind = ReinterpretUpcast;
else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
ReinterpretKind = ReinterpretDowncast;
else
return;
bool VirtualBase = true;
bool NonZeroOffset = false;
for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
E = BasePaths.end();
I != E; ++I) {
const CXXBasePath &Path = *I;
CharUnits Offset = CharUnits::Zero();
bool IsVirtual = false;
for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
IElem != EElem; ++IElem) {
IsVirtual = IElem->Base->isVirtual();
if (IsVirtual)
break;
const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
assert(BaseRD && "Base type should be a valid unqualified class type");
// Don't check if any base has invalid declaration or has no definition
// since it has no layout info.
const CXXRecordDecl *Class = IElem->Class,
*ClassDefinition = Class->getDefinition();
if (Class->isInvalidDecl() || !ClassDefinition ||
!ClassDefinition->isCompleteDefinition())
return;
const ASTRecordLayout &DerivedLayout =
Self.Context.getASTRecordLayout(Class);
Offset += DerivedLayout.getBaseClassOffset(BaseRD);
}
if (!IsVirtual) {
// Don't warn if any path is a non-virtually derived base at offset zero.
if (Offset.isZero())
return;
// Offset makes sense only for non-virtual bases.
else
NonZeroOffset = true;
}
VirtualBase = VirtualBase && IsVirtual;
}
(void) NonZeroOffset; // Silence set but not used warning.
assert((VirtualBase || NonZeroOffset) &&
"Should have returned if has non-virtual base with zero offset");
QualType BaseType =
ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
QualType DerivedType =
ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
SourceLocation BeginLoc = OpRange.getBegin();
Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
<< DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
<< OpRange;
Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
<< int(ReinterpretKind)
<< FixItHint::CreateReplacement(BeginLoc, "static_cast");
}
/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
/// valid.
/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
/// like this:
/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
void CastOperation::CheckReinterpretCast() {
if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
- SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
+ SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
else
checkNonOverloadPlaceholders();
if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
return;
unsigned msg = diag::err_bad_cxx_cast_generic;
TryCastResult tcr =
TryReinterpretCast(Self, SrcExpr, DestType,
/*CStyle*/false, OpRange, msg, Kind);
if (tcr != TC_Success && msg != 0)
{
if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
return;
if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
//FIXME: &f<int>; is overloaded and resolvable
Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
<< OverloadExpr::find(SrcExpr.get()).Expression->getName()
<< DestType << OpRange;
Self.NoteAllOverloadCandidates(SrcExpr.get());
} else {
diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
DestType, /*listInitialization=*/false);
}
SrcExpr = ExprError();
} else if (tcr == TC_Success) {
if (Self.getLangOpts().ObjCAutoRefCount)
checkObjCARCConversion(Sema::CCK_OtherCast);
DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
}
}
/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
/// implicit conversions explicit and getting rid of data loss warnings.
void CastOperation::CheckStaticCast() {
if (isPlaceholder()) {
checkNonOverloadPlaceholders();
if (SrcExpr.isInvalid())
return;
}
// This test is outside everything else because it's the only case where
// a non-lvalue-reference target type does not lead to decay.
// C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
if (DestType->isVoidType()) {
Kind = CK_ToVoid;
if (claimPlaceholder(BuiltinType::Overload)) {
Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
false, // Decay Function to ptr
true, // Complain
OpRange, DestType, diag::err_bad_static_cast_overload);
if (SrcExpr.isInvalid())
return;
}
- SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
+ SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
return;
}
if (ValueKind == VK_RValue && !DestType->isRecordType() &&
!isPlaceholder(BuiltinType::Overload)) {
- SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
+ SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
return;
}
unsigned msg = diag::err_bad_cxx_cast_generic;
TryCastResult tcr
= TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Kind, BasePath, /*ListInitialization=*/false);
if (tcr != TC_Success && msg != 0) {
if (SrcExpr.isInvalid())
return;
if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
<< oe->getName() << DestType << OpRange
<< oe->getQualifierLoc().getSourceRange();
Self.NoteAllOverloadCandidates(SrcExpr.get());
} else {
diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
/*listInitialization=*/false);
}
SrcExpr = ExprError();
} else if (tcr == TC_Success) {
if (Kind == CK_BitCast)
checkCastAlign();
if (Self.getLangOpts().ObjCAutoRefCount)
checkObjCARCConversion(Sema::CCK_OtherCast);
} else if (Kind == CK_BitCast) {
checkCastAlign();
}
}
/// TryStaticCast - Check if a static cast can be performed, and do so if
/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
/// and casting away constness.
static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType,
Sema::CheckedConversionKind CCK,
const SourceRange &OpRange, unsigned &msg,
CastKind &Kind, CXXCastPath &BasePath,
bool ListInitialization) {
// Determine whether we have the semantics of a C-style cast.
bool CStyle
= (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
// The order the tests is not entirely arbitrary. There is one conversion
// that can be handled in two different ways. Given:
// struct A {};
// struct B : public A {
// B(); B(const A&);
// };
// const A &a = B();
// the cast static_cast<const B&>(a) could be seen as either a static
// reference downcast, or an explicit invocation of the user-defined
// conversion using B's conversion constructor.
// DR 427 specifies that the downcast is to be applied here.
// C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
// Done outside this function.
TryCastResult tcr;
// C++ 5.2.9p5, reference downcast.
// See the function for details.
// DR 427 specifies that this is to be applied before paragraph 2.
tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
OpRange, msg, Kind, BasePath);
if (tcr != TC_NotApplicable)
return tcr;
// C++0x [expr.static.cast]p3:
// A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
// T2" if "cv2 T2" is reference-compatible with "cv1 T1".
tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
BasePath, msg);
if (tcr != TC_NotApplicable)
return tcr;
// C++ 5.2.9p2: An expression e can be explicitly converted to a type T
// [...] if the declaration "T t(e);" is well-formed, [...].
tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Kind, ListInitialization);
if (SrcExpr.isInvalid())
return TC_Failed;
if (tcr != TC_NotApplicable)
return tcr;
// C++ 5.2.9p6: May apply the reverse of any standard conversion, except
// lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
// conversions, subject to further restrictions.
// Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
// of qualification conversions impossible.
// In the CStyle case, the earlier attempt to const_cast should have taken
// care of reverse qualification conversions.
QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
// C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
// converted to an integral type. [...] A value of a scoped enumeration type
// can also be explicitly converted to a floating-point type [...].
if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
if (Enum->getDecl()->isScoped()) {
if (DestType->isBooleanType()) {
Kind = CK_IntegralToBoolean;
return TC_Success;
} else if (DestType->isIntegralType(Self.Context)) {
Kind = CK_IntegralCast;
return TC_Success;
} else if (DestType->isRealFloatingType()) {
Kind = CK_IntegralToFloating;
return TC_Success;
}
}
}
// Reverse integral promotion/conversion. All such conversions are themselves
// again integral promotions or conversions and are thus already handled by
// p2 (TryDirectInitialization above).
// (Note: any data loss warnings should be suppressed.)
// The exception is the reverse of enum->integer, i.e. integer->enum (and
// enum->enum). See also C++ 5.2.9p7.
// The same goes for reverse floating point promotion/conversion and
// floating-integral conversions. Again, only floating->enum is relevant.
if (DestType->isEnumeralType()) {
if (SrcType->isIntegralOrEnumerationType()) {
Kind = CK_IntegralCast;
return TC_Success;
} else if (SrcType->isRealFloatingType()) {
Kind = CK_FloatingToIntegral;
return TC_Success;
}
}
// Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
// C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Kind, BasePath);
if (tcr != TC_NotApplicable)
return tcr;
// Reverse member pointer conversion. C++ 4.11 specifies member pointer
// conversion. C++ 5.2.9p9 has additional information.
// DR54's access restrictions apply here also.
tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
OpRange, msg, Kind, BasePath);
if (tcr != TC_NotApplicable)
return tcr;
// Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
// void*. C++ 5.2.9p10 specifies additional restrictions, which really is
// just the usual constness stuff.
if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
QualType SrcPointee = SrcPointer->getPointeeType();
if (SrcPointee->isVoidType()) {
if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
QualType DestPointee = DestPointer->getPointeeType();
if (DestPointee->isIncompleteOrObjectType()) {
// This is definitely the intended conversion, but it might fail due
// to a qualifier violation. Note that we permit Objective-C lifetime
// and GC qualifier mismatches here.
if (!CStyle) {
Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
DestPointeeQuals.removeObjCGCAttr();
DestPointeeQuals.removeObjCLifetime();
SrcPointeeQuals.removeObjCGCAttr();
SrcPointeeQuals.removeObjCLifetime();
if (DestPointeeQuals != SrcPointeeQuals &&
!DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
msg = diag::err_bad_cxx_cast_qualifiers_away;
return TC_Failed;
}
}
Kind = CK_BitCast;
return TC_Success;
}
}
else if (DestType->isObjCObjectPointerType()) {
// allow both c-style cast and static_cast of objective-c pointers as
// they are pervasive.
Kind = CK_CPointerToObjCPointerCast;
return TC_Success;
}
else if (CStyle && DestType->isBlockPointerType()) {
// allow c-style cast of void * to block pointers.
Kind = CK_AnyPointerToBlockPointerCast;
return TC_Success;
}
}
}
// Allow arbitray objective-c pointer conversion with static casts.
if (SrcType->isObjCObjectPointerType() &&
DestType->isObjCObjectPointerType()) {
Kind = CK_BitCast;
return TC_Success;
}
// Allow ns-pointer to cf-pointer conversion in either direction
// with static casts.
if (!CStyle &&
Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
return TC_Success;
// We tried everything. Everything! Nothing works! :-(
return TC_NotApplicable;
}
/// Tests whether a conversion according to N2844 is valid.
TryCastResult
TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
unsigned &msg) {
// C++0x [expr.static.cast]p3:
// A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
// cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
if (!R)
return TC_NotApplicable;
if (!SrcExpr->isGLValue())
return TC_NotApplicable;
// Because we try the reference downcast before this function, from now on
// this is the only cast possibility, so we issue an error if we fail now.
// FIXME: Should allow casting away constness if CStyle.
bool DerivedToBase;
bool ObjCConversion;
bool ObjCLifetimeConversion;
QualType FromType = SrcExpr->getType();
QualType ToType = R->getPointeeType();
if (CStyle) {
FromType = FromType.getUnqualifiedType();
ToType = ToType.getUnqualifiedType();
}
if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
ToType, FromType,
DerivedToBase, ObjCConversion,
ObjCLifetimeConversion)
< Sema::Ref_Compatible_With_Added_Qualification) {
msg = diag::err_bad_lvalue_to_rvalue_cast;
return TC_Failed;
}
if (DerivedToBase) {
Kind = CK_DerivedToBase;
CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
/*DetectVirtual=*/true);
if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
return TC_NotApplicable;
Self.BuildBasePathArray(Paths, BasePath);
} else
Kind = CK_NoOp;
return TC_Success;
}
/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
TryCastResult
TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
bool CStyle, const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
CXXCastPath &BasePath) {
// C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
// cast to type "reference to cv2 D", where D is a class derived from B,
// if a valid standard conversion from "pointer to D" to "pointer to B"
// exists, cv2 >= cv1, and B is not a virtual base class of D.
// In addition, DR54 clarifies that the base must be accessible in the
// current context. Although the wording of DR54 only applies to the pointer
// variant of this rule, the intent is clearly for it to apply to the this
// conversion as well.
const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
if (!DestReference) {
return TC_NotApplicable;
}
bool RValueRef = DestReference->isRValueReferenceType();
if (!RValueRef && !SrcExpr->isLValue()) {
// We know the left side is an lvalue reference, so we can suggest a reason.
msg = diag::err_bad_cxx_cast_rvalue;
return TC_NotApplicable;
}
QualType DestPointee = DestReference->getPointeeType();
return TryStaticDowncast(Self,
Self.Context.getCanonicalType(SrcExpr->getType()),
Self.Context.getCanonicalType(DestPointee), CStyle,
OpRange, SrcExpr->getType(), DestType, msg, Kind,
BasePath);
}
/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
TryCastResult
TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
bool CStyle, const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
CXXCastPath &BasePath) {
// C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
// type, can be converted to an rvalue of type "pointer to cv2 D", where D
// is a class derived from B, if a valid standard conversion from "pointer
// to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
// class of D.
// In addition, DR54 clarifies that the base must be accessible in the
// current context.
const PointerType *DestPointer = DestType->getAs<PointerType>();
if (!DestPointer) {
return TC_NotApplicable;
}
const PointerType *SrcPointer = SrcType->getAs<PointerType>();
if (!SrcPointer) {
msg = diag::err_bad_static_cast_pointer_nonpointer;
return TC_NotApplicable;
}
return TryStaticDowncast(Self,
Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
Self.Context.getCanonicalType(DestPointer->getPointeeType()),
CStyle, OpRange, SrcType, DestType, msg, Kind,
BasePath);
}
/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
/// DestType is possible and allowed.
TryCastResult
TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
QualType OrigDestType, unsigned &msg,
CastKind &Kind, CXXCastPath &BasePath) {
// We can only work with complete types. But don't complain if it doesn't work
if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
return TC_NotApplicable;
// Downcast can only happen in class hierarchies, so we need classes.
if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
return TC_NotApplicable;
}
CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
/*DetectVirtual=*/true);
if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
return TC_NotApplicable;
}
// Target type does derive from source type. Now we're serious. If an error
// appears now, it's not ignored.
// This may not be entirely in line with the standard. Take for example:
// struct A {};
// struct B : virtual A {
// B(A&);
// };
//
// void f()
// {
// (void)static_cast<const B&>(*((A*)0));
// }
// As far as the standard is concerned, p5 does not apply (A is virtual), so
// p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
// However, both GCC and Comeau reject this example, and accepting it would
// mean more complex code if we're to preserve the nice error message.
// FIXME: Being 100% compliant here would be nice to have.
// Must preserve cv, as always, unless we're in C-style mode.
if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
msg = diag::err_bad_cxx_cast_qualifiers_away;
return TC_Failed;
}
if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
// This code is analoguous to that in CheckDerivedToBaseConversion, except
// that it builds the paths in reverse order.
// To sum up: record all paths to the base and build a nice string from
// them. Use it to spice up the error message.
if (!Paths.isRecordingPaths()) {
Paths.clear();
Paths.setRecordingPaths(true);
Self.IsDerivedFrom(DestType, SrcType, Paths);
}
std::string PathDisplayStr;
std::set<unsigned> DisplayedPaths;
for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
PI != PE; ++PI) {
if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
// We haven't displayed a path to this particular base
// class subobject yet.
PathDisplayStr += "\n ";
for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
EE = PI->rend();
EI != EE; ++EI)
PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
PathDisplayStr += QualType(DestType).getAsString();
}
}
Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
<< QualType(SrcType).getUnqualifiedType()
<< QualType(DestType).getUnqualifiedType()
<< PathDisplayStr << OpRange;
msg = 0;
return TC_Failed;
}
if (Paths.getDetectedVirtual() != nullptr) {
QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
<< OrigSrcType << OrigDestType << VirtualBase << OpRange;
msg = 0;
return TC_Failed;
}
if (!CStyle) {
switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
SrcType, DestType,
Paths.front(),
diag::err_downcast_from_inaccessible_base)) {
case Sema::AR_accessible:
case Sema::AR_delayed: // be optimistic
case Sema::AR_dependent: // be optimistic
break;
case Sema::AR_inaccessible:
msg = 0;
return TC_Failed;
}
}
Self.BuildBasePathArray(Paths, BasePath);
Kind = CK_BaseToDerived;
return TC_Success;
}
/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
/// C++ 5.2.9p9 is valid:
///
/// An rvalue of type "pointer to member of D of type cv1 T" can be
/// converted to an rvalue of type "pointer to member of B of type cv2 T",
/// where B is a base class of D [...].
///
TryCastResult
TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
CXXCastPath &BasePath) {
const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
if (!DestMemPtr)
return TC_NotApplicable;
bool WasOverloadedFunction = false;
DeclAccessPair FoundOverload;
if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
if (FunctionDecl *Fn
= Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
FoundOverload)) {
CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
SrcType = Self.Context.getMemberPointerType(Fn->getType(),
Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
WasOverloadedFunction = true;
}
}
const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
if (!SrcMemPtr) {
msg = diag::err_bad_static_cast_member_pointer_nonmp;
return TC_NotApplicable;
}
// T == T, modulo cv
if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
DestMemPtr->getPointeeType()))
return TC_NotApplicable;
// B base of D
QualType SrcClass(SrcMemPtr->getClass(), 0);
QualType DestClass(DestMemPtr->getClass(), 0);
CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
/*DetectVirtual=*/true);
if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) ||
!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
return TC_NotApplicable;
}
// B is a base of D. But is it an allowed base? If not, it's a hard error.
if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Paths.clear();
Paths.setRecordingPaths(true);
bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
assert(StillOkay);
(void)StillOkay;
std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
<< 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
msg = 0;
return TC_Failed;
}
if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
<< SrcClass << DestClass << QualType(VBase, 0) << OpRange;
msg = 0;
return TC_Failed;
}
if (!CStyle) {
switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
DestClass, SrcClass,
Paths.front(),
diag::err_upcast_to_inaccessible_base)) {
case Sema::AR_accessible:
case Sema::AR_delayed:
case Sema::AR_dependent:
// Optimistically assume that the delayed and dependent cases
// will work out.
break;
case Sema::AR_inaccessible:
msg = 0;
return TC_Failed;
}
}
if (WasOverloadedFunction) {
// Resolve the address of the overloaded function again, this time
// allowing complaints if something goes wrong.
FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
DestType,
true,
FoundOverload);
if (!Fn) {
msg = 0;
return TC_Failed;
}
SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
if (!SrcExpr.isUsable()) {
msg = 0;
return TC_Failed;
}
}
Self.BuildBasePathArray(Paths, BasePath);
Kind = CK_DerivedToBaseMemberPointer;
return TC_Success;
}
/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
/// is valid:
///
/// An expression e can be explicitly converted to a type T using a
/// @c static_cast if the declaration "T t(e);" is well-formed [...].
TryCastResult
TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
Sema::CheckedConversionKind CCK,
const SourceRange &OpRange, unsigned &msg,
CastKind &Kind, bool ListInitialization) {
if (DestType->isRecordType()) {
if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
diag::err_bad_dynamic_cast_incomplete) ||
Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
diag::err_allocation_of_abstract_type)) {
msg = 0;
return TC_Failed;
}
} else if (DestType->isMemberPointerType()) {
if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
}
}
InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
InitializationKind InitKind
= (CCK == Sema::CCK_CStyleCast)
? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
ListInitialization)
: (CCK == Sema::CCK_FunctionalCast)
? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
: InitializationKind::CreateCast(OpRange);
Expr *SrcExprRaw = SrcExpr.get();
InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
// At this point of CheckStaticCast, if the destination is a reference,
// or the expression is an overload expression this has to work.
// There is no other way that works.
// On the other hand, if we're checking a C-style cast, we've still got
// the reinterpret_cast way.
bool CStyle
= (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
return TC_NotApplicable;
ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
if (Result.isInvalid()) {
msg = 0;
return TC_Failed;
}
if (InitSeq.isConstructorInitialization())
Kind = CK_ConstructorConversion;
else
Kind = CK_NoOp;
SrcExpr = Result;
return TC_Success;
}
/// TryConstCast - See if a const_cast from source to destination is allowed,
/// and perform it if it is.
static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType, bool CStyle,
unsigned &msg) {
DestType = Self.Context.getCanonicalType(DestType);
QualType SrcType = SrcExpr.get()->getType();
bool NeedToMaterializeTemporary = false;
if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
// C++11 5.2.11p4:
// if a pointer to T1 can be explicitly converted to the type "pointer to
// T2" using a const_cast, then the following conversions can also be
// made:
// -- an lvalue of type T1 can be explicitly converted to an lvalue of
// type T2 using the cast const_cast<T2&>;
// -- a glvalue of type T1 can be explicitly converted to an xvalue of
// type T2 using the cast const_cast<T2&&>; and
// -- if T1 is a class type, a prvalue of type T1 can be explicitly
// converted to an xvalue of type T2 using the cast const_cast<T2&&>.
if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
// Cannot const_cast non-lvalue to lvalue reference type. But if this
// is C-style, static_cast might find a way, so we simply suggest a
// message and tell the parent to keep searching.
msg = diag::err_bad_cxx_cast_rvalue;
return TC_NotApplicable;
}
if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
if (!SrcType->isRecordType()) {
// Cannot const_cast non-class prvalue to rvalue reference type. But if
// this is C-style, static_cast can do this.
msg = diag::err_bad_cxx_cast_rvalue;
return TC_NotApplicable;
}
// Materialize the class prvalue so that the const_cast can bind a
// reference to it.
NeedToMaterializeTemporary = true;
}
// It's not completely clear under the standard whether we can
// const_cast bit-field gl-values. Doing so would not be
// intrinsically complicated, but for now, we say no for
// consistency with other compilers and await the word of the
// committee.
if (SrcExpr.get()->refersToBitField()) {
msg = diag::err_bad_cxx_cast_bitfield;
return TC_NotApplicable;
}
DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
SrcType = Self.Context.getPointerType(SrcType);
}
// C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
// the rules for const_cast are the same as those used for pointers.
if (!DestType->isPointerType() &&
!DestType->isMemberPointerType() &&
!DestType->isObjCObjectPointerType()) {
// Cannot cast to non-pointer, non-reference type. Note that, if DestType
// was a reference type, we converted it to a pointer above.
// The status of rvalue references isn't entirely clear, but it looks like
// conversion to them is simply invalid.
// C++ 5.2.11p3: For two pointer types [...]
if (!CStyle)
msg = diag::err_bad_const_cast_dest;
return TC_NotApplicable;
}
if (DestType->isFunctionPointerType() ||
DestType->isMemberFunctionPointerType()) {
// Cannot cast direct function pointers.
// C++ 5.2.11p2: [...] where T is any object type or the void type [...]
// T is the ultimate pointee of source and target type.
if (!CStyle)
msg = diag::err_bad_const_cast_dest;
return TC_NotApplicable;
}
SrcType = Self.Context.getCanonicalType(SrcType);
// Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
// completely equal.
// C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
// in multi-level pointers may change, but the level count must be the same,
// as must be the final pointee type.
while (SrcType != DestType &&
Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Qualifiers SrcQuals, DestQuals;
SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
// const_cast is permitted to strip cvr-qualifiers, only. Make sure that
// the other qualifiers (e.g., address spaces) are identical.
SrcQuals.removeCVRQualifiers();
DestQuals.removeCVRQualifiers();
if (SrcQuals != DestQuals)
return TC_NotApplicable;
}
// Since we're dealing in canonical types, the remainder must be the same.
if (SrcType != DestType)
return TC_NotApplicable;
if (NeedToMaterializeTemporary)
// This is a const_cast from a class prvalue to an rvalue reference type.
// Materialize a temporary to store the result of the conversion.
SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
- SrcType, SrcExpr.take(), /*IsLValueReference*/ false);
+ SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
return TC_Success;
}
// Checks for undefined behavior in reinterpret_cast.
// The cases that is checked for is:
// *reinterpret_cast<T*>(&a)
// reinterpret_cast<T&>(a)
// where accessing 'a' as type 'T' will result in undefined behavior.
void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference,
SourceRange Range) {
unsigned DiagID = IsDereference ?
diag::warn_pointer_indirection_from_incompatible_type :
diag::warn_undefined_reinterpret_cast;
if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
DiagnosticsEngine::Ignored) {
return;
}
QualType SrcTy, DestTy;
if (IsDereference) {
if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
return;
}
SrcTy = SrcType->getPointeeType();
DestTy = DestType->getPointeeType();
} else {
if (!DestType->getAs<ReferenceType>()) {
return;
}
SrcTy = SrcType;
DestTy = DestType->getPointeeType();
}
// Cast is compatible if the types are the same.
if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
return;
}
// or one of the types is a char or void type
if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
return;
}
// or one of the types is a tag type.
if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
return;
}
// FIXME: Scoped enums?
if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
(SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
return;
}
}
Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
}
static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
QualType DestType) {
QualType SrcType = SrcExpr.get()->getType();
if (Self.Context.hasSameType(SrcType, DestType))
return;
if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
if (SrcPtrTy->isObjCSelType()) {
QualType DT = DestType;
if (isa<PointerType>(DestType))
DT = DestType->getPointeeType();
if (!DT.getUnqualifiedType()->isVoidType())
Self.Diag(SrcExpr.get()->getExprLoc(),
diag::warn_cast_pointer_from_sel)
<< SrcType << DestType << SrcExpr.get()->getSourceRange();
}
}
static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
const Expr *SrcExpr, QualType DestType,
Sema &Self) {
QualType SrcType = SrcExpr->getType();
// Not warning on reinterpret_cast, boolean, constant expressions, etc
// are not explicit design choices, but consistent with GCC's behavior.
// Feel free to modify them if you've reason/evidence for an alternative.
if (CStyle && SrcType->isIntegralType(Self.Context)
&& !SrcType->isBooleanType()
&& !SrcType->isEnumeralType()
&& !SrcExpr->isIntegerConstantExpr(Self.Context)
&& Self.Context.getTypeSize(DestType) >
Self.Context.getTypeSize(SrcType)) {
// Separate between casts to void* and non-void* pointers.
// Some APIs use (abuse) void* for something like a user context,
// and often that value is an integer even if it isn't a pointer itself.
// Having a separate warning flag allows users to control the warning
// for their workflow.
unsigned Diag = DestType->isVoidPointerType() ?
diag::warn_int_to_void_pointer_cast
: diag::warn_int_to_pointer_cast;
Self.Diag(Loc, Diag) << SrcType << DestType;
}
}
static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind) {
bool IsLValueCast = false;
DestType = Self.Context.getCanonicalType(DestType);
QualType SrcType = SrcExpr.get()->getType();
// Is the source an overloaded name? (i.e. &foo)
// If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
if (SrcType == Self.Context.OverloadTy) {
// ... unless foo<int> resolves to an lvalue unambiguously.
// TODO: what if this fails because of DiagnoseUseOfDecl or something
// like it?
ExprResult SingleFunctionExpr = SrcExpr;
if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
SingleFunctionExpr,
Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
) && SingleFunctionExpr.isUsable()) {
SrcExpr = SingleFunctionExpr;
SrcType = SrcExpr.get()->getType();
} else {
return TC_NotApplicable;
}
}
if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
if (!SrcExpr.get()->isGLValue()) {
// Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
// similar comment in const_cast.
msg = diag::err_bad_cxx_cast_rvalue;
return TC_NotApplicable;
}
if (!CStyle) {
Self.CheckCompatibleReinterpretCast(SrcType, DestType,
/*isDereference=*/false, OpRange);
}
// C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
// same effect as the conversion *reinterpret_cast<T*>(&x) with the
// built-in & and * operators.
const char *inappropriate = nullptr;
switch (SrcExpr.get()->getObjectKind()) {
case OK_Ordinary:
break;
case OK_BitField: inappropriate = "bit-field"; break;
case OK_VectorComponent: inappropriate = "vector element"; break;
case OK_ObjCProperty: inappropriate = "property expression"; break;
case OK_ObjCSubscript: inappropriate = "container subscripting expression";
break;
}
if (inappropriate) {
Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
<< inappropriate << DestType
<< OpRange << SrcExpr.get()->getSourceRange();
msg = 0; SrcExpr = ExprError();
return TC_NotApplicable;
}
// This code does this transformation for the checked types.
DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
SrcType = Self.Context.getPointerType(SrcType);
IsLValueCast = true;
}
// Canonicalize source for comparison.
SrcType = Self.Context.getCanonicalType(SrcType);
const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
*SrcMemPtr = SrcType->getAs<MemberPointerType>();
if (DestMemPtr && SrcMemPtr) {
// C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
// can be explicitly converted to an rvalue of type "pointer to member
// of Y of type T2" if T1 and T2 are both function types or both object
// types.
if (DestMemPtr->getPointeeType()->isFunctionType() !=
SrcMemPtr->getPointeeType()->isFunctionType())
return TC_NotApplicable;
// C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
// constness.
// A reinterpret_cast followed by a const_cast can, though, so in C-style,
// we accept it.
if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
/*CheckObjCLifetime=*/CStyle)) {
msg = diag::err_bad_cxx_cast_qualifiers_away;
return TC_Failed;
}
if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
// We need to determine the inheritance model that the class will use if
// haven't yet.
Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0);
Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
}
// Don't allow casting between member pointers of different sizes.
if (Self.Context.getTypeSize(DestMemPtr) !=
Self.Context.getTypeSize(SrcMemPtr)) {
msg = diag::err_bad_cxx_cast_member_pointer_size;
return TC_Failed;
}
// A valid member pointer cast.
assert(!IsLValueCast);
Kind = CK_ReinterpretMemberPointer;
return TC_Success;
}
// See below for the enumeral issue.
if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
// C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
// type large enough to hold it. A value of std::nullptr_t can be
// converted to an integral type; the conversion has the same meaning
// and validity as a conversion of (void*)0 to the integral type.
if (Self.Context.getTypeSize(SrcType) >
Self.Context.getTypeSize(DestType)) {
msg = diag::err_bad_reinterpret_cast_small_int;
return TC_Failed;
}
Kind = CK_PointerToIntegral;
return TC_Success;
}
bool destIsVector = DestType->isVectorType();
bool srcIsVector = SrcType->isVectorType();
if (srcIsVector || destIsVector) {
// FIXME: Should this also apply to floating point types?
bool srcIsScalar = SrcType->isIntegralType(Self.Context);
bool destIsScalar = DestType->isIntegralType(Self.Context);
// Check if this is a cast between a vector and something else.
if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
!(srcIsVector && destIsVector))
return TC_NotApplicable;
// If both types have the same size, we can successfully cast.
if (Self.Context.getTypeSize(SrcType)
== Self.Context.getTypeSize(DestType)) {
Kind = CK_BitCast;
return TC_Success;
}
if (destIsScalar)
msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
else if (srcIsScalar)
msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
else
msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
return TC_Failed;
}
if (SrcType == DestType) {
// C++ 5.2.10p2 has a note that mentions that, subject to all other
// restrictions, a cast to the same type is allowed so long as it does not
// cast away constness. In C++98, the intent was not entirely clear here,
// since all other paragraphs explicitly forbid casts to the same type.
// C++11 clarifies this case with p2.
//
// The only allowed types are: integral, enumeration, pointer, or
// pointer-to-member types. We also won't restrict Obj-C pointers either.
Kind = CK_NoOp;
TryCastResult Result = TC_NotApplicable;
if (SrcType->isIntegralOrEnumerationType() ||
SrcType->isAnyPointerType() ||
SrcType->isMemberPointerType() ||
SrcType->isBlockPointerType()) {
Result = TC_Success;
}
return Result;
}
bool destIsPtr = DestType->isAnyPointerType() ||
DestType->isBlockPointerType();
bool srcIsPtr = SrcType->isAnyPointerType() ||
SrcType->isBlockPointerType();
if (!destIsPtr && !srcIsPtr) {
// Except for std::nullptr_t->integer and lvalue->reference, which are
// handled above, at least one of the two arguments must be a pointer.
return TC_NotApplicable;
}
if (DestType->isIntegralType(Self.Context)) {
assert(srcIsPtr && "One type must be a pointer");
// C++ 5.2.10p4: A pointer can be explicitly converted to any integral
// type large enough to hold it; except in Microsoft mode, where the
// integral type size doesn't matter (except we don't allow bool).
bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
!DestType->isBooleanType();
if ((Self.Context.getTypeSize(SrcType) >
Self.Context.getTypeSize(DestType)) &&
!MicrosoftException) {
msg = diag::err_bad_reinterpret_cast_small_int;
return TC_Failed;
}
Kind = CK_PointerToIntegral;
return TC_Success;
}
if (SrcType->isIntegralOrEnumerationType()) {
assert(destIsPtr && "One type must be a pointer");
checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
Self);
// C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
// converted to a pointer.
// C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
// necessarily converted to a null pointer value.]
Kind = CK_IntegralToPointer;
return TC_Success;
}
if (!destIsPtr || !srcIsPtr) {
// With the valid non-pointer conversions out of the way, we can be even
// more stringent.
return TC_NotApplicable;
}
// C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
// The C-style cast operator can.
if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
/*CheckObjCLifetime=*/CStyle)) {
msg = diag::err_bad_cxx_cast_qualifiers_away;
return TC_Failed;
}
// Cannot convert between block pointers and Objective-C object pointers.
if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
(DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
return TC_NotApplicable;
if (IsLValueCast) {
Kind = CK_LValueBitCast;
} else if (DestType->isObjCObjectPointerType()) {
Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
} else if (DestType->isBlockPointerType()) {
if (!SrcType->isBlockPointerType()) {
Kind = CK_AnyPointerToBlockPointerCast;
} else {
Kind = CK_BitCast;
}
} else {
Kind = CK_BitCast;
}
// Any pointer can be cast to an Objective-C pointer type with a C-style
// cast.
if (CStyle && DestType->isObjCObjectPointerType()) {
return TC_Success;
}
if (CStyle)
DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
// Not casting away constness, so the only remaining check is for compatible
// pointer categories.
if (SrcType->isFunctionPointerType()) {
if (DestType->isFunctionPointerType()) {
// C++ 5.2.10p6: A pointer to a function can be explicitly converted to
// a pointer to a function of a different type.
return TC_Success;
}
// C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
// an object type or vice versa is conditionally-supported.
// Compilers support it in C++03 too, though, because it's necessary for
// casting the return value of dlsym() and GetProcAddress().
// FIXME: Conditionally-supported behavior should be configurable in the
// TargetInfo or similar.
Self.Diag(OpRange.getBegin(),
Self.getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
<< OpRange;
return TC_Success;
}
if (DestType->isFunctionPointerType()) {
// See above.
Self.Diag(OpRange.getBegin(),
Self.getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
<< OpRange;
return TC_Success;
}
// C++ 5.2.10p7: A pointer to an object can be explicitly converted to
// a pointer to an object of different type.
// Void pointers are not specified, but supported by every compiler out there.
// So we finish by allowing everything that remains - it's got to be two
// object pointers.
return TC_Success;
}
void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
bool ListInitialization) {
// Handle placeholders.
if (isPlaceholder()) {
// C-style casts can resolve __unknown_any types.
if (claimPlaceholder(BuiltinType::UnknownAny)) {
SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
SrcExpr.get(), Kind,
ValueKind, BasePath);
return;
}
checkNonOverloadPlaceholders();
if (SrcExpr.isInvalid())
return;
}
// C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
// This test is outside everything else because it's the only case where
// a non-lvalue-reference target type does not lead to decay.
if (DestType->isVoidType()) {
Kind = CK_ToVoid;
if (claimPlaceholder(BuiltinType::Overload)) {
Self.ResolveAndFixSingleFunctionTemplateSpecialization(
SrcExpr, /* Decay Function to ptr */ false,
/* Complain */ true, DestRange, DestType,
diag::err_bad_cstyle_cast_overload);
if (SrcExpr.isInvalid())
return;
}
- SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
+ SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
return;
}
// If the type is dependent, we won't do any other semantic analysis now.
if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
SrcExpr.get()->isValueDependent()) {
assert(Kind == CK_Dependent);
return;
}
if (ValueKind == VK_RValue && !DestType->isRecordType() &&
!isPlaceholder(BuiltinType::Overload)) {
- SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
+ SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
if (SrcExpr.isInvalid())
return;
}
// AltiVec vector initialization with a single literal.
if (const VectorType *vecTy = DestType->getAs<VectorType>())
if (vecTy->getVectorKind() == VectorType::AltiVecVector
&& (SrcExpr.get()->getType()->isIntegerType()
|| SrcExpr.get()->getType()->isFloatingType())) {
Kind = CK_VectorSplat;
return;
}
// C++ [expr.cast]p5: The conversions performed by
// - a const_cast,
// - a static_cast,
// - a static_cast followed by a const_cast,
// - a reinterpret_cast, or
// - a reinterpret_cast followed by a const_cast,
// can be performed using the cast notation of explicit type conversion.
// [...] If a conversion can be interpreted in more than one of the ways
// listed above, the interpretation that appears first in the list is used,
// even if a cast resulting from that interpretation is ill-formed.
// In plain language, this means trying a const_cast ...
unsigned msg = diag::err_bad_cxx_cast_generic;
TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
/*CStyle*/true, msg);
if (SrcExpr.isInvalid())
return;
if (tcr == TC_Success)
Kind = CK_NoOp;
Sema::CheckedConversionKind CCK
= FunctionalStyle? Sema::CCK_FunctionalCast
: Sema::CCK_CStyleCast;
if (tcr == TC_NotApplicable) {
// ... or if that is not possible, a static_cast, ignoring const, ...
tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
msg, Kind, BasePath, ListInitialization);
if (SrcExpr.isInvalid())
return;
if (tcr == TC_NotApplicable) {
// ... and finally a reinterpret_cast, ignoring const.
tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
OpRange, msg, Kind);
if (SrcExpr.isInvalid())
return;
}
}
if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
checkObjCARCConversion(CCK);
if (tcr != TC_Success && msg != 0) {
if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
DeclAccessPair Found;
FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
DestType,
/*Complain*/ true,
Found);
if (Fn) {
// If DestType is a function type (not to be confused with the function
// pointer type), it will be possible to resolve the function address,
// but the type cast should be considered as failure.
OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
<< OE->getName() << DestType << OpRange
<< OE->getQualifierLoc().getSourceRange();
Self.NoteAllOverloadCandidates(SrcExpr.get());
}
} else {
diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
OpRange, SrcExpr.get(), DestType, ListInitialization);
}
} else if (Kind == CK_BitCast) {
checkCastAlign();
}
// Clear out SrcExpr if there was a fatal error.
if (tcr != TC_Success)
SrcExpr = ExprError();
}
/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
/// non-matching type. Such as enum function call to int, int call to
/// pointer; etc. Cast to 'void' is an exception.
static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
QualType DestType) {
if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
SrcExpr.get()->getExprLoc())
== DiagnosticsEngine::Ignored)
return;
if (!isa<CallExpr>(SrcExpr.get()))
return;
QualType SrcType = SrcExpr.get()->getType();
if (DestType.getUnqualifiedType()->isVoidType())
return;
if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
&& (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
return;
if (SrcType->isIntegerType() && DestType->isIntegerType() &&
(SrcType->isBooleanType() == DestType->isBooleanType()) &&
(SrcType->isEnumeralType() == DestType->isEnumeralType()))
return;
if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
return;
if (SrcType->isEnumeralType() && DestType->isEnumeralType())
return;
if (SrcType->isComplexType() && DestType->isComplexType())
return;
if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
return;
Self.Diag(SrcExpr.get()->getExprLoc(),
diag::warn_bad_function_cast)
<< SrcType << DestType << SrcExpr.get()->getSourceRange();
}
/// Check the semantics of a C-style cast operation, in C.
void CastOperation::CheckCStyleCast() {
assert(!Self.getLangOpts().CPlusPlus);
// C-style casts can resolve __unknown_any types.
if (claimPlaceholder(BuiltinType::UnknownAny)) {
SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
SrcExpr.get(), Kind,
ValueKind, BasePath);
return;
}
// C99 6.5.4p2: the cast type needs to be void or scalar and the expression
// type needs to be scalar.
if (DestType->isVoidType()) {
// We don't necessarily do lvalue-to-rvalue conversions on this.
- SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
+ SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
if (SrcExpr.isInvalid())
return;
// Cast to void allows any expr type.
Kind = CK_ToVoid;
return;
}
- SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
+ SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
if (SrcExpr.isInvalid())
return;
QualType SrcType = SrcExpr.get()->getType();
assert(!SrcType->isPlaceholderType());
// OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
// address space B is illegal.
if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
SrcType->isPointerType()) {
if (DestType->getPointeeType().getAddressSpace() !=
SrcType->getPointeeType().getAddressSpace()) {
Self.Diag(OpRange.getBegin(),
diag::err_typecheck_incompatible_address_space)
<< SrcType << DestType << Sema::AA_Casting
<< SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
}
if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
diag::err_typecheck_cast_to_incomplete)) {
SrcExpr = ExprError();
return;
}
if (!DestType->isScalarType() && !DestType->isVectorType()) {
const RecordType *DestRecordTy = DestType->getAs<RecordType>();
if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
// GCC struct/union extension: allow cast to self.
Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
<< DestType << SrcExpr.get()->getSourceRange();
Kind = CK_NoOp;
return;
}
// GCC's cast to union extension.
if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
RecordDecl *RD = DestRecordTy->getDecl();
RecordDecl::field_iterator Field, FieldEnd;
for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Field != FieldEnd; ++Field) {
if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
!Field->isUnnamedBitfield()) {
Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
<< SrcExpr.get()->getSourceRange();
break;
}
}
if (Field == FieldEnd) {
Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
<< SrcType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
Kind = CK_ToUnion;
return;
}
// Reject any other conversions to non-scalar types.
Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
<< DestType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
// The type we're casting to is known to be a scalar or vector.
// Require the operand to be a scalar or vector.
if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
Self.Diag(SrcExpr.get()->getExprLoc(),
diag::err_typecheck_expect_scalar_operand)
<< SrcType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
if (DestType->isExtVectorType()) {
- SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
+ SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
return;
}
if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
(SrcType->isIntegerType() || SrcType->isFloatingType())) {
Kind = CK_VectorSplat;
} else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
SrcExpr = ExprError();
}
return;
}
if (SrcType->isVectorType()) {
if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
SrcExpr = ExprError();
return;
}
// The source and target types are both scalars, i.e.
// - arithmetic types (fundamental, enum, and complex)
// - all kinds of pointers
// Note that member pointers were filtered out with C++, above.
if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
SrcExpr = ExprError();
return;
}
// If either type is a pointer, the other type has to be either an
// integer or a pointer.
if (!DestType->isArithmeticType()) {
if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
Self.Diag(SrcExpr.get()->getExprLoc(),
diag::err_cast_pointer_from_non_pointer_int)
<< SrcType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
DestType, Self);
} else if (!SrcType->isArithmeticType()) {
if (!DestType->isIntegralType(Self.Context) &&
DestType->isArithmeticType()) {
Self.Diag(SrcExpr.get()->getLocStart(),
diag::err_cast_pointer_to_non_pointer_int)
<< DestType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
}
if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
if (DestType->isHalfType()) {
Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
<< DestType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
}
// ARC imposes extra restrictions on casts.
if (Self.getLangOpts().ObjCAutoRefCount) {
checkObjCARCConversion(Sema::CCK_CStyleCast);
if (SrcExpr.isInvalid())
return;
if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
ExprPtr->getPointeeType()->isObjCLifetimeType() &&
!CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Self.Diag(SrcExpr.get()->getLocStart(),
diag::err_typecheck_incompatible_ownership)
<< SrcType << DestType << Sema::AA_Casting
<< SrcExpr.get()->getSourceRange();
return;
}
}
}
else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
Self.Diag(SrcExpr.get()->getLocStart(),
diag::err_arc_convesion_of_weak_unavailable)
<< 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
}
DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
Kind = Self.PrepareScalarCast(SrcExpr, DestType);
if (SrcExpr.isInvalid())
return;
if (Kind == CK_BitCast)
checkCastAlign();
}
ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
TypeSourceInfo *CastTypeInfo,
SourceLocation RPLoc,
Expr *CastExpr) {
CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
if (getLangOpts().CPlusPlus) {
Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
isa<InitListExpr>(CastExpr));
} else {
Op.CheckCStyleCast();
}
if (Op.SrcExpr.isInvalid())
return ExprError();
return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
- Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
+ Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
&Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
}
ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
SourceLocation LPLoc,
Expr *CastExpr,
SourceLocation RPLoc) {
assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
if (Op.SrcExpr.isInvalid())
return ExprError();
if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, CastTypeInfo, Op.Kind,
- Op.SrcExpr.take(), &Op.BasePath, LPLoc, RPLoc));
+ Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
}
Index: cfe/trunk/lib/Sema/SemaOverload.cpp
===================================================================
--- cfe/trunk/lib/Sema/SemaOverload.cpp (revision 209799)
+++ cfe/trunk/lib/Sema/SemaOverload.cpp (revision 209800)
@@ -1,12288 +1,12288 @@
//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides Sema routines for C++ overloading.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/Overload.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/Template.h"
#include "clang/Sema/TemplateDeduction.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include <algorithm>
#include <cstdlib>
namespace clang {
using namespace sema;
/// A convenience routine for creating a decayed reference to a function.
static ExprResult
CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
bool HadMultipleCandidates,
SourceLocation Loc = SourceLocation(),
const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
return ExprError();
// If FoundDecl is different from Fn (such as if one is a template
// and the other a specialization), make sure DiagnoseUseOfDecl is
// called on both.
// FIXME: This would be more comprehensively addressed by modifying
// DiagnoseUseOfDecl to accept both the FoundDecl and the decl
// being used.
if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
return ExprError();
DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
VK_LValue, Loc, LocInfo);
if (HadMultipleCandidates)
DRE->setHadMultipleCandidates(true);
S.MarkDeclRefReferenced(DRE);
ExprResult E = S.Owned(DRE);
- E = S.DefaultFunctionArrayConversion(E.take());
+ E = S.DefaultFunctionArrayConversion(E.get());
if (E.isInvalid())
return ExprError();
return E;
}
static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
bool InOverloadResolution,
StandardConversionSequence &SCS,
bool CStyle,
bool AllowObjCWritebackConversion);
static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
QualType &ToType,
bool InOverloadResolution,
StandardConversionSequence &SCS,
bool CStyle);
static OverloadingResult
IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
UserDefinedConversionSequence& User,
OverloadCandidateSet& Conversions,
bool AllowExplicit,
bool AllowObjCConversionOnExplicit);
static ImplicitConversionSequence::CompareKind
CompareStandardConversionSequences(Sema &S,
const StandardConversionSequence& SCS1,
const StandardConversionSequence& SCS2);
static ImplicitConversionSequence::CompareKind
CompareQualificationConversions(Sema &S,
const StandardConversionSequence& SCS1,
const StandardConversionSequence& SCS2);
static ImplicitConversionSequence::CompareKind
CompareDerivedToBaseConversions(Sema &S,
const StandardConversionSequence& SCS1,
const StandardConversionSequence& SCS2);
/// GetConversionCategory - Retrieve the implicit conversion
/// category corresponding to the given implicit conversion kind.
ImplicitConversionCategory
GetConversionCategory(ImplicitConversionKind Kind) {
static const ImplicitConversionCategory
Category[(int)ICK_Num_Conversion_Kinds] = {
ICC_Identity,
ICC_Lvalue_Transformation,
ICC_Lvalue_Transformation,
ICC_Lvalue_Transformation,
ICC_Identity,
ICC_Qualification_Adjustment,
ICC_Promotion,
ICC_Promotion,
ICC_Promotion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion,
ICC_Conversion
};
return Category[(int)Kind];
}
/// GetConversionRank - Retrieve the implicit conversion rank
/// corresponding to the given implicit conversion kind.
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
static const ImplicitConversionRank
Rank[(int)ICK_Num_Conversion_Kinds] = {
ICR_Exact_Match,
ICR_Exact_Match,
ICR_Exact_Match,
ICR_Exact_Match,
ICR_Exact_Match,
ICR_Exact_Match,
ICR_Promotion,
ICR_Promotion,
ICR_Promotion,
ICR_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Complex_Real_Conversion,
ICR_Conversion,
ICR_Conversion,
ICR_Writeback_Conversion
};
return Rank[(int)Kind];
}
/// GetImplicitConversionName - Return the name of this kind of
/// implicit conversion.
const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
"No conversion",
"Lvalue-to-rvalue",
"Array-to-pointer",
"Function-to-pointer",
"Noreturn adjustment",
"Qualification",
"Integral promotion",
"Floating point promotion",
"Complex promotion",
"Integral conversion",
"Floating conversion",
"Complex conversion",
"Floating-integral conversion",
"Pointer conversion",
"Pointer-to-member conversion",
"Boolean conversion",
"Compatible-types conversion",
"Derived-to-base conversion",
"Vector conversion",
"Vector splat",
"Complex-real conversion",
"Block Pointer conversion",
"Transparent Union Conversion"
"Writeback conversion"
};
return Name[Kind];
}
/// StandardConversionSequence - Set the standard conversion
/// sequence to the identity conversion.
void StandardConversionSequence::setAsIdentityConversion() {
First = ICK_Identity;
Second = ICK_Identity;
Third = ICK_Identity;
DeprecatedStringLiteralToCharPtr = false;
QualificationIncludesObjCLifetime = false;
ReferenceBinding = false;
DirectBinding = false;
IsLvalueReference = true;
BindsToFunctionLvalue = false;
BindsToRvalue = false;
BindsImplicitObjectArgumentWithoutRefQualifier = false;
ObjCLifetimeConversionBinding = false;
CopyConstructor = nullptr;
}
/// getRank - Retrieve the rank of this standard conversion sequence
/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
/// implicit conversions.
ImplicitConversionRank StandardConversionSequence::getRank() const {
ImplicitConversionRank Rank = ICR_Exact_Match;
if (GetConversionRank(First) > Rank)
Rank = GetConversionRank(First);
if (GetConversionRank(Second) > Rank)
Rank = GetConversionRank(Second);
if (GetConversionRank(Third) > Rank)
Rank = GetConversionRank(Third);
return Rank;
}
/// isPointerConversionToBool - Determines whether this conversion is
/// a conversion of a pointer or pointer-to-member to bool. This is
/// used as part of the ranking of standard conversion sequences
/// (C++ 13.3.3.2p4).
bool StandardConversionSequence::isPointerConversionToBool() const {
// Note that FromType has not necessarily been transformed by the
// array-to-pointer or function-to-pointer implicit conversions, so
// check for their presence as well as checking whether FromType is
// a pointer.
if (getToType(1)->isBooleanType() &&
(getFromType()->isPointerType() ||
getFromType()->isObjCObjectPointerType() ||
getFromType()->isBlockPointerType() ||
getFromType()->isNullPtrType() ||
First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
return true;
return false;
}
/// isPointerConversionToVoidPointer - Determines whether this
/// conversion is a conversion of a pointer to a void pointer. This is
/// used as part of the ranking of standard conversion sequences (C++
/// 13.3.3.2p4).
bool
StandardConversionSequence::
isPointerConversionToVoidPointer(ASTContext& Context) const {
QualType FromType = getFromType();
QualType ToType = getToType(1);
// Note that FromType has not necessarily been transformed by the
// array-to-pointer implicit conversion, so check for its presence
// and redo the conversion to get a pointer.
if (First == ICK_Array_To_Pointer)
FromType = Context.getArrayDecayedType(FromType);
if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
return ToPtrType->getPointeeType()->isVoidType();
return false;
}
/// Skip any implicit casts which could be either part of a narrowing conversion
/// or after one in an implicit conversion.
static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
switch (ICE->getCastKind()) {
case CK_NoOp:
case CK_IntegralCast:
case CK_IntegralToBoolean:
case CK_IntegralToFloating:
case CK_FloatingToIntegral:
case CK_FloatingToBoolean:
case CK_FloatingCast:
Converted = ICE->getSubExpr();
continue;
default:
return Converted;
}
}
return Converted;
}
/// Check if this standard conversion sequence represents a narrowing
/// conversion, according to C++11 [dcl.init.list]p7.
///
/// \param Ctx The AST context.
/// \param Converted The result of applying this standard conversion sequence.
/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
/// value of the expression prior to the narrowing conversion.
/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
/// type of the expression prior to the narrowing conversion.
NarrowingKind
StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
const Expr *Converted,
APValue &ConstantValue,
QualType &ConstantType) const {
assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
// C++11 [dcl.init.list]p7:
// A narrowing conversion is an implicit conversion ...
QualType FromType = getToType(0);
QualType ToType = getToType(1);
switch (Second) {
// -- from a floating-point type to an integer type, or
//
// -- from an integer type or unscoped enumeration type to a floating-point
// type, except where the source is a constant expression and the actual
// value after conversion will fit into the target type and will produce
// the original value when converted back to the original type, or
case ICK_Floating_Integral:
if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
return NK_Type_Narrowing;
} else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
llvm::APSInt IntConstantValue;
const Expr *Initializer = IgnoreNarrowingConversion(Converted);
if (Initializer &&
Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
// Convert the integer to the floating type.
llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
llvm::APFloat::rmNearestTiesToEven);
// And back.
llvm::APSInt ConvertedValue = IntConstantValue;
bool ignored;
Result.convertToInteger(ConvertedValue,
llvm::APFloat::rmTowardZero, &ignored);
// If the resulting value is different, this was a narrowing conversion.
if (IntConstantValue != ConvertedValue) {
ConstantValue = APValue(IntConstantValue);
ConstantType = Initializer->getType();
return NK_Constant_Narrowing;
}
} else {
// Variables are always narrowings.
return NK_Variable_Narrowing;
}
}
return NK_Not_Narrowing;
// -- from long double to double or float, or from double to float, except
// where the source is a constant expression and the actual value after
// conversion is within the range of values that can be represented (even
// if it cannot be represented exactly), or
case ICK_Floating_Conversion:
if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
// FromType is larger than ToType.
const Expr *Initializer = IgnoreNarrowingConversion(Converted);
if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
// Constant!
assert(ConstantValue.isFloat());
llvm::APFloat FloatVal = ConstantValue.getFloat();
// Convert the source value into the target type.
bool ignored;
llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
Ctx.getFloatTypeSemantics(ToType),
llvm::APFloat::rmNearestTiesToEven, &ignored);
// If there was no overflow, the source value is within the range of
// values that can be represented.
if (ConvertStatus & llvm::APFloat::opOverflow) {
ConstantType = Initializer->getType();
return NK_Constant_Narrowing;
}
} else {
return NK_Variable_Narrowing;
}
}
return NK_Not_Narrowing;
// -- from an integer type or unscoped enumeration type to an integer type
// that cannot represent all the values of the original type, except where
// the source is a constant expression and the actual value after
// conversion will fit into the target type and will produce the original
// value when converted back to the original type.
case ICK_Boolean_Conversion: // Bools are integers too.
if (!FromType->isIntegralOrUnscopedEnumerationType()) {
// Boolean conversions can be from pointers and pointers to members
// [conv.bool], and those aren't considered narrowing conversions.
return NK_Not_Narrowing;
} // Otherwise, fall through to the integral case.
case ICK_Integral_Conversion: {
assert(FromType->isIntegralOrUnscopedEnumerationType());
assert(ToType->isIntegralOrUnscopedEnumerationType());
const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
const unsigned FromWidth = Ctx.getIntWidth(FromType);
const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
const unsigned ToWidth = Ctx.getIntWidth(ToType);
if (FromWidth > ToWidth ||
(FromWidth == ToWidth && FromSigned != ToSigned) ||
(FromSigned && !ToSigned)) {
// Not all values of FromType can be represented in ToType.
llvm::APSInt InitializerValue;
const Expr *Initializer = IgnoreNarrowingConversion(Converted);
if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
// Such conversions on variables are always narrowing.
return NK_Variable_Narrowing;
}
bool Narrowing = false;
if (FromWidth < ToWidth) {
// Negative -> unsigned is narrowing. Otherwise, more bits is never
// narrowing.
if (InitializerValue.isSigned() && InitializerValue.isNegative())
Narrowing = true;
} else {
// Add a bit to the InitializerValue so we don't have to worry about
// signed vs. unsigned comparisons.
InitializerValue = InitializerValue.extend(
InitializerValue.getBitWidth() + 1);
// Convert the initializer to and from the target width and signed-ness.
llvm::APSInt ConvertedValue = InitializerValue;
ConvertedValue = ConvertedValue.trunc(ToWidth);
ConvertedValue.setIsSigned(ToSigned);
ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
ConvertedValue.setIsSigned(InitializerValue.isSigned());
// If the result is different, this was a narrowing conversion.
if (ConvertedValue != InitializerValue)
Narrowing = true;
}
if (Narrowing) {
ConstantType = Initializer->getType();
ConstantValue = APValue(InitializerValue);
return NK_Constant_Narrowing;
}
}
return NK_Not_Narrowing;
}
default:
// Other kinds of conversions are not narrowings.
return NK_Not_Narrowing;
}
}
/// dump - Print this standard conversion sequence to standard
/// error. Useful for debugging overloading issues.
void StandardConversionSequence::dump() const {
raw_ostream &OS = llvm::errs();
bool PrintedSomething = false;
if (First != ICK_Identity) {
OS << GetImplicitConversionName(First);
PrintedSomething = true;
}
if (Second != ICK_Identity) {
if (PrintedSomething) {
OS << " -> ";
}
OS << GetImplicitConversionName(Second);
if (CopyConstructor) {
OS << " (by copy constructor)";
} else if (DirectBinding) {
OS << " (direct reference binding)";
} else if (ReferenceBinding) {
OS << " (reference binding)";
}
PrintedSomething = true;
}
if (Third != ICK_Identity) {
if (PrintedSomething) {
OS << " -> ";
}
OS << GetImplicitConversionName(Third);
PrintedSomething = true;
}
if (!PrintedSomething) {
OS << "No conversions required";
}
}
/// dump - Print this user-defined conversion sequence to standard
/// error. Useful for debugging overloading issues.
void UserDefinedConversionSequence::dump() const {
raw_ostream &OS = llvm::errs();
if (Before.First || Before.Second || Before.Third) {
Before.dump();
OS << " -> ";
}
if (ConversionFunction)
OS << '\'' << *ConversionFunction << '\'';
else
OS << "aggregate initialization";
if (After.First || After.Second || After.Third) {
OS << " -> ";
After.dump();
}
}
/// dump - Print this implicit conversion sequence to standard
/// error. Useful for debugging overloading issues.
void ImplicitConversionSequence::dump() const {
raw_ostream &OS = llvm::errs();
if (isStdInitializerListElement())
OS << "Worst std::initializer_list element conversion: ";
switch (ConversionKind) {
case StandardConversion:
OS << "Standard conversion: ";
Standard.dump();
break;
case UserDefinedConversion:
OS << "User-defined conversion: ";
UserDefined.dump();
break;
case EllipsisConversion:
OS << "Ellipsis conversion";
break;
case AmbiguousConversion:
OS << "Ambiguous conversion";
break;
case BadConversion:
OS << "Bad conversion";
break;
}
OS << "\n";
}
void AmbiguousConversionSequence::construct() {
new (&conversions()) ConversionSet();
}
void AmbiguousConversionSequence::destruct() {
conversions().~ConversionSet();
}
void
AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
FromTypePtr = O.FromTypePtr;
ToTypePtr = O.ToTypePtr;
new (&conversions()) ConversionSet(O.conversions());
}
namespace {
// Structure used by DeductionFailureInfo to store
// template argument information.
struct DFIArguments {
TemplateArgument FirstArg;
TemplateArgument SecondArg;
};
// Structure used by DeductionFailureInfo to store
// template parameter and template argument information.
struct DFIParamWithArguments : DFIArguments {
TemplateParameter Param;
};
}
/// \brief Convert from Sema's representation of template deduction information
/// to the form used in overload-candidate information.
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
Sema::TemplateDeductionResult TDK,
TemplateDeductionInfo &Info) {
DeductionFailureInfo Result;
Result.Result = static_cast<unsigned>(TDK);
Result.HasDiagnostic = false;
Result.Data = nullptr;
switch (TDK) {
case Sema::TDK_Success:
case Sema::TDK_Invalid:
case Sema::TDK_InstantiationDepth:
case Sema::TDK_TooManyArguments:
case Sema::TDK_TooFewArguments:
break;
case Sema::TDK_Incomplete:
case Sema::TDK_InvalidExplicitArguments:
Result.Data = Info.Param.getOpaqueValue();
break;
case Sema::TDK_NonDeducedMismatch: {
// FIXME: Should allocate from normal heap so that we can free this later.
DFIArguments *Saved = new (Context) DFIArguments;
Saved->FirstArg = Info.FirstArg;
Saved->SecondArg = Info.SecondArg;
Result.Data = Saved;
break;
}
case Sema::TDK_Inconsistent:
case Sema::TDK_Underqualified: {
// FIXME: Should allocate from normal heap so that we can free this later.
DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Saved->Param = Info.Param;
Saved->FirstArg = Info.FirstArg;
Saved->SecondArg = Info.SecondArg;
Result.Data = Saved;
break;
}
case Sema::TDK_SubstitutionFailure:
Result.Data = Info.take();
if (Info.hasSFINAEDiagnostic()) {
PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
SourceLocation(), PartialDiagnostic::NullDiagnostic());
Info.takeSFINAEDiagnostic(*Diag);
Result.HasDiagnostic = true;
}
break;
case Sema::TDK_FailedOverloadResolution:
Result.Data = Info.Expression;
break;
case Sema::TDK_MiscellaneousDeductionFailure:
break;
}
return Result;
}
void DeductionFailureInfo::Destroy() {
switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
case Sema::TDK_Success:
case Sema::TDK_Invalid:
case Sema::TDK_InstantiationDepth:
case Sema::TDK_Incomplete:
case Sema::TDK_TooManyArguments:
case Sema::TDK_TooFewArguments:
case Sema::TDK_InvalidExplicitArguments:
case Sema::TDK_FailedOverloadResolution:
break;
case Sema::TDK_Inconsistent:
case Sema::TDK_Underqualified:
case Sema::TDK_NonDeducedMismatch:
// FIXME: Destroy the data?
Data = nullptr;
break;
case Sema::TDK_SubstitutionFailure:
// FIXME: Destroy the template argument list?
Data = nullptr;
if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
Diag->~PartialDiagnosticAt();
HasDiagnostic = false;
}
break;
// Unhandled
case Sema::TDK_MiscellaneousDeductionFailure:
break;
}
}
PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
if (HasDiagnostic)
return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
return nullptr;
}
TemplateParameter DeductionFailureInfo::getTemplateParameter() {
switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
case Sema::TDK_Success:
case Sema::TDK_Invalid:
case Sema::TDK_InstantiationDepth:
case Sema::TDK_TooManyArguments:
case Sema::TDK_TooFewArguments:
case Sema::TDK_SubstitutionFailure:
case Sema::TDK_NonDeducedMismatch:
case Sema::TDK_FailedOverloadResolution:
return TemplateParameter();
case Sema::TDK_Incomplete:
case Sema::TDK_InvalidExplicitArguments:
return TemplateParameter::getFromOpaqueValue(Data);
case Sema::TDK_Inconsistent:
case Sema::TDK_Underqualified:
return static_cast<DFIParamWithArguments*>(Data)->Param;
// Unhandled
case Sema::TDK_MiscellaneousDeductionFailure:
break;
}
return TemplateParameter();
}
TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
case Sema::TDK_Success:
case Sema::TDK_Invalid:
case Sema::TDK_InstantiationDepth:
case Sema::TDK_TooManyArguments:
case Sema::TDK_TooFewArguments:
case Sema::TDK_Incomplete:
case Sema::TDK_InvalidExplicitArguments:
case Sema::TDK_Inconsistent:
case Sema::TDK_Underqualified:
case Sema::TDK_NonDeducedMismatch:
case Sema::TDK_FailedOverloadResolution:
return nullptr;
case Sema::TDK_SubstitutionFailure:
return static_cast<TemplateArgumentList*>(Data);
// Unhandled
case Sema::TDK_MiscellaneousDeductionFailure:
break;
}
return nullptr;
}
const TemplateArgument *DeductionFailureInfo::getFirstArg() {
switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
case Sema::TDK_Success:
case Sema::TDK_Invalid:
case Sema::TDK_InstantiationDepth:
case Sema::TDK_Incomplete:
case Sema::TDK_TooManyArguments:
case Sema::TDK_TooFewArguments:
case Sema::TDK_InvalidExplicitArguments:
case Sema::TDK_SubstitutionFailure:
case Sema::TDK_FailedOverloadResolution:
return nullptr;
case Sema::TDK_Inconsistent:
case Sema::TDK_Underqualified:
case Sema::TDK_NonDeducedMismatch:
return &static_cast<DFIArguments*>(Data)->FirstArg;
// Unhandled
case Sema::TDK_MiscellaneousDeductionFailure:
break;
}
return nullptr;
}
const TemplateArgument *DeductionFailureInfo::getSecondArg() {
switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
case Sema::TDK_Success:
case Sema::TDK_Invalid:
case Sema::TDK_InstantiationDepth:
case Sema::TDK_Incomplete:
case Sema::TDK_TooManyArguments:
case Sema::TDK_TooFewArguments:
case Sema::TDK_InvalidExplicitArguments:
case Sema::TDK_SubstitutionFailure:
case Sema::TDK_FailedOverloadResolution:
return nullptr;
case Sema::TDK_Inconsistent:
case Sema::TDK_Underqualified:
case Sema::TDK_NonDeducedMismatch:
return &static_cast<DFIArguments*>(Data)->SecondArg;
// Unhandled
case Sema::TDK_MiscellaneousDeductionFailure:
break;
}
return nullptr;
}
Expr *DeductionFailureInfo::getExpr() {
if (static_cast<Sema::TemplateDeductionResult>(Result) ==
Sema::TDK_FailedOverloadResolution)
return static_cast<Expr*>(Data);
return nullptr;
}
void OverloadCandidateSet::destroyCandidates() {
for (iterator i = begin(), e = end(); i != e; ++i) {
for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
i->Conversions[ii].~ImplicitConversionSequence();
if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
i->DeductionFailure.Destroy();
}
}
void OverloadCandidateSet::clear() {
destroyCandidates();
NumInlineSequences = 0;
Candidates.clear();
Functions.clear();
}
namespace {
class UnbridgedCastsSet {
struct Entry {
Expr **Addr;
Expr *Saved;
};
SmallVector<Entry, 2> Entries;
public:
void save(Sema &S, Expr *&E) {
assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
Entry entry = { &E, E };
Entries.push_back(entry);
E = S.stripARCUnbridgedCast(E);
}
void restore() {
for (SmallVectorImpl<Entry>::iterator
i = Entries.begin(), e = Entries.end(); i != e; ++i)
*i->Addr = i->Saved;
}
};
}
/// checkPlaceholderForOverload - Do any interesting placeholder-like
/// preprocessing on the given expression.
///
/// \param unbridgedCasts a collection to which to add unbridged casts;
/// without this, they will be immediately diagnosed as errors
///
/// Return true on unrecoverable error.
static bool
checkPlaceholderForOverload(Sema &S, Expr *&E,
UnbridgedCastsSet *unbridgedCasts = nullptr) {
if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
// We can't handle overloaded expressions here because overload
// resolution might reasonably tweak them.
if (placeholder->getKind() == BuiltinType::Overload) return false;
// If the context potentially accepts unbridged ARC casts, strip
// the unbridged cast and add it to the collection for later restoration.
if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
unbridgedCasts) {
unbridgedCasts->save(S, E);
return false;
}
// Go ahead and check everything else.
ExprResult result = S.CheckPlaceholderExpr(E);
if (result.isInvalid())
return true;
- E = result.take();
+ E = result.get();
return false;
}
// Nothing to do.
return false;
}
/// checkArgPlaceholdersForOverload - Check a set of call operands for
/// placeholders.
static bool checkArgPlaceholdersForOverload(Sema &S,
MultiExprArg Args,
UnbridgedCastsSet &unbridged) {
for (unsigned i = 0, e = Args.size(); i != e; ++i)
if (checkPlaceholderForOverload(S, Args[i], &unbridged))
return true;
return false;
}
// IsOverload - Determine whether the given New declaration is an
// overload of the declarations in Old. This routine returns false if
// New and Old cannot be overloaded, e.g., if New has the same
// signature as some function in Old (C++ 1.3.10) or if the Old
// declarations aren't functions (or function templates) at all. When
// it does return false, MatchedDecl will point to the decl that New
// cannot be overloaded with. This decl may be a UsingShadowDecl on
// top of the underlying declaration.
//
// Example: Given the following input:
//
// void f(int, float); // #1
// void f(int, int); // #2
// int f(int, int); // #3
//
// When we process #1, there is no previous declaration of "f",
// so IsOverload will not be used.
//
// When we process #2, Old contains only the FunctionDecl for #1. By
// comparing the parameter types, we see that #1 and #2 are overloaded
// (since they have different signatures), so this routine returns
// false; MatchedDecl is unchanged.
//
// When we process #3, Old is an overload set containing #1 and #2. We
// compare the signatures of #3 to #1 (they're overloaded, so we do
// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
// identical (return types of functions are not part of the
// signature), IsOverload returns false and MatchedDecl will be set to
// point to the FunctionDecl for #2.
//
// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
// into a class by a using declaration. The rules for whether to hide
// shadow declarations ignore some properties which otherwise figure
// into a function template's signature.
Sema::OverloadKind
Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
NamedDecl *&Match, bool NewIsUsingDecl) {
for (LookupResult::iterator I = Old.begin(), E = Old.end();
I != E; ++I) {
NamedDecl *OldD = *I;
bool OldIsUsingDecl = false;
if (isa<UsingShadowDecl>(OldD)) {
OldIsUsingDecl = true;
// We can always introduce two using declarations into the same
// context, even if they have identical signatures.
if (NewIsUsingDecl) continue;
OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
}
// If either declaration was introduced by a using declaration,
// we'll need to use slightly different rules for matching.
// Essentially, these rules are the normal rules, except that
// function templates hide function templates with different
// return types or template parameter lists.
bool UseMemberUsingDeclRules =
(OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
!New->getFriendObjectKind();
if (FunctionDecl *OldF = OldD->getAsFunction()) {
if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
if (UseMemberUsingDeclRules && OldIsUsingDecl) {
HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
continue;
}
if (!isa<FunctionTemplateDecl>(OldD) &&
!shouldLinkPossiblyHiddenDecl(*I, New))
continue;
Match = *I;
return Ovl_Match;
}
} else if (isa<UsingDecl>(OldD)) {
// We can overload with these, which can show up when doing
// redeclaration checks for UsingDecls.
assert(Old.getLookupKind() == LookupUsingDeclName);
} else if (isa<TagDecl>(OldD)) {
// We can always overload with tags by hiding them.
} else if (isa<UnresolvedUsingValueDecl>(OldD)) {
// Optimistically assume that an unresolved using decl will
// overload; if it doesn't, we'll have to diagnose during
// template instantiation.
} else {
// (C++ 13p1):
// Only function declarations can be overloaded; object and type
// declarations cannot be overloaded.
Match = *I;
return Ovl_NonFunction;
}
}
return Ovl_Overload;
}
bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
bool UseUsingDeclRules) {
// C++ [basic.start.main]p2: This function shall not be overloaded.
if (New->isMain())
return false;
// MSVCRT user defined entry points cannot be overloaded.
if (New->isMSVCRTEntryPoint())
return false;
FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
// C++ [temp.fct]p2:
// A function template can be overloaded with other function templates
// and with normal (non-template) functions.
if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
return true;
// Is the function New an overload of the function Old?
QualType OldQType = Context.getCanonicalType(Old->getType());
QualType NewQType = Context.getCanonicalType(New->getType());
// Compare the signatures (C++ 1.3.10) of the two functions to
// determine whether they are overloads. If we find any mismatch
// in the signature, they are overloads.
// If either of these functions is a K&R-style function (no
// prototype), then we consider them to have matching signatures.
if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
isa<FunctionNoProtoType>(NewQType.getTypePtr()))
return false;
const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
// The signature of a function includes the types of its
// parameters (C++ 1.3.10), which includes the presence or absence
// of the ellipsis; see C++ DR 357).
if (OldQType != NewQType &&
(OldType->getNumParams() != NewType->getNumParams() ||
OldType->isVariadic() != NewType->isVariadic() ||
!FunctionParamTypesAreEqual(OldType, NewType)))
return true;
// C++ [temp.over.link]p4:
// The signature of a function template consists of its function
// signature, its return type and its template parameter list. The names
// of the template parameters are significant only for establishing the
// relationship between the template parameters and the rest of the
// signature.
//
// We check the return type and template parameter lists for function
// templates first; the remaining checks follow.
//
// However, we don't consider either of these when deciding whether
// a member introduced by a shadow declaration is hidden.
if (!UseUsingDeclRules && NewTemplate &&
(!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
OldTemplate->getTemplateParameters(),
false, TPL_TemplateMatch) ||
OldType->getReturnType() != NewType->getReturnType()))
return true;
// If the function is a class member, its signature includes the
// cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
//
// As part of this, also check whether one of the member functions
// is static, in which case they are not overloads (C++
// 13.1p2). While not part of the definition of the signature,
// this check is important to determine whether these functions
// can be overloaded.
CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
if (OldMethod && NewMethod &&
!OldMethod->isStatic() && !NewMethod->isStatic()) {
if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
if (!UseUsingDeclRules &&
(OldMethod->getRefQualifier() == RQ_None ||
NewMethod->getRefQualifier() == RQ_None)) {
// C++0x [over.load]p2:
// - Member function declarations with the same name and the same
// parameter-type-list as well as member function template
// declarations with the same name, the same parameter-type-list, and
// the same template parameter lists cannot be overloaded if any of
// them, but not all, have a ref-qualifier (8.3.5).
Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
<< NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Diag(OldMethod->getLocation(), diag::note_previous_declaration);
}
return true;
}
// We may not have applied the implicit const for a constexpr member
// function yet (because we haven't yet resolved whether this is a static
// or non-static member function). Add it now, on the assumption that this
// is a redeclaration of OldMethod.
unsigned OldQuals = OldMethod->getTypeQualifiers();
unsigned NewQuals = NewMethod->getTypeQualifiers();
if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
!isa<CXXConstructorDecl>(NewMethod))
NewQuals |= Qualifiers::Const;
// We do not allow overloading based off of '__restrict'.
OldQuals &= ~Qualifiers::Restrict;
NewQuals &= ~Qualifiers::Restrict;
if (OldQuals != NewQuals)
return true;
}
// enable_if attributes are an order-sensitive part of the signature.
for (specific_attr_iterator<EnableIfAttr>
NewI = New->specific_attr_begin<EnableIfAttr>(),
NewE = New->specific_attr_end<EnableIfAttr>(),
OldI = Old->specific_attr_begin<EnableIfAttr>(),
OldE = Old->specific_attr_end<EnableIfAttr>();
NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
if (NewI == NewE || OldI == OldE)
return true;
llvm::FoldingSetNodeID NewID, OldID;
NewI->getCond()->Profile(NewID, Context, true);
OldI->getCond()->Profile(OldID, Context, true);
if (NewID != OldID)
return true;
}
// The signatures match; this is not an overload.
return false;
}
/// \brief Checks availability of the function depending on the current
/// function context. Inside an unavailable function, unavailability is ignored.
///
/// \returns true if \arg FD is unavailable and current context is inside
/// an available function, false otherwise.
bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
}
/// \brief Tries a user-defined conversion from From to ToType.
///
/// Produces an implicit conversion sequence for when a standard conversion
/// is not an option. See TryImplicitConversion for more information.
static ImplicitConversionSequence
TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion,
bool AllowObjCConversionOnExplicit) {
ImplicitConversionSequence ICS;
if (SuppressUserConversions) {
// We're not in the case above, so there is no conversion that
// we can perform.
ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
return ICS;
}
// Attempt user-defined conversion.
OverloadCandidateSet Conversions(From->getExprLoc(),
OverloadCandidateSet::CSK_Normal);
OverloadingResult UserDefResult
= IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
AllowExplicit, AllowObjCConversionOnExplicit);
if (UserDefResult == OR_Success) {
ICS.setUserDefined();
ICS.UserDefined.Before.setAsIdentityConversion();
// C++ [over.ics.user]p4:
// A conversion of an expression of class type to the same class
// type is given Exact Match rank, and a conversion of an
// expression of class type to a base class of that type is
// given Conversion rank, in spite of the fact that a copy
// constructor (i.e., a user-defined conversion function) is
// called for those cases.
if (CXXConstructorDecl *Constructor
= dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
QualType FromCanon
= S.Context.getCanonicalType(From->getType().getUnqualifiedType());
QualType ToCanon
= S.Context.getCanonicalType(ToType).getUnqualifiedType();
if (Constructor->isCopyConstructor() &&
(FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
// Turn this into a "standard" conversion sequence, so that it
// gets ranked with standard conversion sequences.
ICS.setStandard();
ICS.Standard.setAsIdentityConversion();
ICS.Standard.setFromType(From->getType());
ICS.Standard.setAllToTypes(ToType);
ICS.Standard.CopyConstructor = Constructor;
if (ToCanon != FromCanon)
ICS.Standard.Second = ICK_Derived_To_Base;
}
}
// C++ [over.best.ics]p4:
// However, when considering the argument of a user-defined
// conversion function that is a candidate by 13.3.1.3 when
// invoked for the copying of the temporary in the second step
// of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
// 13.3.1.6 in all cases, only standard conversion sequences and
// ellipsis conversion sequences are allowed.
if (SuppressUserConversions && ICS.isUserDefined()) {
ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
}
} else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
ICS.setAmbiguous();
ICS.Ambiguous.setFromType(From->getType());
ICS.Ambiguous.setToType(ToType);
for (OverloadCandidateSet::iterator Cand = Conversions.begin();
Cand != Conversions.end(); ++Cand)
if (Cand->Viable)
ICS.Ambiguous.addConversion(Cand->Function);
} else {
ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
}
return ICS;
}
/// TryImplicitConversion - Attempt to perform an implicit conversion
/// from the given expression (Expr) to the given type (ToType). This
/// function returns an implicit conversion sequence that can be used
/// to perform the initialization. Given
///
/// void f(float f);
/// void g(int i) { f(i); }
///
/// this routine would produce an implicit conversion sequence to
/// describe the initialization of f from i, which will be a standard
/// conversion sequence containing an lvalue-to-rvalue conversion (C++
/// 4.1) followed by a floating-integral conversion (C++ 4.9).
//
/// Note that this routine only determines how the conversion can be
/// performed; it does not actually perform the conversion. As such,
/// it will not produce any diagnostics if no conversion is available,
/// but will instead return an implicit conversion sequence of kind
/// "BadConversion".
///
/// If @p SuppressUserConversions, then user-defined conversions are
/// not permitted.
/// If @p AllowExplicit, then explicit user-defined conversions are
/// permitted.
///
/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
/// writeback conversion, which allows __autoreleasing id* parameters to
/// be initialized with __strong id* or __weak id* arguments.
static ImplicitConversionSequence
TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion,
bool AllowObjCConversionOnExplicit) {
ImplicitConversionSequence ICS;
if (IsStandardConversion(S, From, ToType, InOverloadResolution,
ICS.Standard, CStyle, AllowObjCWritebackConversion)){
ICS.setStandard();
return ICS;
}
if (!S.getLangOpts().CPlusPlus) {
ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
return ICS;
}
// C++ [over.ics.user]p4:
// A conversion of an expression of class type to the same class
// type is given Exact Match rank, and a conversion of an
// expression of class type to a base class of that type is
// given Conversion rank, in spite of the fact that a copy/move
// constructor (i.e., a user-defined conversion function) is
// called for those cases.
QualType FromType = From->getType();
if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
(S.Context.hasSameUnqualifiedType(FromType, ToType) ||
S.IsDerivedFrom(FromType, ToType))) {
ICS.setStandard();
ICS.Standard.setAsIdentityConversion();
ICS.Standard.setFromType(FromType);
ICS.Standard.setAllToTypes(ToType);
// We don't actually check at this point whether there is a valid
// copy/move constructor, since overloading just assumes that it
// exists. When we actually perform initialization, we'll find the
// appropriate constructor to copy the returned object, if needed.
ICS.Standard.CopyConstructor = nullptr;
// Determine whether this is considered a derived-to-base conversion.
if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
ICS.Standard.Second = ICK_Derived_To_Base;
return ICS;
}
return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
AllowExplicit, InOverloadResolution, CStyle,
AllowObjCWritebackConversion,
AllowObjCConversionOnExplicit);
}
ImplicitConversionSequence
Sema::TryImplicitConversion(Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion) {
return clang::TryImplicitConversion(*this, From, ToType,
SuppressUserConversions, AllowExplicit,
InOverloadResolution, CStyle,
AllowObjCWritebackConversion,
/*AllowObjCConversionOnExplicit=*/false);
}
/// PerformImplicitConversion - Perform an implicit conversion of the
/// expression From to the type ToType. Returns the
/// converted expression. Flavor is the kind of conversion we're
/// performing, used in the error message. If @p AllowExplicit,
/// explicit user-defined conversions are permitted.
ExprResult
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action, bool AllowExplicit) {
ImplicitConversionSequence ICS;
return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
}
ExprResult
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action, bool AllowExplicit,
ImplicitConversionSequence& ICS) {
if (checkPlaceholderForOverload(*this, From))
return ExprError();
// Objective-C ARC: Determine whether we will allow the writeback conversion.
bool AllowObjCWritebackConversion
= getLangOpts().ObjCAutoRefCount &&
(Action == AA_Passing || Action == AA_Sending);
if (getLangOpts().ObjC1)
CheckObjCBridgeRelatedConversions(From->getLocStart(),
ToType, From->getType(), From);
ICS = clang::TryImplicitConversion(*this, From, ToType,
/*SuppressUserConversions=*/false,
AllowExplicit,
/*InOverloadResolution=*/false,
/*CStyle=*/false,
AllowObjCWritebackConversion,
/*AllowObjCConversionOnExplicit=*/false);
return PerformImplicitConversion(From, ToType, ICS, Action);
}
/// \brief Determine whether the conversion from FromType to ToType is a valid
/// conversion that strips "noreturn" off the nested function type.
bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
QualType &ResultTy) {
if (Context.hasSameUnqualifiedType(FromType, ToType))
return false;
// Permit the conversion F(t __attribute__((noreturn))) -> F(t)
// where F adds one of the following at most once:
// - a pointer
// - a member pointer
// - a block pointer
CanQualType CanTo = Context.getCanonicalType(ToType);
CanQualType CanFrom = Context.getCanonicalType(FromType);
Type::TypeClass TyClass = CanTo->getTypeClass();
if (TyClass != CanFrom->getTypeClass()) return false;
if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
if (TyClass == Type::Pointer) {
CanTo = CanTo.getAs<PointerType>()->getPointeeType();
CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
} else if (TyClass == Type::BlockPointer) {
CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
} else if (TyClass == Type::MemberPointer) {
CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
} else {
return false;
}
TyClass = CanTo->getTypeClass();
if (TyClass != CanFrom->getTypeClass()) return false;
if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
return false;
}
const FunctionType *FromFn = cast<FunctionType>(CanFrom);
FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
if (!EInfo.getNoReturn()) return false;
FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
assert(QualType(FromFn, 0).isCanonical());
if (QualType(FromFn, 0) != CanTo) return false;
ResultTy = ToType;
return true;
}
/// \brief Determine whether the conversion from FromType to ToType is a valid
/// vector conversion.
///
/// \param ICK Will be set to the vector conversion kind, if this is a vector
/// conversion.
static bool IsVectorConversion(Sema &S, QualType FromType,
QualType ToType, ImplicitConversionKind &ICK) {
// We need at least one of these types to be a vector type to have a vector
// conversion.
if (!ToType->isVectorType() && !FromType->isVectorType())
return false;
// Identical types require no conversions.
if (S.Context.hasSameUnqualifiedType(FromType, ToType))
return false;
// There are no conversions between extended vector types, only identity.
if (ToType->isExtVectorType()) {
// There are no conversions between extended vector types other than the
// identity conversion.
if (FromType->isExtVectorType())
return false;