150
|
1 //===- 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 //
|
223
|
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.
|
|
14 //
|
|
15 //===----------------------------------------------------------------------===//
|
|
16
|
|
17 #include "TableGenBackends.h"
|
|
18 #include "llvm/ADT/MapVector.h"
|
|
19 #include "llvm/ADT/STLExtras.h"
|
236
|
20 #include "llvm/ADT/SmallSet.h"
|
223
|
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"
|
|
32
|
|
33 using namespace llvm;
|
|
34
|
|
35 namespace {
|
|
36
|
|
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;
|
|
41 };
|
|
42
|
150
|
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
|
|
46 // SemaLookup.cpp
|
|
47 //
|
|
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.
|
|
56 //
|
|
57 // The file generated by this TableGen emitter contains the following:
|
|
58 //
|
|
59 // * Structs and enums to represent types and function signatures.
|
|
60 //
|
|
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.
|
|
65 //
|
|
66 // * OpenCLTypeStruct TypeTable[]
|
|
67 // Type information for return types and arguments.
|
|
68 //
|
|
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.
|
|
74 //
|
|
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.
|
|
78 //
|
|
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.
|
|
82 //
|
221
|
83 // * void OCL2Qual(Sema&, OpenCLTypeStruct, std::vector<QualType>&)
|
150
|
84 // Convert an OpenCLTypeStruct type to a list of QualType instances.
|
|
85 // One OpenCLTypeStruct can represent multiple types, primarily when using
|
|
86 // GenTypes.
|
|
87 //
|
|
88 class BuiltinNameEmitter {
|
|
89 public:
|
|
90 BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
|
|
91 : Records(Records), OS(OS) {}
|
|
92
|
|
93 // Entrypoint to generate the functions and structures for checking
|
|
94 // whether a function is an OpenCL builtin function.
|
|
95 void Emit();
|
|
96
|
|
97 private:
|
|
98 // A list of indices into the builtin function table.
|
|
99 using BuiltinIndexListTy = SmallVector<unsigned, 11>;
|
|
100
|
|
101 // Contains OpenCL builtin functions and related information, stored as
|
|
102 // Record instances. They are coming from the associated TableGen file.
|
|
103 RecordKeeper &Records;
|
|
104
|
|
105 // The output file.
|
|
106 raw_ostream &OS;
|
|
107
|
|
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
|
|
115 // TypesSeen.
|
|
116 void ExtractEnumTypes(std::vector<Record *> &Types,
|
|
117 StringMap<bool> &TypesSeen, std::string &Output,
|
|
118 std::vector<const Record *> &List);
|
|
119
|
|
120 // Emit the enum or struct used in the generated file.
|
|
121 // Populate the TypeList at the same time.
|
|
122 void EmitDeclarations();
|
|
123
|
|
124 // Parse the Records generated by TableGen to populate the SignaturesList,
|
|
125 // FctOverloadMap and TypeMap.
|
|
126 void GetOverloads();
|
|
127
|
|
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);
|
|
136
|
|
137 // Group functions with the same list of signatures by populating the
|
|
138 // SignatureListMap.
|
|
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
|
|
142 // function names.
|
|
143 void GroupBySignature();
|
|
144
|
|
145 // Emit the FunctionExtensionTable that lists all function extensions.
|
|
146 void EmitExtensionTable();
|
|
147
|
|
148 // Emit the TypeTable containing all types used by OpenCL builtins.
|
|
149 void EmitTypeTable();
|
|
150
|
|
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.
|
|
155 // E.g.:
|
|
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();
|
|
160
|
|
161 // Emit the BuiltinTable table. This table contains all the overloads of
|
|
162 // each function, and is a struct OpenCLBuiltinDecl.
|
|
163 // E.g.:
|
|
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();
|
|
173
|
|
174 // Emit a StringMatcher function to check whether a function name is an
|
|
175 // OpenCL builtin function name.
|
|
176 void EmitStringMatcher();
|
|
177
|
|
178 // Emit a function returning the clang QualType instance associated with
|
|
179 // the TableGen Record Type.
|
|
180 void EmitQualTypeFinder();
|
|
181
|
|
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>>,
|
|
186 // <<float>, 5>,
|
|
187 // ...
|
|
188 // <<double, double>, 35>.
|
|
189 std::vector<std::pair<std::vector<Record *>, unsigned>> SignaturesList;
|
|
190
|
|
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>>>
|
|
202 FctOverloadMap;
|
|
203
|
|
204 // Contains the map of OpenCL types to their index in the TypeTable.
|
|
205 MapVector<const Record *, unsigned> TypeMap;
|
|
206
|
|
207 // List of OpenCL function extensions mapping extension strings to
|
|
208 // an index into the FunctionExtensionTable.
|
|
209 StringMap<unsigned> FunctionExtensionIndex;
|
|
210
|
|
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;
|
|
214
|
|
215 // Same as TypeList, but for generic types only.
|
|
216 std::vector<const Record *> GenTypeList;
|
|
217
|
|
218 // Map an ordered vector of signatures to their original Record instances,
|
|
219 // and to a list of function names that share these signatures.
|
|
220 //
|
|
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
|
|
227 //
|
|
228 // Then we will create a mapping of the vector of signatures:
|
|
229 // SignatureListMap[<I1, I2, I3>] = <
|
|
230 // <"cos", "sin">,
|
|
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;
|
|
235 };
|
223
|
236
|
236
|
237 /// Base class for emitting a file (e.g. header or test) from OpenCLBuiltins.td
|
|
238 class OpenCLBuiltinFileEmitterBase {
|
223
|
239 public:
|
236
|
240 OpenCLBuiltinFileEmitterBase(RecordKeeper &Records, raw_ostream &OS)
|
223
|
241 : Records(Records), OS(OS) {}
|
236
|
242 virtual ~OpenCLBuiltinFileEmitterBase() = default;
|
223
|
243
|
|
244 // Entrypoint to generate the functions for testing all OpenCL builtin
|
|
245 // functions.
|
236
|
246 virtual void emit() = 0;
|
223
|
247
|
236
|
248 protected:
|
223
|
249 struct TypeFlags {
|
|
250 TypeFlags() : IsConst(false), IsVolatile(false), IsPointer(false) {}
|
|
251 bool IsConst : 1;
|
|
252 bool IsVolatile : 1;
|
|
253 bool IsPointer : 1;
|
|
254 StringRef AddrSpace;
|
|
255 };
|
|
256
|
|
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;
|
|
261
|
|
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;
|
|
268
|
|
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
|
|
272 // qualifiers.
|
|
273 //
|
|
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]
|
|
280 // ...
|
|
281 void
|
|
282 expandTypesInSignature(const std::vector<Record *> &Signature,
|
|
283 SmallVectorImpl<SmallVector<std::string, 2>> &Types);
|
|
284
|
236
|
285 // Emit extension enabling pragmas.
|
|
286 void emitExtensionSetup();
|
|
287
|
|
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);
|
|
291
|
|
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
|
|
294 // was emitted.
|
|
295 std::string emitVersionGuard(const Record *Builtin);
|
|
296
|
|
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.
|
|
300 StringRef
|
|
301 emitTypeExtensionGuards(const SmallVectorImpl<std::string> &Signature);
|
|
302
|
|
303 // Map type strings to type extensions (e.g. "half2" -> "cl_khr_fp16").
|
|
304 StringMap<StringRef> TypeExtMap;
|
|
305
|
223
|
306 // Contains OpenCL builtin functions and related information, stored as
|
|
307 // Record instances. They are coming from the associated TableGen file.
|
|
308 RecordKeeper &Records;
|
|
309
|
|
310 // The output file.
|
|
311 raw_ostream &OS;
|
|
312 };
|
|
313
|
236
|
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 {
|
|
318 public:
|
|
319 OpenCLBuiltinTestEmitter(RecordKeeper &Records, raw_ostream &OS)
|
|
320 : OpenCLBuiltinFileEmitterBase(Records, OS) {}
|
|
321
|
|
322 // Entrypoint to generate the functions for testing all OpenCL builtin
|
|
323 // functions.
|
|
324 void emit() override;
|
|
325 };
|
|
326
|
150
|
327 } // namespace
|
|
328
|
|
329 void BuiltinNameEmitter::Emit() {
|
|
330 emitSourceFileHeader("OpenCL Builtin handling", OS);
|
|
331
|
|
332 OS << "#include \"llvm/ADT/StringRef.h\"\n";
|
|
333 OS << "using namespace clang;\n\n";
|
|
334
|
|
335 // Emit enums and structs.
|
|
336 EmitDeclarations();
|
|
337
|
|
338 // Parse the Records to populate the internal lists.
|
|
339 GetOverloads();
|
|
340 GroupBySignature();
|
|
341
|
|
342 // Emit tables.
|
|
343 EmitExtensionTable();
|
|
344 EmitTypeTable();
|
|
345 EmitSignatureTable();
|
|
346 EmitBuiltinTable();
|
|
347
|
|
348 // Emit functions.
|
|
349 EmitStringMatcher();
|
|
350 EmitQualTypeFinder();
|
|
351 }
|
|
352
|
|
353 void BuiltinNameEmitter::ExtractEnumTypes(std::vector<Record *> &Types,
|
|
354 StringMap<bool> &TypesSeen,
|
|
355 std::string &Output,
|
|
356 std::vector<const Record *> &List) {
|
|
357 raw_string_ostream SS(Output);
|
|
358
|
|
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
|
|
364 // important.
|
|
365 List.push_back(T);
|
|
366 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
|
|
367 }
|
|
368 }
|
|
369 SS.flush();
|
|
370 }
|
|
371
|
|
372 void BuiltinNameEmitter::EmitDeclarations() {
|
|
373 // Enum of scalar type names (float, int, ...) and generic type sets.
|
|
374 OS << "enum OpenCLTypeID {\n";
|
|
375
|
|
376 StringMap<bool> TypesSeen;
|
|
377 std::string GenTypeEnums;
|
|
378 std::string TypeEnums;
|
|
379
|
|
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);
|
|
386
|
|
387 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
|
|
388 ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
|
|
389
|
|
390 OS << TypeEnums;
|
|
391 OS << GenTypeEnums;
|
|
392 OS << "};\n";
|
|
393
|
|
394 // Structure definitions.
|
|
395 OS << R"(
|
|
396 // Image access qualifier.
|
|
397 enum OpenCLAccessQual : unsigned char {
|
|
398 OCLAQ_None,
|
|
399 OCLAQ_ReadOnly,
|
|
400 OCLAQ_WriteOnly,
|
|
401 OCLAQ_ReadWrite
|
|
402 };
|
|
403
|
|
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;
|
|
416 // Access qualifier.
|
|
417 const OpenCLAccessQual AccessQualifier;
|
|
418 // Address space of the pointer (if applicable).
|
|
419 const LangAS AS;
|
|
420 };
|
|
421
|
|
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;
|
221
|
438 // OpenCL versions in which this overload is available.
|
|
439 const unsigned short Versions;
|
150
|
440 };
|
|
441
|
|
442 )";
|
|
443 }
|
|
444
|
|
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.
|
|
449 //
|
|
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;
|
|
455
|
|
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.
|
|
460 unsigned NVecSizes =
|
|
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 "
|
|
467 "in a declaration");
|
|
468 }
|
|
469 GenTypeVecSizes = NVecSizes;
|
|
470 }
|
|
471
|
|
472 // Check number of data types.
|
|
473 unsigned NTypes =
|
|
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 "
|
|
480 "in a declaration");
|
|
481 }
|
|
482 GenTypeTypes = NTypes;
|
|
483 }
|
|
484 }
|
|
485 }
|
|
486 }
|
|
487
|
|
488 void BuiltinNameEmitter::GetOverloads() {
|
|
489 // Populate the TypeMap.
|
|
490 std::vector<Record *> Types = Records.getAllDerivedDefinitions("Type");
|
|
491 unsigned I = 0;
|
|
492 for (const auto &T : Types) {
|
|
493 TypeMap.insert(std::make_pair(T, I++));
|
|
494 }
|
|
495
|
|
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>>{}));
|
|
504 }
|
|
505
|
|
506 auto Signature = B->getValueAsListOfDefs("Signature");
|
|
507 // Reuse signatures to avoid unnecessary duplicates.
|
|
508 auto it =
|
236
|
509 llvm::find_if(SignaturesList,
|
|
510 [&](const std::pair<std::vector<Record *>, unsigned> &a) {
|
|
511 return a.first == Signature;
|
|
512 });
|
150
|
513 unsigned SignIndex;
|
|
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();
|
|
519 } else {
|
|
520 SignIndex = it->second;
|
|
521 }
|
|
522 FctOverloadMap[BName].push_back(std::make_pair(B, SignIndex));
|
|
523 }
|
|
524 }
|
|
525
|
|
526 void BuiltinNameEmitter::EmitExtensionTable() {
|
|
527 OS << "static const char *FunctionExtensionTable[] = {\n";
|
|
528 unsigned Index = 0;
|
|
529 std::vector<Record *> FuncExtensions =
|
|
530 Records.getAllDerivedDefinitions("FunctionExtension");
|
|
531
|
|
532 for (const auto &FE : FuncExtensions) {
|
|
533 // Emit OpenCL extension table entry.
|
|
534 OS << " // " << Index << ": " << FE->getName() << "\n"
|
|
535 << " \"" << FE->getValueAsString("ExtName") << "\",\n";
|
|
536
|
|
537 // Record index of this extension.
|
|
538 FunctionExtensionIndex[FE->getName()] = Index++;
|
|
539 }
|
|
540 OS << "};\n\n";
|
|
541 }
|
|
542
|
|
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");
|
|
552
|
|
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";
|
|
561 }
|
|
562 OS << "};\n\n";
|
|
563 }
|
|
564
|
|
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
|
|
568 // signature.
|
|
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.");
|
|
579 }
|
|
580 OS << Entry << ", ";
|
|
581 }
|
|
582 OS << "\n";
|
|
583 }
|
|
584 OS << "};\n\n";
|
|
585 }
|
|
586
|
221
|
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;
|
|
594
|
|
595 // A maximum version of 0 means available in all later versions.
|
|
596 if (MaxVersion == 0) {
|
|
597 MaxVersion = UINT_MAX;
|
|
598 }
|
|
599
|
|
600 unsigned VersionIDs[] = {100, 110, 120, 200, 300};
|
|
601 for (unsigned I = 0; I < sizeof(VersionIDs) / sizeof(VersionIDs[0]); I++) {
|
|
602 if (VersionIDs[I] >= MinVersion && VersionIDs[I] < MaxVersion) {
|
|
603 Encoded |= 1 << I;
|
|
604 }
|
|
605 }
|
|
606
|
|
607 return Encoded;
|
|
608 }
|
|
609
|
150
|
610 void BuiltinNameEmitter::EmitBuiltinTable() {
|
|
611 unsigned Index = 0;
|
|
612
|
|
613 OS << "static const OpenCLBuiltinStruct BuiltinTable[] = {\n";
|
|
614 for (const auto &SLM : SignatureListMap) {
|
|
615
|
|
616 OS << " // " << (Index + 1) << ": ";
|
|
617 for (const auto &Name : SLM.second.Names) {
|
|
618 OS << Name << ", ";
|
|
619 }
|
|
620 OS << "\n";
|
|
621
|
|
622 for (const auto &Overload : SLM.second.Signatures) {
|
|
623 StringRef ExtName = Overload.first->getValueAsDef("Extension")->getName();
|
221
|
624 unsigned int MinVersion =
|
|
625 Overload.first->getValueAsDef("MinVersion")->getValueAsInt("ID");
|
|
626 unsigned int MaxVersion =
|
|
627 Overload.first->getValueAsDef("MaxVersion")->getValueAsInt("ID");
|
|
628
|
150
|
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] << ", "
|
221
|
635 << EncodeVersions(MinVersion, MaxVersion) << " },\n";
|
150
|
636 Index++;
|
|
637 }
|
|
638 }
|
|
639 OS << "};\n\n";
|
|
640 }
|
|
641
|
|
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");
|
|
647
|
|
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()) {
|
|
662 return true;
|
|
663 }
|
|
664 }
|
|
665 return false;
|
|
666 }
|
|
667
|
|
668 void BuiltinNameEmitter::GroupBySignature() {
|
|
669 // List of signatures known to be emitted.
|
|
670 std::vector<BuiltinIndexListTy *> KnownSignatures;
|
|
671
|
|
672 for (auto &Fct : FctOverloadMap) {
|
|
673 bool FoundReusableSig = false;
|
|
674
|
|
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);
|
|
679 }
|
|
680 // Sort the list to facilitate future comparisons.
|
173
|
681 llvm::sort(*CurSignatureList);
|
150
|
682
|
|
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;
|
|
691 }
|
|
692 }
|
|
693 }
|
|
694
|
|
695 if (FoundReusableSig) {
|
|
696 delete CurSignatureList;
|
|
697 } else {
|
|
698 // Add a new entry.
|
|
699 SignatureListMap[CurSignatureList] = {
|
|
700 SmallVector<StringRef, 4>(1, Fct.first), Fct.second};
|
|
701 KnownSignatures.push_back(CurSignatureList);
|
|
702 }
|
|
703 }
|
|
704
|
|
705 for (auto *I : KnownSignatures) {
|
|
706 delete I;
|
|
707 }
|
|
708 }
|
|
709
|
|
710 void BuiltinNameEmitter::EmitStringMatcher() {
|
|
711 std::vector<StringMatcher::StringPair> ValidBuiltins;
|
|
712 unsigned CumulativeIndex = 1;
|
|
713
|
|
714 for (const auto &SLM : SignatureListMap) {
|
|
715 const auto &Ovl = SLM.second.Signatures;
|
|
716
|
|
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) {
|
|
720 std::string RetStmt;
|
|
721 raw_string_ostream SS(RetStmt);
|
|
722 SS << "return std::make_pair(" << CumulativeIndex << ", " << Ovl.size()
|
|
723 << ");";
|
|
724 SS.flush();
|
|
725 ValidBuiltins.push_back(
|
|
726 StringMatcher::StringPair(std::string(FctName), RetStmt));
|
|
727 }
|
|
728 CumulativeIndex += Ovl.size();
|
|
729 }
|
|
730
|
|
731 OS << R"(
|
|
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) {
|
|
737
|
|
738 )";
|
|
739
|
|
740 StringMatcher("Name", ValidBuiltins, OS).Emit(0, true);
|
|
741
|
|
742 OS << " return std::make_pair(0, 0);\n";
|
|
743 OS << "} // isOpenCLBuiltin\n";
|
|
744 }
|
|
745
|
236
|
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, " ");
|
|
751 OS << " if (";
|
|
752 for (StringRef Ext : ExtVec) {
|
|
753 if (Ext != ExtVec.front())
|
|
754 OS << " && ";
|
|
755 OS << "S.getPreprocessor().isMacroDefined(\"" << Ext << "\")";
|
|
756 }
|
|
757 OS << ") {\n ";
|
|
758 }
|
|
759
|
150
|
760 void BuiltinNameEmitter::EmitQualTypeFinder() {
|
|
761 OS << R"(
|
|
762
|
221
|
763 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
|
|
764 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
|
|
765
|
150
|
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
|
|
773 // applied.
|
221
|
774 static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
|
150
|
775 llvm::SmallVectorImpl<QualType> &QT) {
|
221
|
776 ASTContext &Context = S.Context;
|
150
|
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;
|
|
781 )";
|
|
782
|
|
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")) {
|
|
788 OS << V << ", ";
|
|
789 }
|
|
790 OS << "};\n";
|
|
791 }
|
|
792
|
|
793 // Step 1.
|
|
794 // Start of switch statement over all types.
|
|
795 OS << "\n switch (Ty.ID) {\n";
|
|
796
|
|
797 // Switch cases for image types (Image2d, Image3d, ...)
|
|
798 std::vector<Record *> ImageTypes =
|
|
799 Records.getAllDerivedDefinitions("ImageType");
|
|
800
|
|
801 // Map an image type name to its 3 access-qualified types (RO, WO, RW).
|
221
|
802 StringMap<SmallVector<Record *, 3>> ImageTypesMap;
|
150
|
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));
|
|
810 } else {
|
|
811 Entry->second.push_back(IT);
|
|
812 }
|
|
813 }
|
|
814
|
|
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) {
|
221
|
820 OS << " case OCLT_" << ITE.getKey() << ":\n"
|
150
|
821 << " switch (Ty.AccessQualifier) {\n"
|
|
822 << " case OCLAQ_None:\n"
|
|
823 << " llvm_unreachable(\"Image without access qualifier\");\n";
|
221
|
824 for (const auto &Image : ITE.getValue()) {
|
236
|
825 StringRef Exts =
|
|
826 Image->getValueAsDef("Extension")->getValueAsString("ExtName");
|
150
|
827 OS << StringSwitch<const char *>(
|
|
828 Image->getValueAsString("AccessQualifier"))
|
|
829 .Case("RO", " case OCLAQ_ReadOnly:\n")
|
|
830 .Case("WO", " case OCLAQ_WriteOnly:\n")
|
236
|
831 .Case("RW", " case OCLAQ_ReadWrite:\n");
|
|
832 if (!Exts.empty()) {
|
|
833 OS << " ";
|
|
834 EmitMacroChecks(OS, Exts);
|
|
835 }
|
|
836 OS << " QT.push_back("
|
221
|
837 << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
|
236
|
838 << ");\n";
|
|
839 if (!Exts.empty()) {
|
|
840 OS << " }\n";
|
|
841 }
|
|
842 OS << " break;\n";
|
150
|
843 }
|
|
844 OS << " }\n"
|
|
845 << " break;\n";
|
|
846 }
|
|
847
|
|
848 // Switch cases for generic types.
|
|
849 for (const auto *GenType : Records.getAllDerivedDefinitions("GenericType")) {
|
221
|
850 OS << " case OCLT_" << GenType->getValueAsString("Name") << ": {\n";
|
150
|
851
|
|
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.
|
221
|
855 std::vector<Record *> BaseTypes =
|
|
856 GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
|
|
857
|
|
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) {
|
236
|
861 StringRef Exts =
|
221
|
862 T->getValueAsDef("Extension")->getValueAsString("ExtName");
|
236
|
863 if (!Exts.empty()) {
|
|
864 EmitMacroChecks(OS, Exts);
|
221
|
865 }
|
|
866 OS << " TypeList.push_back("
|
|
867 << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ");\n";
|
236
|
868 if (!Exts.empty()) {
|
221
|
869 OS << " }\n";
|
150
|
870 }
|
|
871 }
|
221
|
872 OS << " GenTypeNumTypes = TypeList.size();\n";
|
|
873
|
|
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"
|
|
880 << " }\n";
|
|
881
|
150
|
882 // GenVectorSizes is the list of vector sizes for this GenType.
|
|
883 OS << " GenVectorSizes = List"
|
|
884 << GenType->getValueAsDef("VectorList")->getValueAsString("Name")
|
221
|
885 << ";\n"
|
|
886 << " break;\n"
|
|
887 << " }\n";
|
150
|
888 }
|
|
889
|
|
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;
|
|
895
|
|
896 for (const auto *T : Types) {
|
|
897 // Check this is not an image type
|
|
898 if (ImageTypesMap.find(T->getValueAsString("Name")) != ImageTypesMap.end())
|
|
899 continue;
|
|
900 // Check we have not seen this Type
|
|
901 if (TypesSeen.find(T->getValueAsString("Name")) != TypesSeen.end())
|
|
902 continue;
|
|
903 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
|
|
904
|
|
905 // Check the Type does not have an "abstract" QualType
|
221
|
906 auto QT = T->getValueAsDef("QTExpr");
|
150
|
907 if (QT->getValueAsBit("IsAbstract") == 1)
|
|
908 continue;
|
|
909 // Emit the cases for non generic, non image types.
|
|
910 OS << " case OCLT_" << T->getValueAsString("Name") << ":\n";
|
221
|
911
|
236
|
912 StringRef Exts = T->getValueAsDef("Extension")->getValueAsString("ExtName");
|
|
913 // If this type depends on an extension, ensure the extension macros are
|
221
|
914 // defined.
|
236
|
915 if (!Exts.empty()) {
|
|
916 EmitMacroChecks(OS, Exts);
|
221
|
917 }
|
|
918 OS << " QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n";
|
236
|
919 if (!Exts.empty()) {
|
221
|
920 OS << " }\n";
|
|
921 }
|
150
|
922 OS << " break;\n";
|
|
923 }
|
|
924
|
|
925 // End of switch statement.
|
|
926 OS << " } // end of switch (Ty.ID)\n\n";
|
|
927
|
|
928 // Step 2.
|
|
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() << ") {";
|
|
934 OS << R"(
|
|
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]);
|
|
940 }
|
|
941 }
|
|
942 }
|
|
943 )";
|
|
944
|
|
945 // Assign the right attributes to the types (e.g. vector size).
|
|
946 OS << R"(
|
|
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);
|
|
951 }
|
|
952 }
|
|
953
|
|
954 if (Ty.IsVolatile != 0) {
|
|
955 for (unsigned Index = 0; Index < QT.size(); Index++) {
|
|
956 QT[Index] = Context.getVolatileType(QT[Index]);
|
|
957 }
|
|
958 }
|
|
959
|
|
960 if (Ty.IsConst != 0) {
|
|
961 for (unsigned Index = 0; Index < QT.size(); Index++) {
|
|
962 QT[Index] = Context.getConstType(QT[Index]);
|
|
963 }
|
|
964 }
|
|
965
|
|
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]);
|
|
973 }
|
|
974 }
|
|
975 )";
|
|
976
|
|
977 // End of the "OCL2Qual" function.
|
|
978 OS << "\n} // OCL2Qual\n";
|
|
979 }
|
|
980
|
236
|
981 std::string OpenCLBuiltinFileEmitterBase::getTypeString(const Record *Type,
|
|
982 TypeFlags Flags,
|
|
983 int VectorSize) const {
|
223
|
984 std::string S;
|
|
985 if (Type->getValueAsBit("IsConst") || Flags.IsConst) {
|
|
986 S += "const ";
|
|
987 }
|
|
988 if (Type->getValueAsBit("IsVolatile") || Flags.IsVolatile) {
|
|
989 S += "volatile ";
|
|
990 }
|
|
991
|
|
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");
|
|
1000 S += " ";
|
|
1001 };
|
|
1002 if (Flags.IsPointer) {
|
|
1003 PrintAddrSpace(Flags.AddrSpace);
|
|
1004 } else if (Type->getValueAsBit("IsPointer")) {
|
|
1005 PrintAddrSpace(Type->getValueAsString("AddrSpace"));
|
|
1006 }
|
|
1007
|
|
1008 StringRef Acc = Type->getValueAsString("AccessQualifier");
|
|
1009 if (Acc != "") {
|
|
1010 S += StringSwitch<const char *>(Acc)
|
|
1011 .Case("RO", "__read_only ")
|
|
1012 .Case("WO", "__write_only ")
|
|
1013 .Case("RW", "__read_write ");
|
|
1014 }
|
|
1015
|
|
1016 S += Type->getValueAsString("Name").str();
|
|
1017 if (VectorSize > 1) {
|
|
1018 S += std::to_string(VectorSize);
|
|
1019 }
|
|
1020
|
|
1021 if (Type->getValueAsBit("IsPointer") || Flags.IsPointer) {
|
|
1022 S += " *";
|
|
1023 }
|
|
1024
|
|
1025 return S;
|
|
1026 }
|
|
1027
|
236
|
1028 void OpenCLBuiltinFileEmitterBase::getTypeLists(
|
223
|
1029 Record *Type, TypeFlags &Flags, std::vector<Record *> &TypeList,
|
|
1030 std::vector<int64_t> &VectorList) const {
|
|
1031 bool isGenType = Type->isSubClassOf("GenericType");
|
|
1032 if (isGenType) {
|
|
1033 TypeList = Type->getValueAsDef("TypeList")->getValueAsListOfDefs("List");
|
|
1034 VectorList =
|
|
1035 Type->getValueAsDef("VectorList")->getValueAsListOfInts("List");
|
|
1036 return;
|
|
1037 }
|
|
1038
|
|
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
|
|
1046 // GenericType.
|
|
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);
|
|
1052 return;
|
|
1053 }
|
|
1054 }
|
|
1055
|
|
1056 // Not a GenericType, so just insert the single type.
|
|
1057 TypeList.push_back(Type);
|
|
1058 VectorList.push_back(Type->getValueAsInt("VecWidth"));
|
|
1059 }
|
|
1060
|
236
|
1061 void OpenCLBuiltinFileEmitterBase::expandTypesInSignature(
|
223
|
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;
|
|
1072 TypeFlags Flags;
|
|
1073
|
|
1074 getTypeLists(Arg, Flags, TypeList, VectorList);
|
|
1075
|
|
1076 // Insert the Cartesian product of the types and vector sizes.
|
|
1077 for (const auto &Vector : VectorList) {
|
|
1078 for (const auto &Type : TypeList) {
|
236
|
1079 std::string FullType = getTypeString(Type, Flags, Vector);
|
|
1080 ExpandedArg.push_back(FullType);
|
|
1081
|
|
1082 // If the type requires an extension, add a TypeExtMap entry mapping
|
|
1083 // the full type name to the extension.
|
|
1084 StringRef Ext =
|
|
1085 Type->getValueAsDef("Extension")->getValueAsString("ExtName");
|
|
1086 if (!Ext.empty() && TypeExtMap.find(FullType) == TypeExtMap.end()) {
|
|
1087 TypeExtMap.insert({FullType, Ext});
|
|
1088 }
|
223
|
1089 }
|
|
1090 }
|
|
1091 NumSignatures = std::max<unsigned>(NumSignatures, ExpandedArg.size());
|
|
1092 ExpandedGenTypes.push_back(ExpandedArg);
|
|
1093 }
|
|
1094
|
|
1095 // Now the total number of signatures is known. Populate the return list with
|
|
1096 // all signatures.
|
|
1097 for (unsigned I = 0; I < NumSignatures; I++) {
|
|
1098 SmallVector<std::string, 2> Args;
|
|
1099
|
|
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]);
|
|
1106 }
|
|
1107 Types.push_back(Args);
|
|
1108 }
|
|
1109 }
|
|
1110
|
236
|
1111 void OpenCLBuiltinFileEmitterBase::emitExtensionSetup() {
|
223
|
1112 OS << R"(
|
|
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
|
|
1120
|
|
1121 )";
|
236
|
1122 }
|
|
1123
|
|
1124 std::string
|
|
1125 OpenCLBuiltinFileEmitterBase::emitExtensionGuard(const Record *Builtin) {
|
|
1126 StringRef Extensions =
|
|
1127 Builtin->getValueAsDef("Extension")->getValueAsString("ExtName");
|
|
1128 if (Extensions.empty())
|
|
1129 return "";
|
|
1130
|
|
1131 OS << "#if";
|
|
1132
|
|
1133 SmallVector<StringRef, 2> ExtVec;
|
|
1134 Extensions.split(ExtVec, " ");
|
|
1135 bool isFirst = true;
|
|
1136 for (StringRef Ext : ExtVec) {
|
|
1137 if (!isFirst) {
|
|
1138 OS << " &&";
|
|
1139 }
|
|
1140 OS << " defined(" << Ext << ")";
|
|
1141 isFirst = false;
|
|
1142 }
|
|
1143 OS << "\n";
|
|
1144
|
|
1145 return "#endif // Extension\n";
|
|
1146 }
|
|
1147
|
|
1148 std::string
|
|
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);
|
|
1153 };
|
|
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);
|
|
1159 OS << "\n";
|
|
1160 OptionalEndif = "#endif // MinVersion\n" + OptionalEndif;
|
|
1161 }
|
|
1162 int MaxVersion = Builtin->getValueAsDef("MaxVersion")->getValueAsInt("ID");
|
|
1163 if (MaxVersion) {
|
|
1164 OS << "#if __OPENCL_C_VERSION__ < ";
|
|
1165 PrintOpenCLVersion(MaxVersion);
|
|
1166 OS << "\n";
|
|
1167 OptionalEndif = "#endif // MaxVersion\n" + OptionalEndif;
|
|
1168 }
|
|
1169 return OptionalEndif;
|
|
1170 }
|
|
1171
|
|
1172 StringRef OpenCLBuiltinFileEmitterBase::emitTypeExtensionGuards(
|
|
1173 const SmallVectorImpl<std::string> &Signature) {
|
|
1174 SmallSet<StringRef, 2> ExtSet;
|
|
1175
|
|
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) {
|
|
1184 ExtSet.insert(Ext);
|
|
1185 }
|
|
1186 }
|
|
1187 }
|
|
1188
|
|
1189 // Emit the #if only when at least one extension is required.
|
|
1190 if (ExtSet.empty())
|
|
1191 return "";
|
|
1192
|
|
1193 OS << "#if ";
|
|
1194 bool isFirst = true;
|
|
1195 for (const auto Ext : ExtSet) {
|
|
1196 if (!isFirst)
|
|
1197 OS << " && ";
|
|
1198 OS << "defined(" << Ext << ")";
|
|
1199 isFirst = false;
|
|
1200 }
|
|
1201 OS << "\n";
|
|
1202 return "#endif // TypeExtension\n";
|
|
1203 }
|
|
1204
|
|
1205 void OpenCLBuiltinTestEmitter::emit() {
|
|
1206 emitSourceFileHeader("OpenCL Builtin exhaustive testing", OS);
|
|
1207
|
|
1208 emitExtensionSetup();
|
223
|
1209
|
|
1210 // Ensure each test has a unique name by numbering them.
|
|
1211 unsigned TestID = 0;
|
|
1212
|
|
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");
|
|
1217
|
|
1218 SmallVector<SmallVector<std::string, 2>, 4> FTypes;
|
|
1219 expandTypesInSignature(B->getValueAsListOfDefs("Signature"), FTypes);
|
|
1220
|
|
1221 OS << "// Test " << Name << "\n";
|
236
|
1222
|
|
1223 std::string OptionalExtensionEndif = emitExtensionGuard(B);
|
|
1224 std::string OptionalVersionEndif = emitVersionGuard(B);
|
223
|
1225
|
|
1226 for (const auto &Signature : FTypes) {
|
236
|
1227 StringRef OptionalTypeExtEndif = emitTypeExtensionGuards(Signature);
|
|
1228
|
223
|
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++) {
|
|
1233 if (I != 1)
|
|
1234 OS << ", ";
|
|
1235 OS << Signature[I] << " arg" << I;
|
|
1236 }
|
|
1237 }
|
|
1238 OS << ") {\n";
|
|
1239
|
|
1240 // Emit function body.
|
|
1241 OS << " ";
|
|
1242 if (Signature[0] != "void") {
|
|
1243 OS << "return ";
|
|
1244 }
|
|
1245 OS << Name << "(";
|
|
1246 for (unsigned I = 1; I < Signature.size(); I++) {
|
|
1247 if (I != 1)
|
|
1248 OS << ", ";
|
|
1249 OS << "arg" << I;
|
|
1250 }
|
|
1251 OS << ");\n";
|
|
1252
|
|
1253 // End of function body.
|
|
1254 OS << "}\n";
|
236
|
1255 OS << OptionalTypeExtEndif;
|
223
|
1256 }
|
236
|
1257
|
|
1258 OS << OptionalVersionEndif;
|
|
1259 OS << OptionalExtensionEndif;
|
223
|
1260 }
|
|
1261 }
|
|
1262
|
150
|
1263 void clang::EmitClangOpenCLBuiltins(RecordKeeper &Records, raw_ostream &OS) {
|
|
1264 BuiltinNameEmitter NameChecker(Records, OS);
|
|
1265 NameChecker.Emit();
|
|
1266 }
|
223
|
1267
|
|
1268 void clang::EmitClangOpenCLBuiltinTests(RecordKeeper &Records,
|
|
1269 raw_ostream &OS) {
|
|
1270 OpenCLBuiltinTestEmitter TestFileGenerator(Records, OS);
|
|
1271 TestFileGenerator.emit();
|
|
1272 }
|