blob: c8975d7bf615dbc7ed2423efda229577f01d1c9c [file] [log] [blame]
Sven van Haastregt79a222f2019-06-03 09:39:11 +00001//===- ClangOpenCLBuiltinEmitter.cpp - Generate Clang OpenCL Builtin handling
2//
3// The LLVM Compiler Infrastructure
4//
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
8//
9//===----------------------------------------------------------------------===//
10//
11// This tablegen backend emits code for checking whether a function is an
12// OpenCL builtin function. If so, all overloads of this function are
13// added to the LookupResult. The generated include file is used by
14// SemaLookup.cpp
15//
16// For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos")
17// returns a pair <Index, Len>.
Sven van Haastregtb21a3652019-08-19 11:56:03 +000018// BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
Sven van Haastregt79a222f2019-06-03 09:39:11 +000019// <SigIndex, SigLen> of the overloads of "cos".
Sven van Haastregtb21a3652019-08-19 11:56:03 +000020// SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains
21// one of the signatures of "cos". The SignatureTable entry can be
22// referenced by other functions, e.g. "sin", to exploit the fact that
23// many OpenCL builtins share the same signature.
24//
25// The file generated by this TableGen emitter contains the following:
26//
27// * Structs and enums to represent types and function signatures.
28//
29// * OpenCLTypeStruct TypeTable[]
30// Type information for return types and arguments.
31//
32// * unsigned SignatureTable[]
33// A list of types representing function signatures. Each entry is an index
34// into the above TypeTable. Multiple entries following each other form a
35// signature, where the first entry is the return type and subsequent
36// entries are the argument types.
37//
38// * OpenCLBuiltinStruct BuiltinTable[]
39// Each entry represents one overload of an OpenCL builtin function and
40// consists of an index into the SignatureTable and the number of arguments.
41//
42// * std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name)
43// Find out whether a string matches an existing OpenCL builtin function
44// name and return an index into BuiltinTable and the number of overloads.
45//
46// * void OCL2Qual(ASTContext&, OpenCLTypeStruct, std::vector<QualType>&)
47// Convert an OpenCLTypeStruct type to a list of QualType instances.
48// One OpenCLTypeStruct can represent multiple types, primarily when using
49// GenTypes.
50//
Sven van Haastregt79a222f2019-06-03 09:39:11 +000051//===----------------------------------------------------------------------===//
52
John McCallc45f8d42019-10-01 23:12:57 +000053#include "TableGenBackends.h"
Sven van Haastregt79a222f2019-06-03 09:39:11 +000054#include "llvm/ADT/MapVector.h"
55#include "llvm/ADT/STLExtras.h"
56#include "llvm/ADT/SmallString.h"
57#include "llvm/ADT/StringExtras.h"
58#include "llvm/ADT/StringRef.h"
59#include "llvm/ADT/StringSet.h"
Sven van Haastregt988f1e32019-09-05 10:01:24 +000060#include "llvm/ADT/StringSwitch.h"
Sven van Haastregt79a222f2019-06-03 09:39:11 +000061#include "llvm/Support/ErrorHandling.h"
62#include "llvm/Support/raw_ostream.h"
63#include "llvm/TableGen/Error.h"
64#include "llvm/TableGen/Record.h"
65#include "llvm/TableGen/StringMatcher.h"
66#include "llvm/TableGen/TableGenBackend.h"
67#include <set>
68
69using namespace llvm;
70
71namespace {
72class BuiltinNameEmitter {
73public:
74 BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
75 : Records(Records), OS(OS) {}
76
77 // Entrypoint to generate the functions and structures for checking
78 // whether a function is an OpenCL builtin function.
79 void Emit();
80
81private:
82 // Contains OpenCL builtin functions and related information, stored as
83 // Record instances. They are coming from the associated TableGen file.
84 RecordKeeper &Records;
85
86 // The output file.
87 raw_ostream &OS;
88
Sven van Haastregtb21a3652019-08-19 11:56:03 +000089 // Helper function for BuiltinNameEmitter::EmitDeclarations. Generate enum
90 // definitions in the Output string parameter, and save their Record instances
91 // in the List parameter.
92 // \param Types (in) List containing the Types to extract.
93 // \param TypesSeen (inout) List containing the Types already extracted.
94 // \param Output (out) String containing the enums to emit in the output file.
95 // \param List (out) List containing the extracted Types, except the Types in
96 // TypesSeen.
97 void ExtractEnumTypes(std::vector<Record *> &Types,
98 StringMap<bool> &TypesSeen, std::string &Output,
99 std::vector<const Record *> &List);
100
101 // Emit the enum or struct used in the generated file.
102 // Populate the TypeList at the same time.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000103 void EmitDeclarations();
104
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000105 // Parse the Records generated by TableGen to populate the SignaturesList,
106 // FctOverloadMap and TypeMap.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000107 void GetOverloads();
108
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000109 // Emit the TypeTable containing all types used by OpenCL builtins.
110 void EmitTypeTable();
111
112 // Emit the SignatureTable. This table contains all the possible signatures.
113 // A signature is stored as a list of indexes of the TypeTable.
114 // The first index references the return type (mandatory), and the followings
115 // reference its arguments.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000116 // E.g.:
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000117 // 15, 2, 15 can represent a function with the signature:
118 // int func(float, int)
119 // The "int" type being at the index 15 in the TypeTable.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000120 void EmitSignatureTable();
121
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000122 // Emit the BuiltinTable table. This table contains all the overloads of
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000123 // each function, and is a struct OpenCLBuiltinDecl.
124 // E.g.:
Sven van Haastregted69faa2019-09-19 13:41:51 +0000125 // // 891 convert_float2_rtn
126 // { 58, 2, 100, 0 },
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000127 // This means that the signature of this convert_float2_rtn overload has
128 // 1 argument (+1 for the return type), stored at index 58 in
Sven van Haastregted69faa2019-09-19 13:41:51 +0000129 // the SignatureTable. The last two values represent the minimum (1.0) and
130 // maximum (0, meaning no max version) OpenCL version in which this overload
131 // is supported.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000132 void EmitBuiltinTable();
133
134 // Emit a StringMatcher function to check whether a function name is an
135 // OpenCL builtin function name.
136 void EmitStringMatcher();
137
138 // Emit a function returning the clang QualType instance associated with
139 // the TableGen Record Type.
140 void EmitQualTypeFinder();
141
142 // Contains a list of the available signatures, without the name of the
143 // function. Each pair consists of a signature and a cumulative index.
144 // E.g.: <<float, float>, 0>,
145 // <<float, int, int, 2>>,
146 // <<float>, 5>,
147 // ...
148 // <<double, double>, 35>.
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000149 std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000150
151 // Map the name of a builtin function to its prototypes (instances of the
152 // TableGen "Builtin" class).
153 // Each prototype is registered as a pair of:
154 // <pointer to the "Builtin" instance,
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000155 // cumulative index of the associated signature in the SignaturesList>
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000156 // E.g.: The function cos: (float cos(float), double cos(double), ...)
157 // <"cos", <<ptrToPrototype0, 5>,
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000158 // <ptrToPrototype1, 35>,
159 // <ptrToPrototype2, 79>>
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000160 // ptrToPrototype1 has the following signature: <double, double>
161 MapVector<StringRef, std::vector<std::pair<const Record *, unsigned>>>
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000162 FctOverloadMap;
163
164 // Contains the map of OpenCL types to their index in the TypeTable.
165 MapVector<const Record *, unsigned> TypeMap;
166
167 // List of OpenCL type names in the same order as in enum OpenCLTypeID.
168 // This list does not contain generic types.
169 std::vector<const Record *> TypeList;
170
171 // Same as TypeList, but for generic types only.
172 std::vector<const Record *> GenTypeList;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000173};
174} // namespace
175
176void BuiltinNameEmitter::Emit() {
177 emitSourceFileHeader("OpenCL Builtin handling", OS);
178
179 OS << "#include \"llvm/ADT/StringRef.h\"\n";
180 OS << "using namespace clang;\n\n";
181
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000182 // Emit enums and structs.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000183 EmitDeclarations();
184
185 GetOverloads();
186
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000187 // Emit tables.
188 EmitTypeTable();
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000189 EmitSignatureTable();
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000190 EmitBuiltinTable();
191
192 EmitStringMatcher();
193
194 EmitQualTypeFinder();
195}
196
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000197void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
198 StringMap<bool> &TypesSeen,
199 std::string &Output,
200 std::vector<const Record *> &List) {
201 raw_string_ostream SS(Output);
202
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000203 for (const auto *T : Types) {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000204 if (TypesSeen.find(T->getValueAsString("Name")) == TypesSeen.end()) {
205 SS << " OCLT_" + T->getValueAsString("Name") << ",\n";
206 // Save the type names in the same order as their enum value. Note that
207 // the Record can be a VectorType or something else, only the name is
208 // important.
209 List.push_back(T);
210 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
211 }
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000212 }
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000213 SS.flush();
214}
215
216void BuiltinNameEmitter::EmitDeclarations() {
217 // Enum of scalar type names (float, int, ...) and generic type sets.
218 OS << "enum OpenCLTypeID {\n";
219
220 StringMap<bool> TypesSeen;
221 std::string GenTypeEnums;
222 std::string TypeEnums;
223
224 // Extract generic types and non-generic types separately, to keep
225 // gentypes at the end of the enum which simplifies the special handling
226 // for gentypes in SemaLookup.
227 std::vector<Record *> GenTypes =
228 Records.getAllDerivedDefinitions("GenericType");
229 ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
230
231 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
232 ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
233
234 OS << TypeEnums;
235 OS << GenTypeEnums;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000236 OS << "};\n";
237
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000238 // Structure definitions.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000239 OS << R"(
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000240// Image access qualifier.
241enum OpenCLAccessQual : unsigned char {
242 OCLAQ_None,
243 OCLAQ_ReadOnly,
244 OCLAQ_WriteOnly,
245 OCLAQ_ReadWrite
246};
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000247
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000248// Represents a return type or argument type.
249struct OpenCLTypeStruct {
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000250 // A type (e.g. float, int, ...).
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000251 const OpenCLTypeID ID;
252 // Vector size (if applicable; 0 for scalars and generic types).
253 const unsigned VectorWidth;
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000254 // 0 if the type is not a pointer.
255 const bool IsPointer;
256 // 0 if the type is not const.
257 const bool IsConst;
258 // 0 if the type is not volatile.
259 const bool IsVolatile;
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000260 // Access qualifier.
261 const OpenCLAccessQual AccessQualifier;
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000262 // Address space of the pointer (if applicable).
263 const LangAS AS;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000264};
265
266// One overload of an OpenCL builtin function.
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000267struct OpenCLBuiltinStruct {
268 // Index of the signature in the OpenCLTypeStruct table.
269 const unsigned SigTableIndex;
270 // Entries between index SigTableIndex and (SigTableIndex + NumTypes - 1) in
271 // the SignatureTable represent the complete signature. The first type at
272 // index SigTableIndex is the return type.
273 const unsigned NumTypes;
Sven van Haastregted69faa2019-09-19 13:41:51 +0000274 // First OpenCL version in which this overload was introduced (e.g. CL20).
275 const unsigned short MinVersion;
276 // First OpenCL version in which this overload was removed (e.g. CL20).
277 const unsigned short MaxVersion;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000278};
279
280)";
281}
282
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000283// Verify that the combination of GenTypes in a signature is supported.
284// To simplify the logic for creating overloads in SemaLookup, only allow
285// a signature to contain different GenTypes if these GenTypes represent
286// the same number of actual scalar or vector types.
287//
288// Exit with a fatal error if an unsupported construct is encountered.
289static void VerifySignature(const std::vector<Record *> &Signature,
290 const Record *BuiltinRec) {
291 unsigned GenTypeVecSizes = 1;
292 unsigned GenTypeTypes = 1;
293
294 for (const auto *T : Signature) {
295 // Check all GenericType arguments in this signature.
296 if (T->isSubClassOf("GenericType")) {
297 // Check number of vector sizes.
298 unsigned NVecSizes =
299 T->getValueAsDef("VectorList")->getValueAsListOfInts("List").size();
300 if (NVecSizes != GenTypeVecSizes && NVecSizes != 1) {
301 if (GenTypeVecSizes > 1) {
302 // We already saw a gentype with a different number of vector sizes.
303 PrintFatalError(BuiltinRec->getLoc(),
304 "number of vector sizes should be equal or 1 for all gentypes "
305 "in a declaration");
306 }
307 GenTypeVecSizes = NVecSizes;
308 }
309
310 // Check number of data types.
311 unsigned NTypes =
312 T->getValueAsDef("TypeList")->getValueAsListOfDefs("List").size();
313 if (NTypes != GenTypeTypes && NTypes != 1) {
314 if (GenTypeTypes > 1) {
315 // We already saw a gentype with a different number of types.
316 PrintFatalError(BuiltinRec->getLoc(),
317 "number of types should be equal or 1 for all gentypes "
318 "in a declaration");
319 }
320 GenTypeTypes = NTypes;
321 }
322 }
323 }
324}
325
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000326void BuiltinNameEmitter::GetOverloads() {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000327 // Populate the TypeMap.
328 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
329 unsigned I = 0;
330 for (const auto &T : Types) {
331 TypeMap.insert(std::make_pair(T, I++));
332 }
333
334 // Populate the SignaturesList and the FctOverloadMap.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000335 unsigned CumulativeSignIndex = 0;
336 std::vector<Record *> Builtins = Records.getAllDerivedDefinitions("Builtin");
337 for (const auto *B : Builtins) {
338 StringRef BName = B->getValueAsString("Name");
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000339 if (FctOverloadMap.find(BName) == FctOverloadMap.end()) {
340 FctOverloadMap.insert(std::make_pair(
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000341 BName, std::vector<std::pair<const Record *, unsigned>>{}));
342 }
343
344 auto Signature = B->getValueAsListOfDefs("Signature");
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000345 // Reuse signatures to avoid unnecessary duplicates.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000346 auto it =
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000347 std::find_if(SignaturesList.begin(), SignaturesList.end(),
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000348 [&](const std::pair<std::vector<Record *>, unsigned> &a) {
349 return a.first == Signature;
350 });
351 unsigned SignIndex;
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000352 if (it == SignaturesList.end()) {
353 VerifySignature(Signature, B);
354 SignaturesList.push_back(std::make_pair(Signature, CumulativeSignIndex));
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000355 SignIndex = CumulativeSignIndex;
356 CumulativeSignIndex += Signature.size();
357 } else {
358 SignIndex = it->second;
359 }
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000360 FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000361 }
362}
363
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000364void BuiltinNameEmitter::EmitTypeTable() {
365 OS << "static const OpenCLTypeStruct TypeTable[] = {\n";
366 for (const auto &T : TypeMap) {
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000367 const char *AccessQual =
368 StringSwitch<const char *>(T.first->getValueAsString("AccessQualifier"))
369 .Case("RO", "OCLAQ_ReadOnly")
370 .Case("WO", "OCLAQ_WriteOnly")
371 .Case("RW", "OCLAQ_ReadWrite")
372 .Default("OCLAQ_None");
373
374 OS << " // " << T.second << "\n"
375 << " {OCLT_" << T.first->getValueAsString("Name") << ", "
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000376 << T.first->getValueAsInt("VecWidth") << ", "
377 << T.first->getValueAsBit("IsPointer") << ", "
378 << T.first->getValueAsBit("IsConst") << ", "
379 << T.first->getValueAsBit("IsVolatile") << ", "
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000380 << AccessQual << ", "
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000381 << T.first->getValueAsString("AddrSpace") << "},\n";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000382 }
383 OS << "};\n\n";
384}
385
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000386void BuiltinNameEmitter::EmitSignatureTable() {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000387 // Store a type (e.g. int, float, int2, ...). The type is stored as an index
388 // of a struct OpenCLType table. Multiple entries following each other form a
389 // signature.
390 OS << "static const unsigned SignatureTable[] = {\n";
391 for (const auto &P : SignaturesList) {
392 OS << " // " << P.second << "\n ";
393 for (const Record *R : P.first) {
394 OS << TypeMap.find(R)->second << ", ";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000395 }
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000396 OS << "\n";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000397 }
398 OS << "};\n\n";
399}
400
401void BuiltinNameEmitter::EmitBuiltinTable() {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000402 unsigned Index = 0;
403
404 OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
405 for (const auto &FOM : FctOverloadMap) {
406
407 OS << " // " << (Index + 1) << ": " << FOM.first << "\n";
408
409 for (const auto &Overload : FOM.second) {
Sven van Haastregted69faa2019-09-19 13:41:51 +0000410 OS << " { " << Overload.second << ", "
411 << Overload.first->getValueAsListOfDefs("Signature").size() << ", "
412 << Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID")
413 << ", "
414 << Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID")
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000415 << " },\n";
Sven van Haastregted69faa2019-09-19 13:41:51 +0000416 Index++;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000417 }
418 }
419 OS << "};\n\n";
420}
421
422void BuiltinNameEmitter::EmitStringMatcher() {
423 std::vector<StringMatcher::StringPair> ValidBuiltins;
424 unsigned CumulativeIndex = 1;
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000425 for (auto &i : FctOverloadMap) {
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000426 auto &Ov = i.second;
427 std::string RetStmt;
428 raw_string_ostream SS(RetStmt);
429 SS << "return std::make_pair(" << CumulativeIndex << ", " << Ov.size()
430 << ");";
431 SS.flush();
432 CumulativeIndex += Ov.size();
433
434 ValidBuiltins.push_back(StringMatcher::StringPair(i.first, RetStmt));
435 }
436
437 OS << R"(
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000438// Find out whether a string matches an existing OpenCL builtin function name.
439// Returns: A pair <0, 0> if no name matches.
440// A pair <Index, Len> indexing the BuiltinTable if the name is
441// matching an OpenCL builtin function.
442static std::pair<unsigned, unsigned> isOpenCLBuiltin(llvm::StringRef Name) {
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000443
444)";
445
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000446 StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000447
448 OS << " return std::make_pair(0, 0);\n";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000449 OS << "} // isOpenCLBuiltin\n";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000450}
451
452void BuiltinNameEmitter::EmitQualTypeFinder() {
453 OS << R"(
454
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000455// Convert an OpenCLTypeStruct type to a list of QualTypes.
456// Generic types represent multiple types and vector sizes, thus a vector
457// is returned. The conversion is done in two steps:
458// Step 1: A switch statement fills a vector with scalar base types for the
459// Cartesian product of (vector sizes) x (types) for generic types,
460// or a single scalar type for non generic types.
461// Step 2: Qualifiers and other type properties such as vector size are
462// applied.
463static void OCL2Qual(ASTContext &Context, const OpenCLTypeStruct &Ty,
Benjamin Kramer19651b62019-08-24 13:04:34 +0000464 llvm::SmallVectorImpl<QualType> &QT) {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000465 // Number of scalar types in the GenType.
466 unsigned GenTypeNumTypes;
467 // Pointer to the list of vector sizes for the GenType.
Benjamin Kramer19651b62019-08-24 13:04:34 +0000468 llvm::ArrayRef<unsigned> GenVectorSizes;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000469)";
470
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000471 // Generate list of vector sizes for each generic type.
472 for (const auto *VectList : Records.getAllDerivedDefinitions("IntList")) {
Benjamin Kramer19651b62019-08-24 13:04:34 +0000473 OS << " constexpr unsigned List"
474 << VectList->getValueAsString("Name") << "[] = {";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000475 for (const auto V : VectList->getValueAsListOfInts("List")) {
476 OS << V << ", ";
477 }
478 OS << "};\n";
479 }
480
481 // Step 1.
482 // Start of switch statement over all types.
483 OS << "\n switch (Ty.ID) {\n";
484
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000485 // Switch cases for image types (Image2d, Image3d, ...)
486 std::vector<Record *> ImageTypes =
487 Records.getAllDerivedDefinitions("ImageType");
488
489 // Map an image type name to its 3 access-qualified types (RO, WO, RW).
490 std::map<StringRef, SmallVector<Record *, 3>> ImageTypesMap;
491 for (auto *IT : ImageTypes) {
492 auto Entry = ImageTypesMap.find(IT->getValueAsString("Name"));
493 if (Entry == ImageTypesMap.end()) {
494 SmallVector<Record *, 3> ImageList;
495 ImageList.push_back(IT);
496 ImageTypesMap.insert(
497 std::make_pair(IT->getValueAsString("Name"), ImageList));
498 } else {
499 Entry->second.push_back(IT);
500 }
501 }
502
503 // Emit the cases for the image types. For an image type name, there are 3
504 // corresponding QualTypes ("RO", "WO", "RW"). The "AccessQualifier" field
505 // tells which one is needed. Emit a switch statement that puts the
506 // corresponding QualType into "QT".
507 for (const auto &ITE : ImageTypesMap) {
508 OS << " case OCLT_" << ITE.first.str() << ":\n"
509 << " switch (Ty.AccessQualifier) {\n"
510 << " case OCLAQ_None:\n"
511 << " llvm_unreachable(\"Image without access qualifier\");\n";
512 for (const auto &Image : ITE.second) {
513 OS << StringSwitch<const char *>(
514 Image->getValueAsString("AccessQualifier"))
515 .Case("RO", " case OCLAQ_ReadOnly:\n")
516 .Case("WO", " case OCLAQ_WriteOnly:\n")
517 .Case("RW", " case OCLAQ_ReadWrite:\n")
518 << " QT.push_back(Context."
519 << Image->getValueAsDef("QTName")->getValueAsString("Name") << ");\n"
520 << " break;\n";
521 }
522 OS << " }\n"
523 << " break;\n";
524 }
525
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000526 // Switch cases for generic types.
527 for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
528 OS << " case OCLT_" << GenType->getValueAsString("Name") << ":\n";
Benjamin Kramer19651b62019-08-24 13:04:34 +0000529 OS << " QT.append({";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000530
531 // Build the Cartesian product of (vector sizes) x (types). Only insert
532 // the plain scalar types for now; other type information such as vector
533 // size and type qualifiers will be added after the switch statement.
534 for (unsigned I = 0; I < GenType->getValueAsDef("VectorList")
535 ->getValueAsListOfInts("List")
536 .size();
537 I++) {
538 for (const auto *T :
539 GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) {
Benjamin Kramer19651b62019-08-24 13:04:34 +0000540 OS << "Context."
541 << T->getValueAsDef("QTName")->getValueAsString("Name") << ", ";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000542 }
543 }
Sven van Haastregt92b2be12019-09-03 11:23:24 +0000544 OS << "});\n";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000545 // GenTypeNumTypes is the number of types in the GenType
546 // (e.g. float/double/half).
547 OS << " GenTypeNumTypes = "
548 << GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")
549 .size()
550 << ";\n";
551 // GenVectorSizes is the list of vector sizes for this GenType.
552 // QT contains GenTypeNumTypes * #GenVectorSizes elements.
Benjamin Kramer19651b62019-08-24 13:04:34 +0000553 OS << " GenVectorSizes = List"
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000554 << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
555 << ";\n";
556 OS << " break;\n";
557 }
558
559 // Switch cases for non generic, non image types (int, int4, float, ...).
560 // Only insert the plain scalar type; vector information and type qualifiers
561 // are added in step 2.
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000562 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
563 StringMap<bool> TypesSeen;
564
565 for (const auto *T : Types) {
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000566 // Check this is not an image type
567 if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
568 continue;
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000569 // Check we have not seen this Type
570 if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
571 continue;
572 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
573
574 // Check the Type does not have an "abstract" QualType
575 auto QT = T->getValueAsDef("QTName");
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000576 if (QT->getValueAsBit("IsAbstract") == 1)
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000577 continue;
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000578 // Emit the cases for non generic, non image types.
579 OS << " case OCLT_" << T->getValueAsString("Name") << ":\n";
580 OS << " QT.push_back(Context." << QT->getValueAsString("Name")
581 << ");\n";
582 OS << " break;\n";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000583 }
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000584
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000585 // End of switch statement.
Sven van Haastregt988f1e32019-09-05 10:01:24 +0000586 OS << " default:\n"
587 << " llvm_unreachable(\"OpenCL builtin type not handled yet\");\n"
588 << " } // end of switch (Ty.ID)\n\n";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000589
590 // Step 2.
591 // Add ExtVector types if this was a generic type, as the switch statement
592 // above only populated the list with scalar types. This completes the
593 // construction of the Cartesian product of (vector sizes) x (types).
594 OS << " // Construct the different vector types for each generic type.\n";
595 OS << " if (Ty.ID >= " << TypeList.size() << ") {";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000596 OS << R"(
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000597 for (unsigned I = 0; I < QT.size(); I++) {
598 // For scalars, size is 1.
Benjamin Kramer19651b62019-08-24 13:04:34 +0000599 if (GenVectorSizes[I / GenTypeNumTypes] != 1) {
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000600 QT[I] = Context.getExtVectorType(QT[I],
Benjamin Kramer19651b62019-08-24 13:04:34 +0000601 GenVectorSizes[I / GenTypeNumTypes]);
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000602 }
603 }
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000604 }
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000605)";
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000606
607 // Assign the right attributes to the types (e.g. vector size).
608 OS << R"(
609 // Set vector size for non-generic vector types.
610 if (Ty.VectorWidth > 1) {
611 for (unsigned Index = 0; Index < QT.size(); Index++) {
612 QT[Index] = Context.getExtVectorType(QT[Index], Ty.VectorWidth);
613 }
614 }
Sven van Haastregtcc0ba282019-08-20 12:21:03 +0000615
616 if (Ty.IsVolatile != 0) {
617 for (unsigned Index = 0; Index < QT.size(); Index++) {
618 QT[Index] = Context.getVolatileType(QT[Index]);
619 }
620 }
621
622 if (Ty.IsConst != 0) {
623 for (unsigned Index = 0; Index < QT.size(); Index++) {
624 QT[Index] = Context.getConstType(QT[Index]);
625 }
626 }
627
628 // Transform the type to a pointer as the last step, if necessary.
629 // Builtin functions only have pointers on [const|volatile], no
630 // [const|volatile] pointers, so this is ok to do it as a last step.
631 if (Ty.IsPointer != 0) {
632 for (unsigned Index = 0; Index < QT.size(); Index++) {
633 QT[Index] = Context.getAddrSpaceQualType(QT[Index], Ty.AS);
634 QT[Index] = Context.getPointerType(QT[Index]);
635 }
636 }
Sven van Haastregtb21a3652019-08-19 11:56:03 +0000637)";
638
639 // End of the "OCL2Qual" function.
640 OS << "\n} // OCL2Qual\n";
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000641}
642
John McCallc45f8d42019-10-01 23:12:57 +0000643void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
Sven van Haastregt79a222f2019-06-03 09:39:11 +0000644 BuiltinNameEmitter NameChecker(Records, OS);
645 NameChecker.Emit();
646}