1 //===- ClangOpenCLBuiltinEmitter.cpp - Generate Clang OpenCL Builtin handling
3 // The LLVM Compiler Infrastructure
5 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
6 // See https://llvm.org/LICENSE.txt for license information.
7 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
9 //===----------------------------------------------------------------------===//
11 // These backends consume the definitions of OpenCL builtin functions in
12 // clang/lib/Sema/OpenCLBuiltins.td and produce builtin handling code for
13 // inclusion in SemaLookup.cpp, or a test file that calls all declared builtins.
15 //===----------------------------------------------------------------------===//
17 #include "TableGenBackends.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/TableGen/Error.h"
29 #include "llvm/TableGen/Record.h"
30 #include "llvm/TableGen/StringMatcher.h"
31 #include "llvm/TableGen/TableGenBackend.h"
37 // A list of signatures that are shared by one or more builtin functions.
38 struct BuiltinTableEntries
{
39 SmallVector
<StringRef
, 4> Names
;
40 std::vector
<std::pair
<const Record
*, unsigned>> Signatures
;
43 // This tablegen backend emits code for checking whether a function is an
44 // OpenCL builtin function. If so, all overloads of this function are
45 // added to the LookupResult. The generated include file is used by
48 // For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos")
49 // returns a pair <Index, Len>.
50 // BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
51 // <SigIndex, SigLen> of the overloads of "cos".
52 // SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains
53 // one of the signatures of "cos". The SignatureTable entry can be
54 // referenced by other functions, e.g. "sin", to exploit the fact that
55 // many OpenCL builtins share the same signature.
57 // The file generated by this TableGen emitter contains the following:
59 // * Structs and enums to represent types and function signatures.
61 // * const char *FunctionExtensionTable[]
62 // List of space-separated OpenCL extensions. A builtin references an
63 // entry in this table when the builtin requires a particular (set of)
64 // extension(s) to be enabled.
66 // * OpenCLTypeStruct TypeTable[]
67 // Type information for return types and arguments.
69 // * unsigned SignatureTable[]
70 // A list of types representing function signatures. Each entry is an index
71 // into the above TypeTable. Multiple entries following each other form a
72 // signature, where the first entry is the return type and subsequent
73 // entries are the argument types.
75 // * OpenCLBuiltinStruct BuiltinTable[]
76 // Each entry represents one overload of an OpenCL builtin function and
77 // consists of an index into the SignatureTable and the number of arguments.
79 // * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name)
80 // Find out whether a string matches an existing OpenCL builtin function
81 // name and return an index into BuiltinTable and the number of overloads.
83 // * void OCL2Qual(Sema&, OpenCLTypeStruct, std::vector<QualType>&)
84 // Convert an OpenCLTypeStruct type to a list of QualType instances.
85 // One OpenCLTypeStruct can represent multiple types, primarily when using
88 class BuiltinNameEmitter
{
90 BuiltinNameEmitter(RecordKeeper
&Records
, raw_ostream
&OS
)
91 : Records(Records
), OS(OS
) {}
93 // Entrypoint to generate the functions and structures for checking
94 // whether a function is an OpenCL builtin function.
98 // A list of indices into the builtin function table.
99 using BuiltinIndexListTy
= SmallVector
<unsigned, 11>;
101 // Contains OpenCL builtin functions and related information, stored as
102 // Record instances. They are coming from the associated TableGen file.
103 RecordKeeper
&Records
;
108 // Helper function for BuiltinNameEmitter::EmitDeclarations. Generate enum
109 // definitions in the Output string parameter, and save their Record instances
110 // in the List parameter.
111 // \param Types (in) List containing the Types to extract.
112 // \param TypesSeen (inout) List containing the Types already extracted.
113 // \param Output (out) String containing the enums to emit in the output file.
114 // \param List (out) List containing the extracted Types, except the Types in
116 void ExtractEnumTypes(std::vector
<Record
*> &Types
,
117 StringMap
<bool> &TypesSeen
, std::string
&Output
,
118 std::vector
<const Record
*> &List
);
120 // Emit the enum or struct used in the generated file.
121 // Populate the TypeList at the same time.
122 void EmitDeclarations();
124 // Parse the Records generated by TableGen to populate the SignaturesList,
125 // FctOverloadMap and TypeMap.
128 // Compare two lists of signatures and check that e.g. the OpenCL version,
129 // function attributes, and extension are equal for each signature.
130 // \param Candidate (in) Entry in the SignatureListMap to check.
131 // \param SignatureList (in) List of signatures of the considered function.
132 // \returns true if the two lists of signatures are identical.
133 bool CanReuseSignature(
134 BuiltinIndexListTy
*Candidate
,
135 std::vector
<std::pair
<const Record
*, unsigned>> &SignatureList
);
137 // Group functions with the same list of signatures by populating the
139 // Some builtin functions have the same list of signatures, for example the
140 // "sin" and "cos" functions. To save space in the BuiltinTable, the
141 // "isOpenCLBuiltin" function will have the same output for these two
143 void GroupBySignature();
145 // Emit the FunctionExtensionTable that lists all function extensions.
146 void EmitExtensionTable();
148 // Emit the TypeTable containing all types used by OpenCL builtins.
149 void EmitTypeTable();
151 // Emit the SignatureTable. This table contains all the possible signatures.
152 // A signature is stored as a list of indexes of the TypeTable.
153 // The first index references the return type (mandatory), and the followings
154 // reference its arguments.
156 // 15, 2, 15 can represent a function with the signature:
157 // int func(float, int)
158 // The "int" type being at the index 15 in the TypeTable.
159 void EmitSignatureTable();
161 // Emit the BuiltinTable table. This table contains all the overloads of
162 // each function, and is a struct OpenCLBuiltinDecl.
164 // // 891 convert_float2_rtn
165 // { 58, 2, 3, 100, 0 },
166 // This means that the signature of this convert_float2_rtn overload has
167 // 1 argument (+1 for the return type), stored at index 58 in
168 // the SignatureTable. This prototype requires extension "3" in the
169 // FunctionExtensionTable. The last two values represent the minimum (1.0)
170 // and maximum (0, meaning no max version) OpenCL version in which this
171 // overload is supported.
172 void EmitBuiltinTable();
174 // Emit a StringMatcher function to check whether a function name is an
175 // OpenCL builtin function name.
176 void EmitStringMatcher();
178 // Emit a function returning the clang QualType instance associated with
179 // the TableGen Record Type.
180 void EmitQualTypeFinder();
182 // Contains a list of the available signatures, without the name of the
183 // function. Each pair consists of a signature and a cumulative index.
184 // E.g.: <<float, float>, 0>,
185 // <<float, int, int, 2>>,
188 // <<double, double>, 35>.
189 std::vector
<std::pair
<std::vector
<Record
*>, unsigned>> SignaturesList
;
191 // Map the name of a builtin function to its prototypes (instances of the
192 // TableGen "Builtin" class).
193 // Each prototype is registered as a pair of:
194 // <pointer to the "Builtin" instance,
195 // cumulative index of the associated signature in the SignaturesList>
196 // E.g.: The function cos: (float cos(float), double cos(double), ...)
197 // <"cos", <<ptrToPrototype0, 5>,
198 // <ptrToPrototype1, 35>,
199 // <ptrToPrototype2, 79>>
200 // ptrToPrototype1 has the following signature: <double, double>
201 MapVector
<StringRef
, std::vector
<std::pair
<const Record
*, unsigned>>>
204 // Contains the map of OpenCL types to their index in the TypeTable.
205 MapVector
<const Record
*, unsigned> TypeMap
;
207 // List of OpenCL function extensions mapping extension strings to
208 // an index into the FunctionExtensionTable.
209 StringMap
<unsigned> FunctionExtensionIndex
;
211 // List of OpenCL type names in the same order as in enum OpenCLTypeID.
212 // This list does not contain generic types.
213 std::vector
<const Record
*> TypeList
;
215 // Same as TypeList, but for generic types only.
216 std::vector
<const Record
*> GenTypeList
;
218 // Map an ordered vector of signatures to their original Record instances,
219 // and to a list of function names that share these signatures.
221 // For example, suppose the "cos" and "sin" functions have only three
222 // signatures, and these signatures are at index Ix in the SignatureTable:
223 // cos | sin | Signature | Index
224 // float cos(float) | float sin(float) | Signature1 | I1
225 // double cos(double) | double sin(double) | Signature2 | I2
226 // half cos(half) | half sin(half) | Signature3 | I3
228 // Then we will create a mapping of the vector of signatures:
229 // SignatureListMap[<I1, I2, I3>] = <
231 // <Signature1, Signature2, Signature3>>
232 // The function "tan", having the same signatures, would be mapped to the
233 // same entry (<I1, I2, I3>).
234 MapVector
<BuiltinIndexListTy
*, BuiltinTableEntries
> SignatureListMap
;
237 /// Base class for emitting a file (e.g. header or test) from OpenCLBuiltins.td
238 class OpenCLBuiltinFileEmitterBase
{
240 OpenCLBuiltinFileEmitterBase(RecordKeeper
&Records
, raw_ostream
&OS
)
241 : Records(Records
), OS(OS
) {}
242 virtual ~OpenCLBuiltinFileEmitterBase() = default;
244 // Entrypoint to generate the functions for testing all OpenCL builtin
246 virtual void emit() = 0;
250 TypeFlags() : IsConst(false), IsVolatile(false), IsPointer(false) {}
257 // Return a string representation of the given type, such that it can be
258 // used as a type in OpenCL C code.
259 std::string
getTypeString(const Record
*Type
, TypeFlags Flags
,
260 int VectorSize
) const;
262 // Return the type(s) and vector size(s) for the given type. For
263 // non-GenericTypes, the resulting vectors will contain 1 element. For
264 // GenericTypes, the resulting vectors typically contain multiple elements.
265 void getTypeLists(Record
*Type
, TypeFlags
&Flags
,
266 std::vector
<Record
*> &TypeList
,
267 std::vector
<int64_t> &VectorList
) const;
269 // Expand the TableGen Records representing a builtin function signature into
270 // one or more function signatures. Return them as a vector of a vector of
271 // strings, with each string containing an OpenCL C type and optional
274 // The Records may contain GenericTypes, which expand into multiple
275 // signatures. Repeated occurrences of GenericType in a signature expand to
276 // the same types. For example [char, FGenType, FGenType] expands to:
277 // [char, float, float]
278 // [char, float2, float2]
279 // [char, float3, float3]
282 expandTypesInSignature(const std::vector
<Record
*> &Signature
,
283 SmallVectorImpl
<SmallVector
<std::string
, 2>> &Types
);
285 // Emit extension enabling pragmas.
286 void emitExtensionSetup();
288 // Emit an #if guard for a Builtin's extension. Return the corresponding
289 // closing #endif, or an empty string if no extension #if guard was emitted.
290 std::string
emitExtensionGuard(const Record
*Builtin
);
292 // Emit an #if guard for a Builtin's language version. Return the
293 // corresponding closing #endif, or an empty string if no version #if guard
295 std::string
emitVersionGuard(const Record
*Builtin
);
297 // Emit an #if guard for all type extensions required for the given type
298 // strings. Return the corresponding closing #endif, or an empty string
299 // if no extension #if guard was emitted.
301 emitTypeExtensionGuards(const SmallVectorImpl
<std::string
> &Signature
);
303 // Map type strings to type extensions (e.g. "half2" -> "cl_khr_fp16").
304 StringMap
<StringRef
> TypeExtMap
;
306 // Contains OpenCL builtin functions and related information, stored as
307 // Record instances. They are coming from the associated TableGen file.
308 RecordKeeper
&Records
;
314 // OpenCL builtin test generator. This class processes the same TableGen input
315 // as BuiltinNameEmitter, but generates a .cl file that contains a call to each
316 // builtin function described in the .td input.
317 class OpenCLBuiltinTestEmitter
: public OpenCLBuiltinFileEmitterBase
{
319 OpenCLBuiltinTestEmitter(RecordKeeper
&Records
, raw_ostream
&OS
)
320 : OpenCLBuiltinFileEmitterBase(Records
, OS
) {}
322 // Entrypoint to generate the functions for testing all OpenCL builtin
324 void emit() override
;
329 void BuiltinNameEmitter::Emit() {
330 emitSourceFileHeader("OpenCL Builtin handling", OS
);
332 OS
<< "#include \"llvm/ADT/StringRef.h\"\n";
333 OS
<< "using namespace clang;\n\n";
335 // Emit enums and structs.
338 // Parse the Records to populate the internal lists.
343 EmitExtensionTable();
345 EmitSignatureTable();
350 EmitQualTypeFinder();
353 void BuiltinNameEmitter::ExtractEnumTypes(std::vector
<Record
*> &Types
,
354 StringMap
<bool> &TypesSeen
,
356 std::vector
<const Record
*> &List
) {
357 raw_string_ostream
SS(Output
);
359 for (const auto *T
: Types
) {
360 if (TypesSeen
.find(T
->getValueAsString("Name")) == TypesSeen
.end()) {
361 SS
<< " OCLT_" + T
->getValueAsString("Name") << ",\n";
362 // Save the type names in the same order as their enum value. Note that
363 // the Record can be a VectorType or something else, only the name is
366 TypesSeen
.insert(std::make_pair(T
->getValueAsString("Name"), true));
372 void BuiltinNameEmitter::EmitDeclarations() {
373 // Enum of scalar type names (float, int, ...) and generic type sets.
374 OS
<< "enum OpenCLTypeID {\n";
376 StringMap
<bool> TypesSeen
;
377 std::string GenTypeEnums
;
378 std::string TypeEnums
;
380 // Extract generic types and non-generic types separately, to keep
381 // gentypes at the end of the enum which simplifies the special handling
382 // for gentypes in SemaLookup.
383 std::vector
<Record
*> GenTypes
=
384 Records
.getAllDerivedDefinitions("GenericType");
385 ExtractEnumTypes(GenTypes
, TypesSeen
, GenTypeEnums
, GenTypeList
);
387 std::vector
<Record
*> Types
= Records
.getAllDerivedDefinitions("Type");
388 ExtractEnumTypes(Types
, TypesSeen
, TypeEnums
, TypeList
);
394 // Structure definitions.
396 // Image access qualifier.
397 enum OpenCLAccessQual : unsigned char {
404 // Represents a return type or argument type.
405 struct OpenCLTypeStruct {
406 // A type (e.g. float, int, ...).
407 const OpenCLTypeID ID;
408 // Vector size (if applicable; 0 for scalars and generic types).
409 const unsigned VectorWidth;
410 // 0 if the type is not a pointer.
411 const bool IsPointer : 1;
412 // 0 if the type is not const.
413 const bool IsConst : 1;
414 // 0 if the type is not volatile.
415 const bool IsVolatile : 1;
417 const OpenCLAccessQual AccessQualifier;
418 // Address space of the pointer (if applicable).
422 // One overload of an OpenCL builtin function.
423 struct OpenCLBuiltinStruct {
424 // Index of the signature in the OpenCLTypeStruct table.
425 const unsigned SigTableIndex;
426 // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
427 // the SignatureTable represent the complete signature. The first type at
428 // index SigTableIndex is the return type.
429 const unsigned NumTypes;
430 // Function attribute __attribute__((pure))
431 const bool IsPure : 1;
432 // Function attribute __attribute__((const))
433 const bool IsConst : 1;
434 // Function attribute __attribute__((convergent))
435 const bool IsConv : 1;
436 // OpenCL extension(s) required for this overload.
437 const unsigned short Extension;
438 // OpenCL versions in which this overload is available.
439 const unsigned short Versions;
445 // Verify that the combination of GenTypes in a signature is supported.
446 // To simplify the logic for creating overloads in SemaLookup, only allow
447 // a signature to contain different GenTypes if these GenTypes represent
448 // the same number of actual scalar or vector types.
450 // Exit with a fatal error if an unsupported construct is encountered.
451 static void VerifySignature(const std::vector
<Record
*> &Signature
,
452 const Record
*BuiltinRec
) {
453 unsigned GenTypeVecSizes
= 1;
454 unsigned GenTypeTypes
= 1;
456 for (const auto *T
: Signature
) {
457 // Check all GenericType arguments in this signature.
458 if (T
->isSubClassOf("GenericType")) {
459 // Check number of vector sizes.
461 T
->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
462 if (NVecSizes
!= GenTypeVecSizes
&& NVecSizes
!= 1) {
463 if (GenTypeVecSizes
> 1) {
464 // We already saw a gentype with a different number of vector sizes.
465 PrintFatalError(BuiltinRec
->getLoc(),
466 "number of vector sizes should be equal or 1 for all gentypes "
469 GenTypeVecSizes
= NVecSizes
;
472 // Check number of data types.
474 T
->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
475 if (NTypes
!= GenTypeTypes
&& NTypes
!= 1) {
476 if (GenTypeTypes
> 1) {
477 // We already saw a gentype with a different number of types.
478 PrintFatalError(BuiltinRec
->getLoc(),
479 "number of types should be equal or 1 for all gentypes "
482 GenTypeTypes
= NTypes
;
488 void BuiltinNameEmitter::GetOverloads() {
489 // Populate the TypeMap.
490 std::vector
<Record
*> Types
= Records
.getAllDerivedDefinitions("Type");
492 for (const auto &T
: Types
) {
493 TypeMap
.insert(std::make_pair(T
, I
++));
496 // Populate the SignaturesList and the FctOverloadMap.
497 unsigned CumulativeSignIndex
= 0;
498 std::vector
<Record
*> Builtins
= Records
.getAllDerivedDefinitions("Builtin");
499 for (const auto *B
: Builtins
) {
500 StringRef BName
= B
->getValueAsString("Name");
501 if (FctOverloadMap
.find(BName
) == FctOverloadMap
.end()) {
502 FctOverloadMap
.insert(std::make_pair(
503 BName
, std::vector
<std::pair
<const Record
*, unsigned>>{}));
506 auto Signature
= B
->getValueAsListOfDefs("Signature");
507 // Reuse signatures to avoid unnecessary duplicates.
509 llvm::find_if(SignaturesList
,
510 [&](const std::pair
<std::vector
<Record
*>, unsigned> &a
) {
511 return a
.first
== Signature
;
514 if (it
== SignaturesList
.end()) {
515 VerifySignature(Signature
, B
);
516 SignaturesList
.push_back(std::make_pair(Signature
, CumulativeSignIndex
));
517 SignIndex
= CumulativeSignIndex
;
518 CumulativeSignIndex
+= Signature
.size();
520 SignIndex
= it
->second
;
522 FctOverloadMap
[BName
].push_back(std::make_pair(B
, SignIndex
));
526 void BuiltinNameEmitter::EmitExtensionTable() {
527 OS
<< "static const char *FunctionExtensionTable[] = {\n";
529 std::vector
<Record
*> FuncExtensions
=
530 Records
.getAllDerivedDefinitions("FunctionExtension");
532 for (const auto &FE
: FuncExtensions
) {
533 // Emit OpenCL extension table entry.
534 OS
<< " // " << Index
<< ": " << FE
->getName() << "\n"
535 << " \"" << FE
->getValueAsString("ExtName") << "\",\n";
537 // Record index of this extension.
538 FunctionExtensionIndex
[FE
->getName()] = Index
++;
543 void BuiltinNameEmitter::EmitTypeTable() {
544 OS
<< "static const OpenCLTypeStruct TypeTable[] = {\n";
545 for (const auto &T
: TypeMap
) {
546 const char *AccessQual
=
547 StringSwitch
<const char *>(T
.first
->getValueAsString("AccessQualifier"))
548 .Case("RO", "OCLAQ_ReadOnly")
549 .Case("WO", "OCLAQ_WriteOnly")
550 .Case("RW", "OCLAQ_ReadWrite")
551 .Default("OCLAQ_None");
553 OS
<< " // " << T
.second
<< "\n"
554 << " {OCLT_" << T
.first
->getValueAsString("Name") << ", "
555 << T
.first
->getValueAsInt("VecWidth") << ", "
556 << T
.first
->getValueAsBit("IsPointer") << ", "
557 << T
.first
->getValueAsBit("IsConst") << ", "
558 << T
.first
->getValueAsBit("IsVolatile") << ", "
559 << AccessQual
<< ", "
560 << T
.first
->getValueAsString("AddrSpace") << "},\n";
565 void BuiltinNameEmitter::EmitSignatureTable() {
566 // Store a type (e.g. int, float, int2, ...). The type is stored as an index
567 // of a struct OpenCLType table. Multiple entries following each other form a
569 OS
<< "static const unsigned short SignatureTable[] = {\n";
570 for (const auto &P
: SignaturesList
) {
571 OS
<< " // " << P
.second
<< "\n ";
572 for (const Record
*R
: P
.first
) {
573 unsigned Entry
= TypeMap
.find(R
)->second
;
574 if (Entry
> USHRT_MAX
) {
575 // Report an error when seeing an entry that is too large for the
576 // current index type (unsigned short). When hitting this, the type
577 // of SignatureTable will need to be changed.
578 PrintFatalError("Entry in SignatureTable exceeds limit.");
587 // Encode a range MinVersion..MaxVersion into a single bit mask that can be
588 // checked against LangOpts using isOpenCLVersionContainedInMask().
589 // This must be kept in sync with OpenCLVersionID in OpenCLOptions.h.
590 // (Including OpenCLOptions.h here would be a layering violation.)
591 static unsigned short EncodeVersions(unsigned int MinVersion
,
592 unsigned int MaxVersion
) {
593 unsigned short Encoded
= 0;
595 // A maximum version of 0 means available in all later versions.
596 if (MaxVersion
== 0) {
597 MaxVersion
= UINT_MAX
;
600 unsigned VersionIDs
[] = {100, 110, 120, 200, 300};
601 for (unsigned I
= 0; I
< std::size(VersionIDs
); I
++) {
602 if (VersionIDs
[I
] >= MinVersion
&& VersionIDs
[I
] < MaxVersion
) {
610 void BuiltinNameEmitter::EmitBuiltinTable() {
613 OS
<< "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
614 for (const auto &SLM
: SignatureListMap
) {
616 OS
<< " // " << (Index
+ 1) << ": ";
617 for (const auto &Name
: SLM
.second
.Names
) {
622 for (const auto &Overload
: SLM
.second
.Signatures
) {
623 StringRef ExtName
= Overload
.first
->getValueAsDef("Extension")->getName();
624 unsigned int MinVersion
=
625 Overload
.first
->getValueAsDef("MinVersion")->getValueAsInt("ID");
626 unsigned int MaxVersion
=
627 Overload
.first
->getValueAsDef("MaxVersion")->getValueAsInt("ID");
629 OS
<< " { " << Overload
.second
<< ", "
630 << Overload
.first
->getValueAsListOfDefs("Signature").size() << ", "
631 << (Overload
.first
->getValueAsBit("IsPure")) << ", "
632 << (Overload
.first
->getValueAsBit("IsConst")) << ", "
633 << (Overload
.first
->getValueAsBit("IsConv")) << ", "
634 << FunctionExtensionIndex
[ExtName
] << ", "
635 << EncodeVersions(MinVersion
, MaxVersion
) << " },\n";
642 bool BuiltinNameEmitter::CanReuseSignature(
643 BuiltinIndexListTy
*Candidate
,
644 std::vector
<std::pair
<const Record
*, unsigned>> &SignatureList
) {
645 assert(Candidate
->size() == SignatureList
.size() &&
646 "signature lists should have the same size");
648 auto &CandidateSigs
=
649 SignatureListMap
.find(Candidate
)->second
.Signatures
;
650 for (unsigned Index
= 0; Index
< Candidate
->size(); Index
++) {
651 const Record
*Rec
= SignatureList
[Index
].first
;
652 const Record
*Rec2
= CandidateSigs
[Index
].first
;
653 if (Rec
->getValueAsBit("IsPure") == Rec2
->getValueAsBit("IsPure") &&
654 Rec
->getValueAsBit("IsConst") == Rec2
->getValueAsBit("IsConst") &&
655 Rec
->getValueAsBit("IsConv") == Rec2
->getValueAsBit("IsConv") &&
656 Rec
->getValueAsDef("MinVersion")->getValueAsInt("ID") ==
657 Rec2
->getValueAsDef("MinVersion")->getValueAsInt("ID") &&
658 Rec
->getValueAsDef("MaxVersion")->getValueAsInt("ID") ==
659 Rec2
->getValueAsDef("MaxVersion")->getValueAsInt("ID") &&
660 Rec
->getValueAsDef("Extension")->getName() ==
661 Rec2
->getValueAsDef("Extension")->getName()) {
668 void BuiltinNameEmitter::GroupBySignature() {
669 // List of signatures known to be emitted.
670 std::vector
<BuiltinIndexListTy
*> KnownSignatures
;
672 for (auto &Fct
: FctOverloadMap
) {
673 bool FoundReusableSig
= false;
675 // Gather all signatures for the current function.
676 auto *CurSignatureList
= new BuiltinIndexListTy();
677 for (const auto &Signature
: Fct
.second
) {
678 CurSignatureList
->push_back(Signature
.second
);
680 // Sort the list to facilitate future comparisons.
681 llvm::sort(*CurSignatureList
);
683 // Check if we have already seen another function with the same list of
684 // signatures. If so, just add the name of the function.
685 for (auto *Candidate
: KnownSignatures
) {
686 if (Candidate
->size() == CurSignatureList
->size() &&
687 *Candidate
== *CurSignatureList
) {
688 if (CanReuseSignature(Candidate
, Fct
.second
)) {
689 SignatureListMap
.find(Candidate
)->second
.Names
.push_back(Fct
.first
);
690 FoundReusableSig
= true;
695 if (FoundReusableSig
) {
696 delete CurSignatureList
;
699 SignatureListMap
[CurSignatureList
] = {
700 SmallVector
<StringRef
, 4>(1, Fct
.first
), Fct
.second
};
701 KnownSignatures
.push_back(CurSignatureList
);
705 for (auto *I
: KnownSignatures
) {
710 void BuiltinNameEmitter::EmitStringMatcher() {
711 std::vector
<StringMatcher::StringPair
> ValidBuiltins
;
712 unsigned CumulativeIndex
= 1;
714 for (const auto &SLM
: SignatureListMap
) {
715 const auto &Ovl
= SLM
.second
.Signatures
;
717 // A single signature list may be used by different builtins. Return the
718 // same <index, length> pair for each of those builtins.
719 for (const auto &FctName
: SLM
.second
.Names
) {
721 raw_string_ostream
SS(RetStmt
);
722 SS
<< "return std::make_pair(" << CumulativeIndex
<< ", " << Ovl
.size()
725 ValidBuiltins
.push_back(
726 StringMatcher::StringPair(std::string(FctName
), RetStmt
));
728 CumulativeIndex
+= Ovl
.size();
732 // Find out whether a string matches an existing OpenCL builtin function name.
733 // Returns: A pair <0, 0> if no name matches.
734 // A pair <Index, Len> indexing the BuiltinTable if the name is
735 // matching an OpenCL builtin function.
736 static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
740 StringMatcher("Name", ValidBuiltins
, OS
).Emit(0, true);
742 OS
<< " return std::make_pair(0, 0);\n";
743 OS
<< "} // isOpenCLBuiltin\n";
746 // Emit an if-statement with an isMacroDefined call for each extension in
747 // the space-separated list of extensions.
748 static void EmitMacroChecks(raw_ostream
&OS
, StringRef Extensions
) {
749 SmallVector
<StringRef
, 2> ExtVec
;
750 Extensions
.split(ExtVec
, " ");
752 for (StringRef Ext
: ExtVec
) {
753 if (Ext
!= ExtVec
.front())
755 OS
<< "S.getPreprocessor().isMacroDefined(\"" << Ext
<< "\")";
760 void BuiltinNameEmitter::EmitQualTypeFinder() {
763 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
764 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
766 // Convert an OpenCLTypeStruct type to a list of QualTypes.
767 // Generic types represent multiple types and vector sizes, thus a vector
768 // is returned. The conversion is done in two steps:
769 // Step 1: A switch statement fills a vector with scalar base types for the
770 // Cartesian product of (vector sizes) x (types) for generic types,
771 // or a single scalar type for non generic types.
772 // Step 2: Qualifiers and other type properties such as vector size are
774 static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
775 llvm::SmallVectorImpl<QualType> &QT) {
776 ASTContext &Context = S.Context;
777 // Number of scalar types in the GenType.
778 unsigned GenTypeNumTypes;
779 // Pointer to the list of vector sizes for the GenType.
780 llvm::ArrayRef<unsigned> GenVectorSizes;
783 // Generate list of vector sizes for each generic type.
784 for (const auto *VectList
: Records
.getAllDerivedDefinitions("IntList")) {
785 OS
<< " constexpr unsigned List"
786 << VectList
->getValueAsString("Name") << "[] = {";
787 for (const auto V
: VectList
->getValueAsListOfInts("List")) {
794 // Start of switch statement over all types.
795 OS
<< "\n switch (Ty.ID) {\n";
797 // Switch cases for image types (Image2d, Image3d, ...)
798 std::vector
<Record
*> ImageTypes
=
799 Records
.getAllDerivedDefinitions("ImageType");
801 // Map an image type name to its 3 access-qualified types (RO, WO, RW).
802 StringMap
<SmallVector
<Record
*, 3>> ImageTypesMap
;
803 for (auto *IT
: ImageTypes
) {
804 auto Entry
= ImageTypesMap
.find(IT
->getValueAsString("Name"));
805 if (Entry
== ImageTypesMap
.end()) {
806 SmallVector
<Record
*, 3> ImageList
;
807 ImageList
.push_back(IT
);
808 ImageTypesMap
.insert(
809 std::make_pair(IT
->getValueAsString("Name"), ImageList
));
811 Entry
->second
.push_back(IT
);
815 // Emit the cases for the image types. For an image type name, there are 3
816 // corresponding QualTypes ("RO", "WO", "RW"). The "AccessQualifier" field
817 // tells which one is needed. Emit a switch statement that puts the
818 // corresponding QualType into "QT".
819 for (const auto &ITE
: ImageTypesMap
) {
820 OS
<< " case OCLT_" << ITE
.getKey() << ":\n"
821 << " switch (Ty.AccessQualifier) {\n"
822 << " case OCLAQ_None:\n"
823 << " llvm_unreachable(\"Image without access qualifier\");\n";
824 for (const auto &Image
: ITE
.getValue()) {
826 Image
->getValueAsDef("Extension")->getValueAsString("ExtName");
827 OS
<< StringSwitch
<const char *>(
828 Image
->getValueAsString("AccessQualifier"))
829 .Case("RO", " case OCLAQ_ReadOnly:\n")
830 .Case("WO", " case OCLAQ_WriteOnly:\n")
831 .Case("RW", " case OCLAQ_ReadWrite:\n");
834 EmitMacroChecks(OS
, Exts
);
836 OS
<< " QT.push_back("
837 << Image
->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
848 // Switch cases for generic types.
849 for (const auto *GenType
: Records
.getAllDerivedDefinitions("GenericType")) {
850 OS
<< " case OCLT_" << GenType
->getValueAsString("Name") << ": {\n";
852 // Build the Cartesian product of (vector sizes) x (types). Only insert
853 // the plain scalar types for now; other type information such as vector
854 // size and type qualifiers will be added after the switch statement.
855 std::vector
<Record
*> BaseTypes
=
856 GenType
->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
858 // Collect all QualTypes for a single vector size into TypeList.
859 OS
<< " SmallVector<QualType, " << BaseTypes
.size() << "> TypeList;\n";
860 for (const auto *T
: BaseTypes
) {
862 T
->getValueAsDef("Extension")->getValueAsString("ExtName");
864 EmitMacroChecks(OS
, Exts
);
866 OS
<< " TypeList.push_back("
867 << T
->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ");\n";
872 OS
<< " GenTypeNumTypes = TypeList.size();\n";
874 // Duplicate the TypeList for every vector size.
875 std::vector
<int64_t> VectorList
=
876 GenType
->getValueAsDef("VectorList")->getValueAsListOfInts("List");
877 OS
<< " QT.reserve(" << VectorList
.size() * BaseTypes
.size() << ");\n"
878 << " for (unsigned I = 0; I < " << VectorList
.size() << "; I++) {\n"
879 << " QT.append(TypeList);\n"
882 // GenVectorSizes is the list of vector sizes for this GenType.
883 OS
<< " GenVectorSizes = List"
884 << GenType
->getValueAsDef("VectorList")->getValueAsString("Name")
890 // Switch cases for non generic, non image types (int, int4, float, ...).
891 // Only insert the plain scalar type; vector information and type qualifiers
892 // are added in step 2.
893 std::vector
<Record
*> Types
= Records
.getAllDerivedDefinitions("Type");
894 StringMap
<bool> TypesSeen
;
896 for (const auto *T
: Types
) {
897 // Check this is not an image type
898 if (ImageTypesMap
.find(T
->getValueAsString("Name")) != ImageTypesMap
.end())
900 // Check we have not seen this Type
901 if (TypesSeen
.find(T
->getValueAsString("Name")) != TypesSeen
.end())
903 TypesSeen
.insert(std::make_pair(T
->getValueAsString("Name"), true));
905 // Check the Type does not have an "abstract" QualType
906 auto QT
= T
->getValueAsDef("QTExpr");
907 if (QT
->getValueAsBit("IsAbstract") == 1)
909 // Emit the cases for non generic, non image types.
910 OS
<< " case OCLT_" << T
->getValueAsString("Name") << ":\n";
912 StringRef Exts
= T
->getValueAsDef("Extension")->getValueAsString("ExtName");
913 // If this type depends on an extension, ensure the extension macros are
916 EmitMacroChecks(OS
, Exts
);
918 OS
<< " QT.push_back(" << QT
->getValueAsString("TypeExpr") << ");\n";
925 // End of switch statement.
926 OS
<< " } // end of switch (Ty.ID)\n\n";
929 // Add ExtVector types if this was a generic type, as the switch statement
930 // above only populated the list with scalar types. This completes the
931 // construction of the Cartesian product of (vector sizes) x (types).
932 OS
<< " // Construct the different vector types for each generic type.\n";
933 OS
<< " if (Ty.ID >= " << TypeList
.size() << ") {";
935 for (unsigned I = 0; I < QT.size(); I++) {
936 // For scalars, size is 1.
937 if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
938 QT[I] = Context.getExtVectorType(QT[I],
939 GenVectorSizes[I / GenTypeNumTypes]);
945 // Assign the right attributes to the types (e.g. vector size).
947 // Set vector size for non-generic vector types.
948 if (Ty.VectorWidth > 1) {
949 for (unsigned Index = 0; Index < QT.size(); Index++) {
950 QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
954 if (Ty.IsVolatile != 0) {
955 for (unsigned Index = 0; Index < QT.size(); Index++) {
956 QT[Index] = Context.getVolatileType(QT[Index]);
960 if (Ty.IsConst != 0) {
961 for (unsigned Index = 0; Index < QT.size(); Index++) {
962 QT[Index] = Context.getConstType(QT[Index]);
966 // Transform the type to a pointer as the last step, if necessary.
967 // Builtin functions only have pointers on [const|volatile], no
968 // [const|volatile] pointers, so this is ok to do it as a last step.
969 if (Ty.IsPointer != 0) {
970 for (unsigned Index = 0; Index < QT.size(); Index++) {
971 QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
972 QT[Index] = Context.getPointerType(QT[Index]);
977 // End of the "OCL2Qual" function.
978 OS
<< "\n} // OCL2Qual\n";
981 std::string
OpenCLBuiltinFileEmitterBase::getTypeString(const Record
*Type
,
983 int VectorSize
) const {
985 if (Type
->getValueAsBit("IsConst") || Flags
.IsConst
) {
988 if (Type
->getValueAsBit("IsVolatile") || Flags
.IsVolatile
) {
992 auto PrintAddrSpace
= [&S
](StringRef AddrSpace
) {
993 S
+= StringSwitch
<const char *>(AddrSpace
)
994 .Case("clang::LangAS::opencl_private", "__private")
995 .Case("clang::LangAS::opencl_global", "__global")
996 .Case("clang::LangAS::opencl_constant", "__constant")
997 .Case("clang::LangAS::opencl_local", "__local")
998 .Case("clang::LangAS::opencl_generic", "__generic")
999 .Default("__private");
1002 if (Flags
.IsPointer
) {
1003 PrintAddrSpace(Flags
.AddrSpace
);
1004 } else if (Type
->getValueAsBit("IsPointer")) {
1005 PrintAddrSpace(Type
->getValueAsString("AddrSpace"));
1008 StringRef Acc
= Type
->getValueAsString("AccessQualifier");
1010 S
+= StringSwitch
<const char *>(Acc
)
1011 .Case("RO", "__read_only ")
1012 .Case("WO", "__write_only ")
1013 .Case("RW", "__read_write ");
1016 S
+= Type
->getValueAsString("Name").str();
1017 if (VectorSize
> 1) {
1018 S
+= std::to_string(VectorSize
);
1021 if (Type
->getValueAsBit("IsPointer") || Flags
.IsPointer
) {
1028 void OpenCLBuiltinFileEmitterBase::getTypeLists(
1029 Record
*Type
, TypeFlags
&Flags
, std::vector
<Record
*> &TypeList
,
1030 std::vector
<int64_t> &VectorList
) const {
1031 bool isGenType
= Type
->isSubClassOf("GenericType");
1033 TypeList
= Type
->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
1035 Type
->getValueAsDef("VectorList")->getValueAsListOfInts("List");
1039 if (Type
->isSubClassOf("PointerType") || Type
->isSubClassOf("ConstType") ||
1040 Type
->isSubClassOf("VolatileType")) {
1041 StringRef SubTypeName
= Type
->getValueAsString("Name");
1042 Record
*PossibleGenType
= Records
.getDef(SubTypeName
);
1043 if (PossibleGenType
&& PossibleGenType
->isSubClassOf("GenericType")) {
1044 // When PointerType, ConstType, or VolatileType is applied to a
1045 // GenericType, the flags need to be taken from the subtype, not from the
1047 Flags
.IsPointer
= Type
->getValueAsBit("IsPointer");
1048 Flags
.IsConst
= Type
->getValueAsBit("IsConst");
1049 Flags
.IsVolatile
= Type
->getValueAsBit("IsVolatile");
1050 Flags
.AddrSpace
= Type
->getValueAsString("AddrSpace");
1051 getTypeLists(PossibleGenType
, Flags
, TypeList
, VectorList
);
1056 // Not a GenericType, so just insert the single type.
1057 TypeList
.push_back(Type
);
1058 VectorList
.push_back(Type
->getValueAsInt("VecWidth"));
1061 void OpenCLBuiltinFileEmitterBase::expandTypesInSignature(
1062 const std::vector
<Record
*> &Signature
,
1063 SmallVectorImpl
<SmallVector
<std::string
, 2>> &Types
) {
1064 // Find out if there are any GenTypes in this signature, and if so, calculate
1065 // into how many signatures they will expand.
1066 unsigned NumSignatures
= 1;
1067 SmallVector
<SmallVector
<std::string
, 4>, 4> ExpandedGenTypes
;
1068 for (const auto &Arg
: Signature
) {
1069 SmallVector
<std::string
, 4> ExpandedArg
;
1070 std::vector
<Record
*> TypeList
;
1071 std::vector
<int64_t> VectorList
;
1074 getTypeLists(Arg
, Flags
, TypeList
, VectorList
);
1076 // Insert the Cartesian product of the types and vector sizes.
1077 for (const auto &Vector
: VectorList
) {
1078 for (const auto &Type
: TypeList
) {
1079 std::string FullType
= getTypeString(Type
, Flags
, Vector
);
1080 ExpandedArg
.push_back(FullType
);
1082 // If the type requires an extension, add a TypeExtMap entry mapping
1083 // the full type name to the extension.
1085 Type
->getValueAsDef("Extension")->getValueAsString("ExtName");
1086 if (!Ext
.empty() && TypeExtMap
.find(FullType
) == TypeExtMap
.end()) {
1087 TypeExtMap
.insert({FullType
, Ext
});
1091 NumSignatures
= std::max
<unsigned>(NumSignatures
, ExpandedArg
.size());
1092 ExpandedGenTypes
.push_back(ExpandedArg
);
1095 // Now the total number of signatures is known. Populate the return list with
1097 for (unsigned I
= 0; I
< NumSignatures
; I
++) {
1098 SmallVector
<std::string
, 2> Args
;
1100 // Process a single signature.
1101 for (unsigned ArgNum
= 0; ArgNum
< Signature
.size(); ArgNum
++) {
1102 // For differently-sized GenTypes in a parameter list, the smaller
1103 // GenTypes just repeat, so index modulo the number of expanded types.
1104 size_t TypeIndex
= I
% ExpandedGenTypes
[ArgNum
].size();
1105 Args
.push_back(ExpandedGenTypes
[ArgNum
][TypeIndex
]);
1107 Types
.push_back(Args
);
1111 void OpenCLBuiltinFileEmitterBase::emitExtensionSetup() {
1113 #pragma OPENCL EXTENSION cl_khr_fp16 : enable
1114 #pragma OPENCL EXTENSION cl_khr_fp64 : enable
1115 #pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
1116 #pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
1117 #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
1118 #pragma OPENCL EXTENSION cl_khr_mipmap_image_writes : enable
1119 #pragma OPENCL EXTENSION cl_khr_3d_image_writes : enable
1125 OpenCLBuiltinFileEmitterBase::emitExtensionGuard(const Record
*Builtin
) {
1126 StringRef Extensions
=
1127 Builtin
->getValueAsDef("Extension")->getValueAsString("ExtName");
1128 if (Extensions
.empty())
1133 SmallVector
<StringRef
, 2> ExtVec
;
1134 Extensions
.split(ExtVec
, " ");
1135 bool isFirst
= true;
1136 for (StringRef Ext
: ExtVec
) {
1140 OS
<< " defined(" << Ext
<< ")";
1145 return "#endif // Extension\n";
1149 OpenCLBuiltinFileEmitterBase::emitVersionGuard(const Record
*Builtin
) {
1150 std::string OptionalEndif
;
1151 auto PrintOpenCLVersion
= [this](int Version
) {
1152 OS
<< "CL_VERSION_" << (Version
/ 100) << "_" << ((Version
% 100) / 10);
1154 int MinVersion
= Builtin
->getValueAsDef("MinVersion")->getValueAsInt("ID");
1155 if (MinVersion
!= 100) {
1156 // OpenCL 1.0 is the default minimum version.
1157 OS
<< "#if __OPENCL_C_VERSION__ >= ";
1158 PrintOpenCLVersion(MinVersion
);
1160 OptionalEndif
= "#endif // MinVersion\n" + OptionalEndif
;
1162 int MaxVersion
= Builtin
->getValueAsDef("MaxVersion")->getValueAsInt("ID");
1164 OS
<< "#if __OPENCL_C_VERSION__ < ";
1165 PrintOpenCLVersion(MaxVersion
);
1167 OptionalEndif
= "#endif // MaxVersion\n" + OptionalEndif
;
1169 return OptionalEndif
;
1172 StringRef
OpenCLBuiltinFileEmitterBase::emitTypeExtensionGuards(
1173 const SmallVectorImpl
<std::string
> &Signature
) {
1174 SmallSet
<StringRef
, 2> ExtSet
;
1176 // Iterate over all types to gather the set of required TypeExtensions.
1177 for (const auto &Ty
: Signature
) {
1178 StringRef TypeExt
= TypeExtMap
.lookup(Ty
);
1179 if (!TypeExt
.empty()) {
1180 // The TypeExtensions are space-separated in the .td file.
1181 SmallVector
<StringRef
, 2> ExtVec
;
1182 TypeExt
.split(ExtVec
, " ");
1183 for (const auto Ext
: ExtVec
) {
1189 // Emit the #if only when at least one extension is required.
1194 bool isFirst
= true;
1195 for (const auto Ext
: ExtSet
) {
1198 OS
<< "defined(" << Ext
<< ")";
1202 return "#endif // TypeExtension\n";
1205 void OpenCLBuiltinTestEmitter::emit() {
1206 emitSourceFileHeader("OpenCL Builtin exhaustive testing", OS
);
1208 emitExtensionSetup();
1210 // Ensure each test has a unique name by numbering them.
1211 unsigned TestID
= 0;
1213 // Iterate over all builtins.
1214 std::vector
<Record
*> Builtins
= Records
.getAllDerivedDefinitions("Builtin");
1215 for (const auto *B
: Builtins
) {
1216 StringRef Name
= B
->getValueAsString("Name");
1218 SmallVector
<SmallVector
<std::string
, 2>, 4> FTypes
;
1219 expandTypesInSignature(B
->getValueAsListOfDefs("Signature"), FTypes
);
1221 OS
<< "// Test " << Name
<< "\n";
1223 std::string OptionalExtensionEndif
= emitExtensionGuard(B
);
1224 std::string OptionalVersionEndif
= emitVersionGuard(B
);
1226 for (const auto &Signature
: FTypes
) {
1227 StringRef OptionalTypeExtEndif
= emitTypeExtensionGuards(Signature
);
1229 // Emit function declaration.
1230 OS
<< Signature
[0] << " test" << TestID
++ << "_" << Name
<< "(";
1231 if (Signature
.size() > 1) {
1232 for (unsigned I
= 1; I
< Signature
.size(); I
++) {
1235 OS
<< Signature
[I
] << " arg" << I
;
1240 // Emit function body.
1242 if (Signature
[0] != "void") {
1246 for (unsigned I
= 1; I
< Signature
.size(); I
++) {
1253 // End of function body.
1255 OS
<< OptionalTypeExtEndif
;
1258 OS
<< OptionalVersionEndif
;
1259 OS
<< OptionalExtensionEndif
;
1263 void clang::EmitClangOpenCLBuiltins(RecordKeeper
&Records
, raw_ostream
&OS
) {
1264 BuiltinNameEmitter
NameChecker(Records
, OS
);
1268 void clang::EmitClangOpenCLBuiltinTests(RecordKeeper
&Records
,
1270 OpenCLBuiltinTestEmitter
TestFileGenerator(Records
, OS
);
1271 TestFileGenerator
.emit();