#include "TableGenBackends.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/StringMatcher.h"
#include "llvm/TableGen/TableGenBackend.h"
using namespace llvm;
namespace {
struct BuiltinTableEntries {
SmallVector<StringRef, 4> Names;
std::vector<std::pair<const Record *, unsigned>> Signatures;
};
class BuiltinNameEmitter {
public:
BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
: Records(Records), OS(OS) {}
void Emit();
private:
using BuiltinIndexListTy = SmallVector<unsigned, 11>;
RecordKeeper &Records;
raw_ostream &OS;
void ExtractEnumTypes(std::vector<Record *> &Types,
StringMap<bool> &TypesSeen, std::string &Output,
std::vector<const Record *> &List);
void EmitDeclarations();
void GetOverloads();
bool CanReuseSignature(
BuiltinIndexListTy *Candidate,
std::vector<std::pair<const Record *, unsigned>> &SignatureList);
void GroupBySignature();
void EmitExtensionTable();
void EmitTypeTable();
void EmitSignatureTable();
void EmitBuiltinTable();
void EmitStringMatcher();
void EmitQualTypeFinder();
std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>>
FctOverloadMap;
MapVector<const Record *, unsigned> TypeMap;
StringMap<unsigned> FunctionExtensionIndex;
std::vector<const Record *> TypeList;
std::vector<const Record *> GenTypeList;
MapVector<BuiltinIndexListTy *, BuiltinTableEntries> SignatureListMap;
};
class OpenCLBuiltinFileEmitterBase {
public:
OpenCLBuiltinFileEmitterBase(RecordKeeper &Records, raw_ostream &OS)
: Records(Records), OS(OS) {}
virtual ~OpenCLBuiltinFileEmitterBase() = default;
virtual void emit() = 0;
protected:
struct TypeFlags {
TypeFlags() : IsConst(false), IsVolatile(false), IsPointer(false) {}
bool IsConst : 1;
bool IsVolatile : 1;
bool IsPointer : 1;
StringRef AddrSpace;
};
std::string getTypeString(const Record *Type, TypeFlags Flags,
int VectorSize) const;
void getTypeLists(Record *Type, TypeFlags &Flags,
std::vector<Record *> &TypeList,
std::vector<int64_t> &VectorList) const;
void
expandTypesInSignature(const std::vector<Record *> &Signature,
SmallVectorImpl<SmallVector<std::string, 2>> &Types);
void emitExtensionSetup();
std::string emitExtensionGuard(const Record *Builtin);
std::string emitVersionGuard(const Record *Builtin);
StringRef
emitTypeExtensionGuards(const SmallVectorImpl<std::string> &Signature);
StringMap<StringRef> TypeExtMap;
RecordKeeper &Records;
raw_ostream &OS;
};
class OpenCLBuiltinTestEmitter : public OpenCLBuiltinFileEmitterBase {
public:
OpenCLBuiltinTestEmitter(RecordKeeper &Records, raw_ostream &OS)
: OpenCLBuiltinFileEmitterBase(Records, OS) {}
void emit() override;
};
}
void BuiltinNameEmitter::Emit() {
emitSourceFileHeader("OpenCL Builtin handling", OS);
OS << "#include \"llvm/ADT/StringRef.h\"\n";
OS << "using namespace clang;\n\n";
EmitDeclarations();
GetOverloads();
GroupBySignature();
EmitExtensionTable();
EmitTypeTable();
EmitSignatureTable();
EmitBuiltinTable();
EmitStringMatcher();
EmitQualTypeFinder();
}
void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
StringMap<bool> &TypesSeen,
std::string &Output,
std::vector<const Record *> &List) {
raw_string_ostream SS(Output);
for (const auto *T : Types) {
if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
SS << " OCLT_" + T->getValueAsString("Name") << ",\n";
List.push_back(T);
TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
}
}
SS.flush();
}
void BuiltinNameEmitter::EmitDeclarations() {
OS << "enum OpenCLTypeID {\n";
StringMap<bool> TypesSeen;
std::string GenTypeEnums;
std::string TypeEnums;
std::vector<Record *> GenTypes =
Records.getAllDerivedDefinitions("GenericType");
ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
OS << TypeEnums;
OS << GenTypeEnums;
OS << "};\n";
OS << R"(
// Image access qualifier.
enum OpenCLAccessQual : unsigned char {
OCLAQ_None,
OCLAQ_ReadOnly,
OCLAQ_WriteOnly,
OCLAQ_ReadWrite
};
// Represents a return type or argument type.
struct OpenCLTypeStruct {
// A type (e.g. float, int, ...).
const OpenCLTypeID ID;
// Vector size (if applicable; 0 for scalars and generic types).
const unsigned VectorWidth;
// 0 if the type is not a pointer.
const bool IsPointer : 1;
// 0 if the type is not const.
const bool IsConst : 1;
// 0 if the type is not volatile.
const bool IsVolatile : 1;
// Access qualifier.
const OpenCLAccessQual AccessQualifier;
// Address space of the pointer (if applicable).
const LangAS AS;
};
// One overload of an OpenCL builtin function.
struct OpenCLBuiltinStruct {
// Index of the signature in the OpenCLTypeStruct table.
const unsigned SigTableIndex;
// Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
// the SignatureTable represent the complete signature. The first type at
// index SigTableIndex is the return type.
const unsigned NumTypes;
// Function attribute __attribute__((pure))
const bool IsPure : 1;
// Function attribute __attribute__((const))
const bool IsConst : 1;
// Function attribute __attribute__((convergent))
const bool IsConv : 1;
// OpenCL extension(s) required for this overload.
const unsigned short Extension;
// OpenCL versions in which this overload is available.
const unsigned short Versions;
};
)";
}
static void VerifySignature(const std::vector<Record *> &Signature,
const Record *BuiltinRec) {
unsigned GenTypeVecSizes = 1;
unsigned GenTypeTypes = 1;
for (const auto *T : Signature) {
if (T->isSubClassOf("GenericType")) {
unsigned NVecSizes =
T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
if (GenTypeVecSizes > 1) {
PrintFatalError(BuiltinRec->getLoc(),
"number of vector sizes should be equal or 1 for all gentypes "
"in a declaration");
}
GenTypeVecSizes = NVecSizes;
}
unsigned NTypes =
T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
if (NTypes != GenTypeTypes && NTypes != 1) {
if (GenTypeTypes > 1) {
PrintFatalError(BuiltinRec->getLoc(),
"number of types should be equal or 1 for all gentypes "
"in a declaration");
}
GenTypeTypes = NTypes;
}
}
}
}
void BuiltinNameEmitter::GetOverloads() {
std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
unsigned I = 0;
for (const auto &T : Types) {
TypeMap.insert(std::make_pair(T, I++));
}
unsigned CumulativeSignIndex = 0;
std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
for (const auto *B : Builtins) {
StringRef BName = B->getValueAsString("Name");
if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
FctOverloadMap.insert(std::make_pair(
BName, std::vector<std::pair<const Record *, unsigned>>{}));
}
auto Signature = B->getValueAsListOfDefs("Signature");
auto it =
llvm::find_if(SignaturesList,
[&](const std::pair<std::vector<Record *>, unsigned> &a) {
return a.first == Signature;
});
unsigned SignIndex;
if (it == SignaturesList.end()) {
VerifySignature(Signature, B);
SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
SignIndex = CumulativeSignIndex;
CumulativeSignIndex += Signature.size();
} else {
SignIndex = it->second;
}
FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
}
}
void BuiltinNameEmitter::EmitExtensionTable() {
OS << "static const char *FunctionExtensionTable[] = {\n";
unsigned Index = 0;
std::vector<Record *> FuncExtensions =
Records.getAllDerivedDefinitions("FunctionExtension");
for (const auto &FE : FuncExtensions) {
OS << " // " << Index << ": " << FE->getName() << "\n"
<< " \"" << FE->getValueAsString("ExtName") << "\",\n";
FunctionExtensionIndex[FE->getName()] = Index++;
}
OS << "};\n\n";
}
void BuiltinNameEmitter::EmitTypeTable() {
OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
for (const auto &T : TypeMap) {
const char *AccessQual =
StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
.Case("RO", "OCLAQ_ReadOnly")
.Case("WO", "OCLAQ_WriteOnly")
.Case("RW", "OCLAQ_ReadWrite")
.Default("OCLAQ_None");
OS << " // " << T.second << "\n"
<< " {OCLT_" << T.first->getValueAsString("Name") << ", "
<< T.first->getValueAsInt("VecWidth") << ", "
<< T.first->getValueAsBit("IsPointer") << ", "
<< T.first->getValueAsBit("IsConst") << ", "
<< T.first->getValueAsBit("IsVolatile") << ", "
<< AccessQual << ", "
<< T.first->getValueAsString("AddrSpace") << "},\n";
}
OS << "};\n\n";
}
void BuiltinNameEmitter::EmitSignatureTable() {
OS << "static const unsigned short SignatureTable[] = {\n";
for (const auto &P : SignaturesList) {
OS << " // " << P.second << "\n ";
for (const Record *R : P.first) {
unsigned Entry = TypeMap.find(R)->second;
if (Entry > USHRT_MAX) {
PrintFatalError("Entry in SignatureTable exceeds limit.");
}
OS << Entry << ", ";
}
OS << "\n";
}
OS << "};\n\n";
}
static unsigned short EncodeVersions(unsigned int MinVersion,
unsigned int MaxVersion) {
unsigned short Encoded = 0;
if (MaxVersion == 0) {
MaxVersion = UINT_MAX;
}
unsigned VersionIDs[] = {100, 110, 120, 200, 300};
for (unsigned I = 0; I < sizeof(VersionIDs) / sizeof(VersionIDs[0]); I++) {
if (VersionIDs[I] >= MinVersion && VersionIDs[I] < MaxVersion) {
Encoded |= 1 << I;
}
}
return Encoded;
}
void BuiltinNameEmitter::EmitBuiltinTable() {
unsigned Index = 0;
OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
for (const auto &SLM : SignatureListMap) {
OS << " // " << (Index + 1) << ": ";
for (const auto &Name : SLM.second.Names) {
OS << Name << ", ";
}
OS << "\n";
for (const auto &Overload : SLM.second.Signatures) {
StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName();
unsigned int MinVersion =
Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID");
unsigned int MaxVersion =
Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID");
OS << " { " << Overload.second << ", "
<< Overload.first->getValueAsListOfDefs("Signature").size() << ", "
<< (Overload.first->getValueAsBit("IsPure")) << ", "
<< (Overload.first->getValueAsBit("IsConst")) << ", "
<< (Overload.first->getValueAsBit("IsConv")) << ", "
<< FunctionExtensionIndex[ExtName] << ", "
<< EncodeVersions(MinVersion, MaxVersion) << " },\n";
Index++;
}
}
OS << "};\n\n";
}
bool BuiltinNameEmitter::CanReuseSignature(
BuiltinIndexListTy *Candidate,
std::vector<std::pair<const Record *, unsigned>> &SignatureList) {
assert(Candidate->size() == SignatureList.size() &&
"signature lists should have the same size");
auto &CandidateSigs =
SignatureListMap.find(Candidate)->second.Signatures;
for (unsigned Index = 0; Index < Candidate->size(); Index++) {
const Record *Rec = SignatureList[Index].first;
const Record *Rec2 = CandidateSigs[Index].first;
if (Rec->getValueAsBit("IsPure") == Rec2->getValueAsBit("IsPure") &&
Rec->getValueAsBit("IsConst") == Rec2->getValueAsBit("IsConst") &&
Rec->getValueAsBit("IsConv") == Rec2->getValueAsBit("IsConv") &&
Rec->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
Rec2->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
Rec->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
Rec2->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
Rec->getValueAsDef("Extension")->getName() ==
Rec2->getValueAsDef("Extension")->getName()) {
return true;
}
}
return false;
}
void BuiltinNameEmitter::GroupBySignature() {
std::vector<BuiltinIndexListTy *> KnownSignatures;
for (auto &Fct : FctOverloadMap) {
bool FoundReusableSig = false;
auto *CurSignatureList = new BuiltinIndexListTy();
for (const auto &Signature : Fct.second) {
CurSignatureList->push_back(Signature.second);
}
llvm::sort(*CurSignatureList);
for (auto *Candidate : KnownSignatures) {
if (Candidate->size() == CurSignatureList->size() &&
*Candidate == *CurSignatureList) {
if (CanReuseSignature(Candidate, Fct.second)) {
SignatureListMap.find(Candidate)->second.Names.push_back(Fct.first);
FoundReusableSig = true;
}
}
}
if (FoundReusableSig) {
delete CurSignatureList;
} else {
SignatureListMap[CurSignatureList] = {
SmallVector<StringRef, 4>(1, Fct.first), Fct.second};
KnownSignatures.push_back(CurSignatureList);
}
}
for (auto *I : KnownSignatures) {
delete I;
}
}
void BuiltinNameEmitter::EmitStringMatcher() {
std::vector<StringMatcher::StringPair> ValidBuiltins;
unsigned CumulativeIndex = 1;
for (const auto &SLM : SignatureListMap) {
const auto &Ovl = SLM.second.Signatures;
for (const auto &FctName : SLM.second.Names) {
std::string RetStmt;
raw_string_ostream SS(RetStmt);
SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
<< ");";
SS.flush();
ValidBuiltins.push_back(
StringMatcher::StringPair(std::string(FctName), RetStmt));
}
CumulativeIndex += Ovl.size();
}
OS << R"(
// Find out whether a string matches an existing OpenCL builtin function name.
// Returns: A pair <0, 0> if no name matches.
// A pair <Index, Len> indexing the BuiltinTable if the name is
// matching an OpenCL builtin function.
static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
)";
StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
OS << " return std::make_pair(0, 0);\n";
OS << "} // isOpenCLBuiltin\n";
}
static void EmitMacroChecks(raw_ostream &OS, StringRef Extensions) {
SmallVector<StringRef, 2> ExtVec;
Extensions.split(ExtVec, " ");
OS << " if (";
for (StringRef Ext : ExtVec) {
if (Ext != ExtVec.front())
OS << " && ";
OS << "S.getPreprocessor().isMacroDefined(\"" << Ext << "\")";
}
OS << ") {\n ";
}
void BuiltinNameEmitter::EmitQualTypeFinder() {
OS << R"(
static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
// Convert an OpenCLTypeStruct type to a list of QualTypes.
// Generic types represent multiple types and vector sizes, thus a vector
// is returned. The conversion is done in two steps:
// Step 1: A switch statement fills a vector with scalar base types for the
// Cartesian product of (vector sizes) x (types) for generic types,
// or a single scalar type for non generic types.
// Step 2: Qualifiers and other type properties such as vector size are
// applied.
static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
llvm::SmallVectorImpl<QualType> &QT) {
ASTContext &Context = S.Context;
// Number of scalar types in the GenType.
unsigned GenTypeNumTypes;
// Pointer to the list of vector sizes for the GenType.
llvm::ArrayRef<unsigned> GenVectorSizes;
)";
for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
OS << " constexpr unsigned List"
<< VectList->getValueAsString("Name") << "[] = {";
for (const auto V : VectList->getValueAsListOfInts("List")) {
OS << V << ", ";
}
OS << "};\n";
}
OS << "\n switch (Ty.ID) {\n";
std::vector<Record *> ImageTypes =
Records.getAllDerivedDefinitions("ImageType");
StringMap<SmallVector<Record *, 3>> ImageTypesMap;
for (auto *IT : ImageTypes) {
auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
if (Entry == ImageTypesMap.end()) {
SmallVector<Record *, 3> ImageList;
ImageList.push_back(IT);
ImageTypesMap.insert(
std::make_pair(IT->getValueAsString("Name"), ImageList));
} else {
Entry->second.push_back(IT);
}
}
for (const auto &ITE : ImageTypesMap) {
OS << " case OCLT_" << ITE.getKey() << ":\n"
<< " switch (Ty.AccessQualifier) {\n"
<< " case OCLAQ_None:\n"
<< " llvm_unreachable(\"Image without access qualifier\");\n";
for (const auto &Image : ITE.getValue()) {
StringRef Exts =
Image->getValueAsDef("Extension")->getValueAsString("ExtName");
OS << StringSwitch<const char *>(
Image->getValueAsString("AccessQualifier"))
.Case("RO", " case OCLAQ_ReadOnly:\n")
.Case("WO", " case OCLAQ_WriteOnly:\n")
.Case("RW", " case OCLAQ_ReadWrite:\n");
if (!Exts.empty()) {
OS << " ";
EmitMacroChecks(OS, Exts);
}
OS << " QT.push_back("
<< Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
<< ");\n";
if (!Exts.empty()) {
OS << " }\n";
}
OS << " break;\n";
}
OS << " }\n"
<< " break;\n";
}
for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
OS << " case OCLT_" << GenType->getValueAsString("Name") << ": {\n";
std::vector<Record *> BaseTypes =
GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
OS << " SmallVector<QualType, " << BaseTypes.size() << "> TypeList;\n";
for (const auto *T : BaseTypes) {
StringRef Exts =
T->getValueAsDef("Extension")->getValueAsString("ExtName");
if (!Exts.empty()) {
EmitMacroChecks(OS, Exts);
}
OS << " TypeList.push_back("
<< T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ");\n";
if (!Exts.empty()) {
OS << " }\n";
}
}
OS << " GenTypeNumTypes = TypeList.size();\n";
std::vector<int64_t> VectorList =
GenType->getValueAsDef("VectorList")->getValueAsListOfInts("List");
OS << " QT.reserve(" << VectorList.size() * BaseTypes.size() << ");\n"
<< " for (unsigned I = 0; I < " << VectorList.size() << "; I++) {\n"
<< " QT.append(TypeList);\n"
<< " }\n";
OS << " GenVectorSizes = List"
<< GenType->getValueAsDef("VectorList")->getValueAsString("Name")
<< ";\n"
<< " break;\n"
<< " }\n";
}
std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
StringMap<bool> TypesSeen;
for (const auto *T : Types) {
if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
continue;
if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
continue;
TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
auto QT = T->getValueAsDef("QTExpr");
if (QT->getValueAsBit("IsAbstract") == 1)
continue;
OS << " case OCLT_" << T->getValueAsString("Name") << ":\n";
StringRef Exts = T->getValueAsDef("Extension")->getValueAsString("ExtName");
if (!Exts.empty()) {
EmitMacroChecks(OS, Exts);
}
OS << " QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n";
if (!Exts.empty()) {
OS << " }\n";
}
OS << " break;\n";
}
OS << " } // end of switch (Ty.ID)\n\n";
OS << " // Construct the different vector types for each generic type.\n";
OS << " if (Ty.ID >= " << TypeList.size() << ") {";
OS << R"(
for (unsigned I = 0; I < QT.size(); I++) {
// For scalars, size is 1.
if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
QT[I] = Context.getExtVectorType(QT[I],
GenVectorSizes[I / GenTypeNumTypes]);
}
}
}
)";
OS << R"(
// Set vector size for non-generic vector types.
if (Ty.VectorWidth > 1) {
for (unsigned Index = 0; Index < QT.size(); Index++) {
QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
}
}
if (Ty.IsVolatile != 0) {
for (unsigned Index = 0; Index < QT.size(); Index++) {
QT[Index] = Context.getVolatileType(QT[Index]);
}
}
if (Ty.IsConst != 0) {
for (unsigned Index = 0; Index < QT.size(); Index++) {
QT[Index] = Context.getConstType(QT[Index]);
}
}
// Transform the type to a pointer as the last step, if necessary.
// Builtin functions only have pointers on [const|volatile], no
// [const|volatile] pointers, so this is ok to do it as a last step.
if (Ty.IsPointer != 0) {
for (unsigned Index = 0; Index < QT.size(); Index++) {
QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
QT[Index] = Context.getPointerType(QT[Index]);
}
}
)";
OS << "\n} // OCL2Qual\n";
}
std::string OpenCLBuiltinFileEmitterBase::getTypeString(const Record *Type,
TypeFlags Flags,
int VectorSize) const {
std::string S;
if (Type->getValueAsBit("IsConst") || Flags.IsConst) {
S += "const ";
}
if (Type->getValueAsBit("IsVolatile") || Flags.IsVolatile) {
S += "volatile ";
}
auto PrintAddrSpace = [&S](StringRef AddrSpace) {
S += StringSwitch<const char *>(AddrSpace)
.Case("clang::LangAS::opencl_private", "__private")
.Case("clang::LangAS::opencl_global", "__global")
.Case("clang::LangAS::opencl_constant", "__constant")
.Case("clang::LangAS::opencl_local", "__local")
.Case("clang::LangAS::opencl_generic", "__generic")
.Default("__private");
S += " ";
};
if (Flags.IsPointer) {
PrintAddrSpace(Flags.AddrSpace);
} else if (Type->getValueAsBit("IsPointer")) {
PrintAddrSpace(Type->getValueAsString("AddrSpace"));
}
StringRef Acc = Type->getValueAsString("AccessQualifier");
if (Acc != "") {
S += StringSwitch<const char *>(Acc)
.Case("RO", "__read_only ")
.Case("WO", "__write_only ")
.Case("RW", "__read_write ");
}
S += Type->getValueAsString("Name").str();
if (VectorSize > 1) {
S += std::to_string(VectorSize);
}
if (Type->getValueAsBit("IsPointer") || Flags.IsPointer) {
S += " *";
}
return S;
}
void OpenCLBuiltinFileEmitterBase::getTypeLists(
Record *Type, TypeFlags &Flags, std::vector<Record *> &TypeList,
std::vector<int64_t> &VectorList) const {
bool isGenType = Type->isSubClassOf("GenericType");
if (isGenType) {
TypeList = Type->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
VectorList =
Type->getValueAsDef("VectorList")->getValueAsListOfInts("List");
return;
}
if (Type->isSubClassOf("PointerType") || Type->isSubClassOf("ConstType") ||
Type->isSubClassOf("VolatileType")) {
StringRef SubTypeName = Type->getValueAsString("Name");
Record *PossibleGenType = Records.getDef(SubTypeName);
if (PossibleGenType && PossibleGenType->isSubClassOf("GenericType")) {
Flags.IsPointer = Type->getValueAsBit("IsPointer");
Flags.IsConst = Type->getValueAsBit("IsConst");
Flags.IsVolatile = Type->getValueAsBit("IsVolatile");
Flags.AddrSpace = Type->getValueAsString("AddrSpace");
getTypeLists(PossibleGenType, Flags, TypeList, VectorList);
return;
}
}
TypeList.push_back(Type);
VectorList.push_back(Type->getValueAsInt("VecWidth"));
}
void OpenCLBuiltinFileEmitterBase::expandTypesInSignature(
const std::vector<Record *> &Signature,
SmallVectorImpl<SmallVector<std::string, 2>> &Types) {
unsigned NumSignatures = 1;
SmallVector<SmallVector<std::string, 4>, 4> ExpandedGenTypes;
for (const auto &Arg : Signature) {
SmallVector<std::string, 4> ExpandedArg;
std::vector<Record *> TypeList;
std::vector<int64_t> VectorList;
TypeFlags Flags;
getTypeLists(Arg, Flags, TypeList, VectorList);
for (const auto &Vector : VectorList) {
for (const auto &Type : TypeList) {
std::string FullType = getTypeString(Type, Flags, Vector);
ExpandedArg.push_back(FullType);
StringRef Ext =
Type->getValueAsDef("Extension")->getValueAsString("ExtName");
if (!Ext.empty() && TypeExtMap.find(FullType) == TypeExtMap.end()) {
TypeExtMap.insert({FullType, Ext});
}
}
}
NumSignatures = std::max<unsigned>(NumSignatures, ExpandedArg.size());
ExpandedGenTypes.push_back(ExpandedArg);
}
for (unsigned I = 0; I < NumSignatures; I++) {
SmallVector<std::string, 2> Args;
for (unsigned ArgNum = 0; ArgNum < Signature.size(); ArgNum++) {
size_t TypeIndex = I % ExpandedGenTypes[ArgNum].size();
Args.push_back(ExpandedGenTypes[ArgNum][TypeIndex]);
}
Types.push_back(Args);
}
}
void OpenCLBuiltinFileEmitterBase::emitExtensionSetup() {
OS << R"(
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
#pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
#pragma OPENCL EXTENSION cl_khr_mipmap_image_writes : enable
#pragma OPENCL EXTENSION cl_khr_3d_image_writes : enable
)";
}
std::string
OpenCLBuiltinFileEmitterBase::emitExtensionGuard(const Record *Builtin) {
StringRef Extensions =
Builtin->getValueAsDef("Extension")->getValueAsString("ExtName");
if (Extensions.empty())
return "";
OS << "#if";
SmallVector<StringRef, 2> ExtVec;
Extensions.split(ExtVec, " ");
bool isFirst = true;
for (StringRef Ext : ExtVec) {
if (!isFirst) {
OS << " &&";
}
OS << " defined(" << Ext << ")";
isFirst = false;
}
OS << "\n";
return "#endif // Extension\n";
}
std::string
OpenCLBuiltinFileEmitterBase::emitVersionGuard(const Record *Builtin) {
std::string OptionalEndif;
auto PrintOpenCLVersion = [this](int Version) {
OS << "CL_VERSION_" << (Version / 100) << "_" << ((Version % 100) / 10);
};
int MinVersion = Builtin->getValueAsDef("MinVersion")->getValueAsInt("ID");
if (MinVersion != 100) {
OS << "#if __OPENCL_C_VERSION__ >= ";
PrintOpenCLVersion(MinVersion);
OS << "\n";
OptionalEndif = "#endif // MinVersion\n" + OptionalEndif;
}
int MaxVersion = Builtin->getValueAsDef("MaxVersion")->getValueAsInt("ID");
if (MaxVersion) {
OS << "#if __OPENCL_C_VERSION__ < ";
PrintOpenCLVersion(MaxVersion);
OS << "\n";
OptionalEndif = "#endif // MaxVersion\n" + OptionalEndif;
}
return OptionalEndif;
}
StringRef OpenCLBuiltinFileEmitterBase::emitTypeExtensionGuards(
const SmallVectorImpl<std::string> &Signature) {
SmallSet<StringRef, 2> ExtSet;
for (const auto &Ty : Signature) {
StringRef TypeExt = TypeExtMap.lookup(Ty);
if (!TypeExt.empty()) {
SmallVector<StringRef, 2> ExtVec;
TypeExt.split(ExtVec, " ");
for (const auto Ext : ExtVec) {
ExtSet.insert(Ext);
}
}
}
if (ExtSet.empty())
return "";
OS << "#if ";
bool isFirst = true;
for (const auto Ext : ExtSet) {
if (!isFirst)
OS << " && ";
OS << "defined(" << Ext << ")";
isFirst = false;
}
OS << "\n";
return "#endif // TypeExtension\n";
}
void OpenCLBuiltinTestEmitter::emit() {
emitSourceFileHeader("OpenCL Builtin exhaustive testing", OS);
emitExtensionSetup();
unsigned TestID = 0;
std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
for (const auto *B : Builtins) {
StringRef Name = B->getValueAsString("Name");
SmallVector<SmallVector<std::string, 2>, 4> FTypes;
expandTypesInSignature(B->getValueAsListOfDefs("Signature"), FTypes);
OS << "// Test " << Name << "\n";
std::string OptionalExtensionEndif = emitExtensionGuard(B);
std::string OptionalVersionEndif = emitVersionGuard(B);
for (const auto &Signature : FTypes) {
StringRef OptionalTypeExtEndif = emitTypeExtensionGuards(Signature);
OS << Signature[0] << " test" << TestID++ << "_" << Name << "(";
if (Signature.size() > 1) {
for (unsigned I = 1; I < Signature.size(); I++) {
if (I != 1)
OS << ", ";
OS << Signature[I] << " arg" << I;
}
}
OS << ") {\n";
OS << " ";
if (Signature[0] != "void") {
OS << "return ";
}
OS << Name << "(";
for (unsigned I = 1; I < Signature.size(); I++) {
if (I != 1)
OS << ", ";
OS << "arg" << I;
}
OS << ");\n";
OS << "}\n";
OS << OptionalTypeExtEndif;
}
OS << OptionalVersionEndif;
OS << OptionalExtensionEndif;
}
}
void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
BuiltinNameEmitter NameChecker(Records, OS);
NameChecker.Emit();
}
void clang::EmitClangOpenCLBuiltinTests(RecordKeeper &Records,
raw_ostream &OS) {
OpenCLBuiltinTestEmitter TestFileGenerator(Records, OS);
TestFileGenerator.emit();
}